@origintrail-official/dkg-node-ui 10.0.17 → 10.0.19

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 (44) hide show
  1. package/dist/chain-cursor-stores.d.ts +17 -0
  2. package/dist/chain-cursor-stores.d.ts.map +1 -1
  3. package/dist/chain-cursor-stores.js +37 -0
  4. package/dist/chain-cursor-stores.js.map +1 -1
  5. package/dist/chain-event-log-store.d.ts +31 -0
  6. package/dist/chain-event-log-store.d.ts.map +1 -1
  7. package/dist/chain-event-log-store.js +87 -13
  8. package/dist/chain-event-log-store.js.map +1 -1
  9. package/dist/db.d.ts +1 -1
  10. package/dist/db.d.ts.map +1 -1
  11. package/dist/db.js +27 -1
  12. package/dist/db.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist-ui/assets/{3d-force-graph-DGF2sXeK.js → 3d-force-graph-CehOGxux.js} +1 -1
  18. package/dist-ui/assets/{ActivityFeed-DNatshHL.js → ActivityFeed-BE4MTD8M.js} +1 -1
  19. package/dist-ui/assets/{AgentHub-lOm96XuE.js → AgentHub-CT6UhLF2.js} +1 -1
  20. package/dist-ui/assets/{AgentProfilePage-BRtazufK.js → AgentProfilePage-ygi-GXKM.js} +1 -1
  21. package/dist-ui/assets/{ApproveWalletsModal-BMtRgndO.js → ApproveWalletsModal-YFfDrGth.js} +3 -3
  22. package/dist-ui/assets/{ContextGraphPrimitives-CBc6kvmp.js → ContextGraphPrimitives-Dh-w2D_i.js} +1 -1
  23. package/dist-ui/assets/{ConvictionDetailView-DOTYSm7p.js → ConvictionDetailView-CfRmqqDD.js} +2 -2
  24. package/dist-ui/assets/MemoryLayerView-DL0zLYAQ.js +2 -0
  25. package/dist-ui/assets/{MemoryStackView-Bol2eMyq.js → MemoryStackView-BsV_JnOe.js} +1 -1
  26. package/dist-ui/assets/{Network-B49IxpAj.js → Network-BkxRENe4.js} +1 -1
  27. package/dist-ui/assets/{OnChainProvenanceCard-BpUoHg4b.js → OnChainProvenanceCard-CnnkMMNI.js} +1 -1
  28. package/dist-ui/assets/{Operations-BCQ545Yk.js → Operations-BaWWLSUw.js} +1 -1
  29. package/dist-ui/assets/{ProjectView-BaQQSy8L.js → ProjectView-BJmZ5f62.js} +31 -31
  30. package/dist-ui/assets/{PublishingConviction-B5nWRsUP.js → PublishingConviction-CKB6JBYk.js} +2 -2
  31. package/dist-ui/assets/{Settings-DeZKX_Ry.js → Settings-DXGMPiJk.js} +1 -1
  32. package/dist-ui/assets/{browserWalletTransaction-B6wyaMOV.js → browserWalletTransaction-BdmrJpK1.js} +3 -3
  33. package/dist-ui/assets/{ccip-B_vQl40F.js → ccip-BNYiIkjs.js} +1 -1
  34. package/dist-ui/assets/{index-CT-LdpBE.js → index-DK8XzE3T.js} +92 -92
  35. package/dist-ui/assets/{index-DHd3qhAk.js → index-DOGXDQkQ.js} +3 -3
  36. package/dist-ui/assets/{jsonld-32FQRO67-BYu8pE-5.js → jsonld-32FQRO67-Ca-KnQfb.js} +2 -2
  37. package/dist-ui/assets/{jsonld-Crm5iwcE.js → jsonld-mRC9FbFR.js} +1 -1
  38. package/dist-ui/assets/{renderer-3d-2EVDZII7-C2z5aUgo.js → renderer-3d-2EVDZII7-AEMBPIY7.js} +2 -2
  39. package/dist-ui/assets/{shikiHighlighter-DW1fRfBU.js → shikiHighlighter-CUQ07vzt.js} +1 -1
  40. package/dist-ui/assets/{useEntityOnChainReceipt-0Ub24t6e.js → useEntityOnChainReceipt-C8NHlPPN.js} +1 -1
  41. package/dist-ui/assets/{useProjectActivity-CLza3psq.js → useProjectActivity-CVFCfbMj.js} +1 -1
  42. package/dist-ui/index.html +1 -1
  43. package/package.json +3 -3
  44. package/dist-ui/assets/MemoryLayerView-DDFI2ngR.js +0 -2
@@ -1,6 +1,6 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DHd3qhAk.js","assets/index-CT-LdpBE.js","assets/index-BLQUVvVz.css","assets/string-DtUow4KV.js"])))=>i.map(i=>d[i]);
2
- var _i=Object.defineProperty;var Ai=(e,t,n)=>t in e?_i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var xt=(e,t,n)=>Ai(e,typeof t!="symbol"?t+"":t,n);import{aO as s,bc as f,bF as ur,aF as Ri,q as un,aU as Ti,Q as Oi,aT as dr,bf as Ii,p as pr,be as hr,R as Ce,n as $t,bE as mr,_ as Pi,L as Oe,bB as fr,bM as zi,u as De,ak as Yt,r as Li,aE as gr,A as vr,i as Mi,t as Ie,b0 as Gn,bw as Bn,aQ as We,bG as Fi,bJ as br,by as ft,ai as Ui,X as Di,Y as Zi,a7 as cs,w as us,b4 as qi,J as dn,aR as Ht,ba as Xt,E as en,bb as yr,b2 as tn,f as Gi,bA as Bi,I as Wn,K as Vt,as as Wi,bL as Vn,S as jn,M as ds,l as ps,D as hs,bg as Vi,G as Qi,U as Ki,F as xr,aP as jr,O as wr,bP as Ji,af as Yi,aA as Hi,bi as ut,a_ as Xi,aG as ea,T as nt,a$ as kr,aY as Nr,P as ta,bq as na,br as sa,av as ra,m as Tn,o as ms,au as ia,a as aa,C as oa,bx as la,bD as ca,s as ua,b as da,bj as pa}from"./index-CT-LdpBE.js";import{e as Qn,R as Ve,h as et,f as It,a as gt,p as Nt,C as Xe,i as ha,c as nn,q as ma,d as fa,U as sn,g as ga,u as va,P as ba,b as ya,A as xa}from"./ActivityFeed-DNatshHL.js";import{E as xe,t as At,S as pn}from"./ContextGraphPrimitives-CBc6kvmp.js";import{t as ja}from"./truncate-BaiMkAOo.js";import{b as wa,u as ka,a as fs,t as dt}from"./useEntityOnChainReceipt-0Ub24t6e.js";import"./useProjectActivity-CLza3psq.js";function Na(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const t=e/100;return`${t.toFixed(t%1===0?0:1)}%`}const Sa={eligible:{glyph:"◉",toneClass:"v10-pca-verdict-green"},fallthrough:{glyph:"⚠",toneClass:"v10-pca-verdict-amber"},"fallthrough-no-funds":{glyph:"⚠",toneClass:"v10-pca-verdict-danger"},unknown:{glyph:"◌",toneClass:"v10-pca-verdict-neutral"}};function Ca({verdict:e,accountId:t,discountBps:n,accountUntracked:r=!1,reasons:i=[],ownerPublish:a=!1,variant:o="banner",children:l,className:c=""}){const d=Sa[e],g=e==="fallthrough"||e==="fallthrough-no-funds",h=g?"alert":"status",u=g?"assertive":"polite",p=t?`PCA #${t}`:"a PCA",v=r?" (not tracked by this node)":"",y=Na(n),w=" unless this graph’s registration escrow already covers it",m=i.length>0?` Reason: ${i.join("; ")}.`:"";if(o==="chip"){const x=e==="eligible"?`Funded by ${p}${v}${y?` (${y} discount)`:""}`:e==="fallthrough"?"⚠ No PCA discount":e==="fallthrough-no-funds"?"⚠ Publish will fail":"PCA status unknown";return s.jsx("span",{className:["v10-pca-verdict-chip",d.toneClass,c].filter(Boolean).join(" "),"data-testid":"pca-eligibility-chip","data-verdict":e,children:s.jsx("span",{className:"v10-pca-verdict-chip-label",role:h,"aria-live":u,children:x})})}let b;return e==="eligible"?b=s.jsxs(s.Fragment,{children:["This publish will use ",p,v,y?` (${y} discount)`:"",".",a?`${w}.`:""]}):e==="fallthrough"?b=s.jsxs(s.Fragment,{children:["No PCA discount on this publish — it will attempt to pay the direct cost from the signing wallet’s TRAC",y?`, forfeiting ${p}’s ${y} discount`:"",a?w:"","; the publish fails if that TRAC is below the fee.",m]}):e==="fallthrough-no-funds"?b=s.jsxs(s.Fragment,{children:["This publish will FAIL — no signing wallet can cover it",y?`, forfeiting ${p}’s ${y} discount`:"",a?w:"",".",m]}):b=s.jsx(s.Fragment,{children:"Couldn’t confirm PCA eligibility — you may pay the direct cost."}),s.jsxs("div",{className:["v10-pca-verdict-banner",d.toneClass,c].filter(Boolean).join(" "),"data-testid":"pca-eligibility-verdict","data-verdict":e,role:h,"aria-live":u,children:[s.jsxs("p",{className:"v10-pca-verdict-message",children:[s.jsx("span",{className:"v10-pca-verdict-glyph","aria-hidden":"true",children:d.glyph}),b]}),l&&s.jsx("div",{className:"v10-pca-verdict-actions",children:l})]})}const $a=".md, .docx, .pdf, .txt, .csv, .json, .ttl, .rdf, .owl, .py, .ts, .js, .tsx, .jsx, .java, .go, .rs, .c, .cpp, .html, .xml, .yaml, .yml";function gs(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Ea(e){var n;const t=((n=e.split(".").pop())==null?void 0:n.toLowerCase())??"";return["md","txt"].includes(t)?"📝":["pdf"].includes(t)?"📕":["docx","doc"].includes(t)?"📄":["csv","json","xml","yaml","yml"].includes(t)?"📊":["ttl","rdf","owl"].includes(t)?"🔗":["py","ts","js","tsx","jsx","java","go","rs","c","cpp"].includes(t)?"💻":["png","jpg","jpeg","webp"].includes(t)?"🖼️":"📄"}function _a({open:e,onClose:t,contextGraphId:n,contextGraphName:r}){var L;const[i,a]=f.useState([]),[o,l]=f.useState(!0),[c,d]=f.useState(!0),[g,h]=f.useState("idle"),[u,p]=f.useState(0),[v,y]=f.useState([]),[w,m]=f.useState(null),[b,x]=f.useState(!1),k=f.useRef(null),S=f.useCallback(A=>{const M=Array.from(A);a(F=>{const B=new Set(F.map(X=>`${X.file.name}:${X.file.size}`)),J=M.filter(X=>!B.has(`${X.name}:${X.size}`));return[...F,...J.map(X=>({file:X,id:`${X.name}-${X.size}-${Date.now()}`}))]})},[]),j=A=>{a(M=>M.filter(F=>F.id!==A))},_=A=>{A.preventDefault(),A.stopPropagation(),x(!0)},z=A=>{A.preventDefault(),A.stopPropagation(),x(!1)},E=A=>{A.preventDefault(),A.stopPropagation(),x(!1),A.dataTransfer.files.length>0&&S(A.dataTransfer.files)},T=async()=>{if(i.length===0)return;h("uploading"),p(0),y([]),m(null);const A=[];for(let F=0;F<i.length;F++){p(F);const{file:B}=i[F],J=B.name.replace(/[^a-zA-Z0-9._-]/g,"_"),X=`${Date.now().toString(36)}-${F}-${J}`;try{const H=await Ri(X,n,B),V=H.extraction.tripleCount??H.extraction.triplesWritten;A.push({fileName:B.name,status:H.extraction.status==="completed"?"success":H.extraction.status==="skipped"?"skipped":"error",triplesWritten:V,error:H.extraction.error})}catch(H){A.push({fileName:B.name,status:"error",error:(H==null?void 0:H.message)??"Upload failed"})}}y(A),p(i.length);const M=A.some(F=>F.status==="error");h(M?"error":"done")},$=()=>{g!=="uploading"&&(a([]),y([]),h("idle"),m(null),p(0),t())},{dialogRef:O,onBackdropClick:Z}=ur(e,$);if(!e)return null;const C=v.reduce((A,M)=>A+(M.triplesWritten??0),0),R=v.filter(A=>A.status==="success").length,G=v.filter(A=>A.status==="skipped").length,P=v.filter(A=>A.status==="error").length;return s.jsx("div",{className:"v10-modal-overlay",onClick:Z,role:"presentation",children:s.jsxs("div",{className:"v10-modal-box",style:{maxWidth:560},ref:O,role:"dialog","aria-modal":"true","aria-labelledby":"dkg-import-modal-title",children:[s.jsxs("div",{className:"v10-modal-header",style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{id:"dkg-import-modal-title",className:"v10-modal-title",children:"Import to Working Memory"}),s.jsx("div",{className:"v10-modal-subtitle",children:r?s.jsxs(s.Fragment,{children:["Upload files to ",s.jsx("strong",{children:r})," — your agent will extract structured knowledge."]}):s.jsx(s.Fragment,{children:"Upload files — your agent will extract structured knowledge and add it to working memory."})})]}),s.jsx("button",{type:"button",className:"v10-modal-close",onClick:$,disabled:g==="uploading","aria-label":"Close import dialog",title:"Close (Esc)",style:{flexShrink:0,cursor:g==="uploading"?"not-allowed":"pointer"},children:"×"})]}),s.jsxs("div",{className:"v10-modal-body",children:[w&&s.jsx("div",{className:"v10-modal-error",children:w}),g==="idle"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`v10-import-dropzone ${b?"drag-over":""}`,onClick:()=>{var A;return(A=k.current)==null?void 0:A.click()},onDragOver:_,onDragLeave:z,onDrop:E,children:[s.jsx("div",{className:"v10-import-dropzone-label",children:"Drag files here, or click to browse"}),s.jsx("div",{className:"v10-import-dropzone-hint",style:{marginTop:4},children:"Your agent will extract structured knowledge and add it to working memory."}),s.jsxs("div",{className:"v10-import-dropzone-hint",style:{marginTop:8},children:["Supported: ",$a]}),s.jsx("input",{ref:k,type:"file",multiple:!0,style:{display:"none"},onChange:A=>{A.target.files&&S(A.target.files),A.target.value=""}})]}),i.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"v10-import-file-list",children:i.map(A=>s.jsxs("div",{className:"v10-import-file-item",children:[s.jsx("span",{className:"v10-import-file-icon",children:Ea(A.file.name)}),s.jsx("span",{className:"v10-import-file-name",children:A.file.name}),s.jsx("span",{className:"v10-import-file-size",children:gs(A.file.size)}),s.jsx("button",{className:"v10-import-file-remove",onClick:()=>j(A.id),title:"Remove",children:"×"})]},A.id))}),s.jsxs("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginBottom:12},children:[i.length," file",i.length!==1?"s":""," selected · ",gs(i.reduce((A,M)=>A+M.file.size,0))," total"]})]}),s.jsx("div",{className:"v10-form-divider"}),s.jsxs("div",{className:"v10-form-label",style:{marginBottom:8},children:["Ingestion Options ",s.jsx("span",{style:{fontSize:10,fontWeight:400,color:"var(--text-tertiary)"},children:"(coming soon)"})]}),s.jsxs("label",{className:"v10-import-option",style:{opacity:.5,pointerEvents:"none"},children:[s.jsx("input",{type:"checkbox",checked:c,disabled:!0,readOnly:!0}),"Store original files as Knowledge Assets"]}),s.jsxs("label",{className:"v10-import-option",style:{opacity:.5,pointerEvents:"none"},children:[s.jsx("input",{type:"checkbox",checked:o,disabled:!0,readOnly:!0}),"Let agent extract structured knowledge from content"]})]}),g==="uploading"&&s.jsxs("div",{className:"v10-import-progress",children:[s.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary)",fontWeight:500},children:["Importing files… (",u+1," of ",i.length,")"]}),s.jsx("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginTop:4},children:((L=i[u])==null?void 0:L.file.name)??"…"}),s.jsx("div",{className:"v10-import-progress-bar",children:s.jsx("div",{className:"v10-import-progress-fill",style:{width:`${(u+.5)/i.length*100}%`}})}),s.jsxs("div",{className:"v10-import-progress-text",children:[u," of ",i.length," files processed"]})]}),(g==="done"||g==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`v10-import-result ${P>0?"error":"success"}`,"data-testid":"import-result","data-import-status":P>0?"error":"success","data-import-triples":C,children:P===0?s.jsxs(s.Fragment,{children:[R>0&&s.jsxs(s.Fragment,{children:["Successfully imported ",R," file",R!==1?"s":"",".",C>0&&s.jsxs(s.Fragment,{children:[" Extracted ",s.jsx("strong",{children:C.toLocaleString()})," triples into working memory."]})]}),G>0&&s.jsxs(s.Fragment,{children:[R>0?" ":"","Stored ",G," file",G!==1?"s":""," as source — no structured knowledge was extracted yet (extraction for these file types is coming soon)."]})]}):s.jsxs(s.Fragment,{children:[R," file",R!==1?"s":""," imported",G>0&&s.jsxs(s.Fragment,{children:[", ",G," stored without extraction"]}),", ",P," failed.",C>0&&s.jsxs(s.Fragment,{children:[" ",C.toLocaleString()," triples extracted."]})]})}),v.length>0&&s.jsx("div",{className:"v10-import-file-list",style:{marginTop:12},children:v.map((A,M)=>s.jsxs("div",{className:"v10-import-file-item",children:[s.jsx("span",{className:"v10-import-file-icon",children:A.status==="success"?"✓":A.status==="skipped"?"–":"✗"}),s.jsx("span",{className:"v10-import-file-name",children:A.fileName}),s.jsx("span",{className:"v10-import-file-size",style:A.status==="error"?{color:"var(--text-danger)"}:void 0,children:A.status==="success"&&A.triplesWritten!=null?`${A.triplesWritten} triples`:A.status==="skipped"?"stored (no extraction)":A.error??"failed"})]},M))})]})]}),s.jsxs("div",{className:"v10-modal-footer",children:[g==="idle"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"v10-modal-btn",onClick:$,children:"Cancel"}),s.jsxs("button",{className:"v10-modal-btn primary",onClick:T,disabled:i.length===0,children:["Start Import (",i.length," file",i.length!==1?"s":"",")"]})]}),g==="uploading"&&s.jsx("button",{className:"v10-modal-btn",disabled:!0,children:"Importing…"}),(g==="done"||g==="error")&&s.jsx("button",{className:"v10-modal-btn primary",onClick:$,children:"Done"})]})]})})}function Aa(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Ra({open:e,onClose:t,contextGraphId:n,contextGraphName:r}){const[i,a]=f.useState(null),[o,l]=f.useState(null),[c,d]=f.useState([]),[g,h]=f.useState(null),[u,p]=f.useState([]),[v,y]=f.useState([]),[w,m]=f.useState(null),[b,x]=f.useState("allowlist");f.useEffect(()=>{e&&(fetch("/api/status",{headers:un()}).then($=>$.json()).then($=>{typeof($==null?void 0:$.peerId)=="string"&&$.peerId.length>0&&l($.peerId)}).catch(()=>{}),Ti(n).then($=>d($.allowedAgents)).catch(()=>d([])),Oi().then($=>{const O=($.agents??[]).filter(Z=>Z.connectionStatus!=="self");p(O)}).catch(()=>p([])),dr(n).then($=>y($.requests)).catch(()=>y([])))},[e,n]);const{dialogRef:k,onBackdropClick:S}=ur(e,t);if(!e)return null;const j=o?`${n}
3
- ${o}`:null,_=($,O)=>{navigator.clipboard.writeText($).then(()=>{a(O),setTimeout(()=>a(null),2e3)}).catch(()=>{})},z=async $=>{try{await Ii(n,$),d(O=>O.filter(Z=>Z!==$))}catch{}},E=async $=>{m($);try{await pr(n,$),y(O=>O.filter(Z=>Z.agentAddress!==$)),d(O=>[...new Set([...O,$])])}catch(O){h((O==null?void 0:O.message)||"Failed to approve")}finally{m(null)}},T=async $=>{m($);try{await hr(n,$),y(O=>O.filter(Z=>Z.agentAddress!==$))}catch(O){h((O==null?void 0:O.message)||"Failed to reject")}finally{m(null)}};return s.jsx("div",{className:"v10-modal-overlay",onClick:S,role:"presentation",children:s.jsxs("div",{className:"v10-modal-box",style:{maxWidth:560},ref:k,role:"dialog","aria-modal":"true","aria-labelledby":"dkg-share-modal-title",children:[s.jsxs("div",{className:"v10-modal-header",style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{id:"dkg-share-modal-title",className:"v10-modal-title",children:"Share Context Graph"}),s.jsxs("div",{className:"v10-modal-subtitle",children:["Invite agents to collaborate on ",s.jsx("strong",{children:r}),"."]})]}),s.jsx("button",{type:"button",className:"v10-modal-close",onClick:t,"aria-label":"Close share dialog",title:"Close (Esc)",style:{flexShrink:0,cursor:"pointer"},children:"×"})]}),s.jsxs("div",{className:"v10-modal-body",children:[s.jsxs("div",{style:{display:"flex",gap:0,marginBottom:16,borderBottom:"1px solid var(--border-default)"},children:[s.jsx("button",{onClick:()=>x("allowlist"),style:{padding:"8px 16px",fontSize:12,fontWeight:b==="allowlist"?600:400,background:"none",border:"none",cursor:"pointer",color:b==="allowlist"?"var(--text-primary)":"var(--text-tertiary)",borderBottom:b==="allowlist"?"2px solid var(--accent-primary)":"2px solid transparent"},children:"Allowlist"}),s.jsxs("button",{onClick:()=>x("requests"),style:{padding:"8px 16px",fontSize:12,fontWeight:b==="requests"?600:400,background:"none",border:"none",cursor:"pointer",color:b==="requests"?"var(--text-primary)":"var(--text-tertiary)",borderBottom:b==="requests"?"2px solid var(--accent-primary)":"2px solid transparent",position:"relative"},children:["Join Requests",v.length>0&&s.jsx("span",{style:{position:"absolute",top:4,right:4,background:"var(--accent-red, #ef4444)",color:"var(--text-on-accent)",borderRadius:999,fontSize:9,fontWeight:700,padding:"1px 5px",minWidth:16,textAlign:"center"},children:v.length})]})]}),b==="allowlist"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"v10-form-group",children:[s.jsx("label",{className:"v10-form-label",children:"Allowed Agents"}),s.jsxs("div",{style:{fontSize:10,color:"var(--text-tertiary)",marginBottom:8},children:["Only agents on this list can read and write to the context graph. To add someone, share the Invite Code below — they'll send a signed join request you can approve in the ",s.jsx("strong",{children:"Join Requests"})," tab."]}),c.length>0&&s.jsx("div",{style:{marginBottom:8,display:"flex",flexDirection:"column",gap:4},children:c.map($=>{const O=u.find(Z=>{var C;return((C=Z.agentAddress)==null?void 0:C.toLowerCase())===$.toLowerCase()});return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 10px",borderRadius:6,fontSize:11,fontFamily:"var(--font-mono)",background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[s.jsx("span",{style:{color:"var(--text-primary)"},children:O?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontFamily:"var(--font-body)",fontWeight:500},children:O.name})," ",s.jsx("span",{style:{color:"var(--text-tertiary)",fontSize:10},children:Aa($)})]}):$}),s.jsx("button",{onClick:()=>z($),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-tertiary)",fontSize:12,padding:"0 4px"},title:"Remove agent",children:"×"})]},$)})}),c.length===0&&s.jsx("div",{style:{padding:"8px 12px",borderRadius:6,fontSize:11,color:"var(--text-tertiary)",background:"var(--bg-surface)",border:"1px dashed var(--border-default)",marginBottom:8},children:"No agents on allowlist — context graph is open to anyone who subscribes."})]}),s.jsx("div",{className:"v10-form-divider"}),s.jsxs("div",{className:"v10-form-group",children:[s.jsx("label",{className:"v10-form-label",children:"Invite Code"}),j===null?s.jsx("div",{style:{padding:"8px 12px",borderRadius:6,fontSize:11,color:"var(--text-tertiary)",background:"var(--bg-surface)",border:"1px dashed var(--border-default)"},children:"Loading peer ID…"}):s.jsxs("div",{style:{position:"relative"},children:[s.jsx("pre",{style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:6,padding:"10px 12px",fontSize:11,lineHeight:1.6,fontFamily:"var(--font-mono)",color:"var(--text-primary)",overflow:"auto",margin:0,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:j}),s.jsx("button",{className:"v10-modal-btn primary",onClick:()=>_(j,"invite"),style:{position:"absolute",top:6,right:6,fontSize:10,padding:"4px 10px",height:26,cursor:"pointer"},children:i==="invite"?"Copied":"Copy Invite"})]})]})]}),b==="requests"&&s.jsxs("div",{className:"v10-form-group",children:[s.jsx("label",{className:"v10-form-label",children:"Pending Join Requests"}),s.jsx("div",{style:{fontSize:10,color:"var(--text-tertiary)",marginBottom:8},children:"Agents who submitted a signed request to join this context graph. Approve to add them to the allowlist."}),v.length===0&&s.jsx("div",{style:{padding:"16px 12px",borderRadius:6,fontSize:11,textAlign:"center",color:"var(--text-tertiary)",background:"var(--bg-surface)",border:"1px dashed var(--border-default)"},children:"No pending join requests."}),v.map($=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 10px",borderRadius:6,fontSize:11,background:"var(--bg-surface)",border:"1px solid var(--border-default)",marginBottom:4},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[$.name&&s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:500},children:$.name}),s.jsx("span",{style:{color:"var(--text-tertiary)",fontFamily:"var(--font-mono)",fontSize:10},children:$.agentAddress}),s.jsxs("span",{style:{fontSize:9,color:"var(--text-tertiary)"},children:["Requested ",new Date($.timestamp).toLocaleString()]})]}),s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{onClick:()=>E($.agentAddress),disabled:w===$.agentAddress,style:{background:"rgba(34, 197, 94, 0.15)",color:"var(--text-success)",border:"1px solid rgba(34, 197, 94, 0.3)",cursor:"pointer",borderRadius:4,fontSize:10,padding:"4px 10px",fontWeight:600},children:w===$.agentAddress?"…":"Approve"}),s.jsx("button",{onClick:()=>T($.agentAddress),disabled:w===$.agentAddress,style:{background:"rgba(239, 68, 68, 0.1)",color:"var(--text-danger)",border:"1px solid rgba(239, 68, 68, 0.2)",cursor:"pointer",borderRadius:4,fontSize:10,padding:"4px 10px",fontWeight:600},children:"Reject"})]})]},$.agentAddress)),g&&s.jsx("div",{style:{fontSize:10,color:"var(--text-danger)",marginTop:4},children:g})]})]}),s.jsx("div",{className:"v10-modal-footer",children:s.jsx("button",{className:"v10-modal-btn",onClick:t,children:"Done"})})]})})}const St=["#6366f1","#14b8a6","#f43f5e","#facc15","#8b5cf6","#10b981","#0ea5e9","#d946ef"],vs=1e4;function jt(e){if(e!=null)return typeof e=="string"?e.startsWith('"')?e.replace(/^"/,"").replace(/"(\^\^<[^>]*>)?$/,""):e:typeof e=="object"&&e!==null&&"value"in e?String(e.value):String(e)}function Ta(e){if(e.startsWith("did:dkg:agent:")){const t=e.slice(14);return t.startsWith("0x")?t.slice(0,6)+"…"+t.slice(-4):t.slice(0,6)+"…"+t.slice(-6)}return e.length>18?e.slice(0,8)+"…"+e.slice(-6):e}function Oa(e){return e.startsWith("did:")||e.startsWith("12D3")?e:/^0x[0-9a-fA-F]{40}$/.test(e)?`did:dkg:agent:${e}`:e}function Ia(e,t){const n=`did:dkg:context-graph:${t}/`;if(!e.startsWith(n))return;const r=e.slice(n.length),i=r.indexOf("/");if(i<0)return;const a=r.slice(0,i);if(!(!a||a.startsWith("_")))return a}function Pa(e){return`PREFIX dkg: <http://dkg.io/ontology/>
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DOGXDQkQ.js","assets/index-DK8XzE3T.js","assets/index-BLQUVvVz.css","assets/string-DtUow4KV.js"])))=>i.map(i=>d[i]);
2
+ var Ai=Object.defineProperty;var Ti=(e,t,n)=>t in e?Ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var xt=(e,t,n)=>Ti(e,typeof t!="symbol"?t+"":t,n);import{aO as s,bd as f,bG as ur,aF as Ri,q as un,aU as Oi,Q as Ii,aT as dr,bg as Pi,p as pr,bf as hr,R as Ce,n as $t,bF as mr,_ as zi,L as Oe,bC as fr,bN as Li,u as De,ak as Ht,r as Mi,aE as gr,A as vr,i as Fi,t as Ie,b0 as Gn,bx as Bn,aQ as We,bH as Ui,bK as br,bz as ft,ai as Di,X as Zi,Y as qi,a7 as cs,w as us,b5 as Gi,J as dn,aR as Yt,bb as Xt,E as en,bc as yr,b2 as xr,b3 as tn,f as Bi,bB as Wi,I as Wn,K as Vt,as as Vi,bM as Vn,S as jn,M as ds,l as ps,D as hs,bh as Qi,G as Ki,U as Ji,F as jr,aP as wr,O as kr,bQ as Hi,af as Yi,aA as Xi,bj as ut,a_ as ea,aG as ta,T as nt,a$ as Nr,aY as Sr,P as na,br as sa,bs as ra,av as ia,m as Rn,o as ms,au as aa,a as oa,C as la,by as ca,bE as ua,s as da,b as pa,bk as ha}from"./index-DK8XzE3T.js";import{e as Qn,R as Ve,h as et,f as It,a as gt,p as Nt,C as Xe,i as ma,c as nn,q as fa,d as ga,U as sn,g as va,u as ba,P as ya,b as xa,A as ja}from"./ActivityFeed-BE4MTD8M.js";import{E as xe,t as At,S as pn}from"./ContextGraphPrimitives-Dh-w2D_i.js";import{t as wa}from"./truncate-BaiMkAOo.js";import{b as ka,u as Na,a as fs,t as dt}from"./useEntityOnChainReceipt-C8NHlPPN.js";import"./useProjectActivity-CVFCfbMj.js";function Sa(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const t=e/100;return`${t.toFixed(t%1===0?0:1)}%`}const Ca={eligible:{glyph:"◉",toneClass:"v10-pca-verdict-green"},fallthrough:{glyph:"⚠",toneClass:"v10-pca-verdict-amber"},"fallthrough-no-funds":{glyph:"⚠",toneClass:"v10-pca-verdict-danger"},unknown:{glyph:"◌",toneClass:"v10-pca-verdict-neutral"}};function $a({verdict:e,accountId:t,discountBps:n,accountUntracked:r=!1,reasons:i=[],ownerPublish:a=!1,variant:o="banner",children:l,className:c=""}){const d=Ca[e],g=e==="fallthrough"||e==="fallthrough-no-funds",h=g?"alert":"status",u=g?"assertive":"polite",p=t?`PCA #${t}`:"a PCA",v=r?" (not tracked by this node)":"",y=Sa(n),w=" unless this graph’s registration escrow already covers it",m=i.length>0?` Reason: ${i.join("; ")}.`:"";if(o==="chip"){const x=e==="eligible"?`Funded by ${p}${v}${y?` (${y} discount)`:""}`:e==="fallthrough"?"⚠ No PCA discount":e==="fallthrough-no-funds"?"⚠ Publish will fail":"PCA status unknown";return s.jsx("span",{className:["v10-pca-verdict-chip",d.toneClass,c].filter(Boolean).join(" "),"data-testid":"pca-eligibility-chip","data-verdict":e,children:s.jsx("span",{className:"v10-pca-verdict-chip-label",role:h,"aria-live":u,children:x})})}let b;return e==="eligible"?b=s.jsxs(s.Fragment,{children:["This publish will use ",p,v,y?` (${y} discount)`:"",".",a?`${w}.`:""]}):e==="fallthrough"?b=s.jsxs(s.Fragment,{children:["No PCA discount on this publish — it will attempt to pay the direct cost from the signing wallet’s TRAC",y?`, forfeiting ${p}’s ${y} discount`:"",a?w:"","; the publish fails if that TRAC is below the fee.",m]}):e==="fallthrough-no-funds"?b=s.jsxs(s.Fragment,{children:["This publish will FAIL — no signing wallet can cover it",y?`, forfeiting ${p}’s ${y} discount`:"",a?w:"",".",m]}):b=s.jsx(s.Fragment,{children:"Couldn’t confirm PCA eligibility — you may pay the direct cost."}),s.jsxs("div",{className:["v10-pca-verdict-banner",d.toneClass,c].filter(Boolean).join(" "),"data-testid":"pca-eligibility-verdict","data-verdict":e,role:h,"aria-live":u,children:[s.jsxs("p",{className:"v10-pca-verdict-message",children:[s.jsx("span",{className:"v10-pca-verdict-glyph","aria-hidden":"true",children:d.glyph}),b]}),l&&s.jsx("div",{className:"v10-pca-verdict-actions",children:l})]})}const Ea=".md, .docx, .pdf, .txt, .csv, .json, .ttl, .rdf, .owl, .py, .ts, .js, .tsx, .jsx, .java, .go, .rs, .c, .cpp, .html, .xml, .yaml, .yml";function gs(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function _a(e){var n;const t=((n=e.split(".").pop())==null?void 0:n.toLowerCase())??"";return["md","txt"].includes(t)?"📝":["pdf"].includes(t)?"📕":["docx","doc"].includes(t)?"📄":["csv","json","xml","yaml","yml"].includes(t)?"📊":["ttl","rdf","owl"].includes(t)?"🔗":["py","ts","js","tsx","jsx","java","go","rs","c","cpp"].includes(t)?"💻":["png","jpg","jpeg","webp"].includes(t)?"🖼️":"📄"}function Aa({open:e,onClose:t,contextGraphId:n,contextGraphName:r}){var L;const[i,a]=f.useState([]),[o,l]=f.useState(!0),[c,d]=f.useState(!0),[g,h]=f.useState("idle"),[u,p]=f.useState(0),[v,y]=f.useState([]),[w,m]=f.useState(null),[b,x]=f.useState(!1),k=f.useRef(null),N=f.useCallback(A=>{const M=Array.from(A);a(F=>{const B=new Set(F.map(X=>`${X.file.name}:${X.file.size}`)),J=M.filter(X=>!B.has(`${X.name}:${X.size}`));return[...F,...J.map(X=>({file:X,id:`${X.name}-${X.size}-${Date.now()}`}))]})},[]),j=A=>{a(M=>M.filter(F=>F.id!==A))},_=A=>{A.preventDefault(),A.stopPropagation(),x(!0)},z=A=>{A.preventDefault(),A.stopPropagation(),x(!1)},E=A=>{A.preventDefault(),A.stopPropagation(),x(!1),A.dataTransfer.files.length>0&&N(A.dataTransfer.files)},T=async()=>{if(i.length===0)return;h("uploading"),p(0),y([]),m(null);const A=[];for(let F=0;F<i.length;F++){p(F);const{file:B}=i[F],J=B.name.replace(/[^a-zA-Z0-9._-]/g,"_"),X=`${Date.now().toString(36)}-${F}-${J}`;try{const Y=await Ri(X,n,B),V=Y.extraction.tripleCount??Y.extraction.triplesWritten;A.push({fileName:B.name,status:Y.extraction.status==="completed"?"success":Y.extraction.status==="skipped"?"skipped":"error",triplesWritten:V,error:Y.extraction.error})}catch(Y){A.push({fileName:B.name,status:"error",error:(Y==null?void 0:Y.message)??"Upload failed"})}}y(A),p(i.length);const M=A.some(F=>F.status==="error");h(M?"error":"done")},C=()=>{g!=="uploading"&&(a([]),y([]),h("idle"),m(null),p(0),t())},{dialogRef:O,onBackdropClick:Z}=ur(e,C);if(!e)return null;const $=v.reduce((A,M)=>A+(M.triplesWritten??0),0),R=v.filter(A=>A.status==="success").length,G=v.filter(A=>A.status==="skipped").length,P=v.filter(A=>A.status==="error").length;return s.jsx("div",{className:"v10-modal-overlay",onClick:Z,role:"presentation",children:s.jsxs("div",{className:"v10-modal-box",style:{maxWidth:560},ref:O,role:"dialog","aria-modal":"true","aria-labelledby":"dkg-import-modal-title",children:[s.jsxs("div",{className:"v10-modal-header",style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{id:"dkg-import-modal-title",className:"v10-modal-title",children:"Import to Working Memory"}),s.jsx("div",{className:"v10-modal-subtitle",children:r?s.jsxs(s.Fragment,{children:["Upload files to ",s.jsx("strong",{children:r})," — your agent will extract structured knowledge."]}):s.jsx(s.Fragment,{children:"Upload files — your agent will extract structured knowledge and add it to working memory."})})]}),s.jsx("button",{type:"button",className:"v10-modal-close",onClick:C,disabled:g==="uploading","aria-label":"Close import dialog",title:"Close (Esc)",style:{flexShrink:0,cursor:g==="uploading"?"not-allowed":"pointer"},children:"×"})]}),s.jsxs("div",{className:"v10-modal-body",children:[w&&s.jsx("div",{className:"v10-modal-error",children:w}),g==="idle"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`v10-import-dropzone ${b?"drag-over":""}`,onClick:()=>{var A;return(A=k.current)==null?void 0:A.click()},onDragOver:_,onDragLeave:z,onDrop:E,children:[s.jsx("div",{className:"v10-import-dropzone-label",children:"Drag files here, or click to browse"}),s.jsx("div",{className:"v10-import-dropzone-hint",style:{marginTop:4},children:"Your agent will extract structured knowledge and add it to working memory."}),s.jsxs("div",{className:"v10-import-dropzone-hint",style:{marginTop:8},children:["Supported: ",Ea]}),s.jsx("input",{ref:k,type:"file",multiple:!0,style:{display:"none"},onChange:A=>{A.target.files&&N(A.target.files),A.target.value=""}})]}),i.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"v10-import-file-list",children:i.map(A=>s.jsxs("div",{className:"v10-import-file-item",children:[s.jsx("span",{className:"v10-import-file-icon",children:_a(A.file.name)}),s.jsx("span",{className:"v10-import-file-name",children:A.file.name}),s.jsx("span",{className:"v10-import-file-size",children:gs(A.file.size)}),s.jsx("button",{className:"v10-import-file-remove",onClick:()=>j(A.id),title:"Remove",children:"×"})]},A.id))}),s.jsxs("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginBottom:12},children:[i.length," file",i.length!==1?"s":""," selected · ",gs(i.reduce((A,M)=>A+M.file.size,0))," total"]})]}),s.jsx("div",{className:"v10-form-divider"}),s.jsxs("div",{className:"v10-form-label",style:{marginBottom:8},children:["Ingestion Options ",s.jsx("span",{style:{fontSize:10,fontWeight:400,color:"var(--text-tertiary)"},children:"(coming soon)"})]}),s.jsxs("label",{className:"v10-import-option",style:{opacity:.5,pointerEvents:"none"},children:[s.jsx("input",{type:"checkbox",checked:c,disabled:!0,readOnly:!0}),"Store original files as Knowledge Assets"]}),s.jsxs("label",{className:"v10-import-option",style:{opacity:.5,pointerEvents:"none"},children:[s.jsx("input",{type:"checkbox",checked:o,disabled:!0,readOnly:!0}),"Let agent extract structured knowledge from content"]})]}),g==="uploading"&&s.jsxs("div",{className:"v10-import-progress",children:[s.jsxs("div",{style:{fontSize:12,color:"var(--text-secondary)",fontWeight:500},children:["Importing files… (",u+1," of ",i.length,")"]}),s.jsx("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginTop:4},children:((L=i[u])==null?void 0:L.file.name)??"…"}),s.jsx("div",{className:"v10-import-progress-bar",children:s.jsx("div",{className:"v10-import-progress-fill",style:{width:`${(u+.5)/i.length*100}%`}})}),s.jsxs("div",{className:"v10-import-progress-text",children:[u," of ",i.length," files processed"]})]}),(g==="done"||g==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`v10-import-result ${P>0?"error":"success"}`,"data-testid":"import-result","data-import-status":P>0?"error":"success","data-import-triples":$,children:P===0?s.jsxs(s.Fragment,{children:[R>0&&s.jsxs(s.Fragment,{children:["Successfully imported ",R," file",R!==1?"s":"",".",$>0&&s.jsxs(s.Fragment,{children:[" Extracted ",s.jsx("strong",{children:$.toLocaleString()})," triples into working memory."]})]}),G>0&&s.jsxs(s.Fragment,{children:[R>0?" ":"","Stored ",G," file",G!==1?"s":""," as source — no structured knowledge was extracted yet (extraction for these file types is coming soon)."]})]}):s.jsxs(s.Fragment,{children:[R," file",R!==1?"s":""," imported",G>0&&s.jsxs(s.Fragment,{children:[", ",G," stored without extraction"]}),", ",P," failed.",$>0&&s.jsxs(s.Fragment,{children:[" ",$.toLocaleString()," triples extracted."]})]})}),v.length>0&&s.jsx("div",{className:"v10-import-file-list",style:{marginTop:12},children:v.map((A,M)=>s.jsxs("div",{className:"v10-import-file-item",children:[s.jsx("span",{className:"v10-import-file-icon",children:A.status==="success"?"✓":A.status==="skipped"?"–":"✗"}),s.jsx("span",{className:"v10-import-file-name",children:A.fileName}),s.jsx("span",{className:"v10-import-file-size",style:A.status==="error"?{color:"var(--text-danger)"}:void 0,children:A.status==="success"&&A.triplesWritten!=null?`${A.triplesWritten} triples`:A.status==="skipped"?"stored (no extraction)":A.error??"failed"})]},M))})]})]}),s.jsxs("div",{className:"v10-modal-footer",children:[g==="idle"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"v10-modal-btn",onClick:C,children:"Cancel"}),s.jsxs("button",{className:"v10-modal-btn primary",onClick:T,disabled:i.length===0,children:["Start Import (",i.length," file",i.length!==1?"s":"",")"]})]}),g==="uploading"&&s.jsx("button",{className:"v10-modal-btn",disabled:!0,children:"Importing…"}),(g==="done"||g==="error")&&s.jsx("button",{className:"v10-modal-btn primary",onClick:C,children:"Done"})]})]})})}function Ta(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Ra({open:e,onClose:t,contextGraphId:n,contextGraphName:r}){const[i,a]=f.useState(null),[o,l]=f.useState(null),[c,d]=f.useState([]),[g,h]=f.useState(null),[u,p]=f.useState([]),[v,y]=f.useState([]),[w,m]=f.useState(null),[b,x]=f.useState("allowlist");f.useEffect(()=>{e&&(fetch("/api/status",{headers:un()}).then(C=>C.json()).then(C=>{typeof(C==null?void 0:C.peerId)=="string"&&C.peerId.length>0&&l(C.peerId)}).catch(()=>{}),Oi(n).then(C=>d(C.allowedAgents)).catch(()=>d([])),Ii().then(C=>{const O=(C.agents??[]).filter(Z=>Z.connectionStatus!=="self");p(O)}).catch(()=>p([])),dr(n).then(C=>y(C.requests)).catch(()=>y([])))},[e,n]);const{dialogRef:k,onBackdropClick:N}=ur(e,t);if(!e)return null;const j=o?`${n}
3
+ ${o}`:null,_=(C,O)=>{navigator.clipboard.writeText(C).then(()=>{a(O),setTimeout(()=>a(null),2e3)}).catch(()=>{})},z=async C=>{try{await Pi(n,C),d(O=>O.filter(Z=>Z!==C))}catch{}},E=async C=>{m(C);try{await pr(n,C),y(O=>O.filter(Z=>Z.agentAddress!==C)),d(O=>[...new Set([...O,C])])}catch(O){h((O==null?void 0:O.message)||"Failed to approve")}finally{m(null)}},T=async C=>{m(C);try{await hr(n,C),y(O=>O.filter(Z=>Z.agentAddress!==C))}catch(O){h((O==null?void 0:O.message)||"Failed to reject")}finally{m(null)}};return s.jsx("div",{className:"v10-modal-overlay",onClick:N,role:"presentation",children:s.jsxs("div",{className:"v10-modal-box",style:{maxWidth:560},ref:k,role:"dialog","aria-modal":"true","aria-labelledby":"dkg-share-modal-title",children:[s.jsxs("div",{className:"v10-modal-header",style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{id:"dkg-share-modal-title",className:"v10-modal-title",children:"Share Context Graph"}),s.jsxs("div",{className:"v10-modal-subtitle",children:["Invite agents to collaborate on ",s.jsx("strong",{children:r}),"."]})]}),s.jsx("button",{type:"button",className:"v10-modal-close",onClick:t,"aria-label":"Close share dialog",title:"Close (Esc)",style:{flexShrink:0,cursor:"pointer"},children:"×"})]}),s.jsxs("div",{className:"v10-modal-body",children:[s.jsxs("div",{style:{display:"flex",gap:0,marginBottom:16,borderBottom:"1px solid var(--border-default)"},children:[s.jsx("button",{onClick:()=>x("allowlist"),style:{padding:"8px 16px",fontSize:12,fontWeight:b==="allowlist"?600:400,background:"none",border:"none",cursor:"pointer",color:b==="allowlist"?"var(--text-primary)":"var(--text-tertiary)",borderBottom:b==="allowlist"?"2px solid var(--accent-primary)":"2px solid transparent"},children:"Allowlist"}),s.jsxs("button",{onClick:()=>x("requests"),style:{padding:"8px 16px",fontSize:12,fontWeight:b==="requests"?600:400,background:"none",border:"none",cursor:"pointer",color:b==="requests"?"var(--text-primary)":"var(--text-tertiary)",borderBottom:b==="requests"?"2px solid var(--accent-primary)":"2px solid transparent",position:"relative"},children:["Join Requests",v.length>0&&s.jsx("span",{style:{position:"absolute",top:4,right:4,background:"var(--accent-red, #ef4444)",color:"var(--text-on-accent)",borderRadius:999,fontSize:9,fontWeight:700,padding:"1px 5px",minWidth:16,textAlign:"center"},children:v.length})]})]}),b==="allowlist"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"v10-form-group",children:[s.jsx("label",{className:"v10-form-label",children:"Allowed Agents"}),s.jsxs("div",{style:{fontSize:10,color:"var(--text-tertiary)",marginBottom:8},children:["Only agents on this list can read and write to the context graph. To add someone, share the Invite Code below — they'll send a signed join request you can approve in the ",s.jsx("strong",{children:"Join Requests"})," tab."]}),c.length>0&&s.jsx("div",{style:{marginBottom:8,display:"flex",flexDirection:"column",gap:4},children:c.map(C=>{const O=u.find(Z=>{var $;return(($=Z.agentAddress)==null?void 0:$.toLowerCase())===C.toLowerCase()});return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 10px",borderRadius:6,fontSize:11,fontFamily:"var(--font-mono)",background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[s.jsx("span",{style:{color:"var(--text-primary)"},children:O?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontFamily:"var(--font-body)",fontWeight:500},children:O.name})," ",s.jsx("span",{style:{color:"var(--text-tertiary)",fontSize:10},children:Ta(C)})]}):C}),s.jsx("button",{onClick:()=>z(C),style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-tertiary)",fontSize:12,padding:"0 4px"},title:"Remove agent",children:"×"})]},C)})}),c.length===0&&s.jsx("div",{style:{padding:"8px 12px",borderRadius:6,fontSize:11,color:"var(--text-tertiary)",background:"var(--bg-surface)",border:"1px dashed var(--border-default)",marginBottom:8},children:"No agents on allowlist — context graph is open to anyone who subscribes."})]}),s.jsx("div",{className:"v10-form-divider"}),s.jsxs("div",{className:"v10-form-group",children:[s.jsx("label",{className:"v10-form-label",children:"Invite Code"}),j===null?s.jsx("div",{style:{padding:"8px 12px",borderRadius:6,fontSize:11,color:"var(--text-tertiary)",background:"var(--bg-surface)",border:"1px dashed var(--border-default)"},children:"Loading peer ID…"}):s.jsxs("div",{style:{position:"relative"},children:[s.jsx("pre",{style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:6,padding:"10px 12px",fontSize:11,lineHeight:1.6,fontFamily:"var(--font-mono)",color:"var(--text-primary)",overflow:"auto",margin:0,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:j}),s.jsx("button",{className:"v10-modal-btn primary",onClick:()=>_(j,"invite"),style:{position:"absolute",top:6,right:6,fontSize:10,padding:"4px 10px",height:26,cursor:"pointer"},children:i==="invite"?"Copied":"Copy Invite"})]})]})]}),b==="requests"&&s.jsxs("div",{className:"v10-form-group",children:[s.jsx("label",{className:"v10-form-label",children:"Pending Join Requests"}),s.jsx("div",{style:{fontSize:10,color:"var(--text-tertiary)",marginBottom:8},children:"Agents who submitted a signed request to join this context graph. Approve to add them to the allowlist."}),v.length===0&&s.jsx("div",{style:{padding:"16px 12px",borderRadius:6,fontSize:11,textAlign:"center",color:"var(--text-tertiary)",background:"var(--bg-surface)",border:"1px dashed var(--border-default)"},children:"No pending join requests."}),v.map(C=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 10px",borderRadius:6,fontSize:11,background:"var(--bg-surface)",border:"1px solid var(--border-default)",marginBottom:4},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[C.name&&s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:500},children:C.name}),s.jsx("span",{style:{color:"var(--text-tertiary)",fontFamily:"var(--font-mono)",fontSize:10},children:C.agentAddress}),s.jsxs("span",{style:{fontSize:9,color:"var(--text-tertiary)"},children:["Requested ",new Date(C.timestamp).toLocaleString()]})]}),s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{onClick:()=>E(C.agentAddress),disabled:w===C.agentAddress,style:{background:"rgba(34, 197, 94, 0.15)",color:"var(--text-success)",border:"1px solid rgba(34, 197, 94, 0.3)",cursor:"pointer",borderRadius:4,fontSize:10,padding:"4px 10px",fontWeight:600},children:w===C.agentAddress?"…":"Approve"}),s.jsx("button",{onClick:()=>T(C.agentAddress),disabled:w===C.agentAddress,style:{background:"rgba(239, 68, 68, 0.1)",color:"var(--text-danger)",border:"1px solid rgba(239, 68, 68, 0.2)",cursor:"pointer",borderRadius:4,fontSize:10,padding:"4px 10px",fontWeight:600},children:"Reject"})]})]},C.agentAddress)),g&&s.jsx("div",{style:{fontSize:10,color:"var(--text-danger)",marginTop:4},children:g})]})]}),s.jsx("div",{className:"v10-modal-footer",children:s.jsx("button",{className:"v10-modal-btn",onClick:t,children:"Done"})})]})})}const St=["#6366f1","#14b8a6","#f43f5e","#facc15","#8b5cf6","#10b981","#0ea5e9","#d946ef"],vs=1e4;function jt(e){if(e!=null)return typeof e=="string"?e.startsWith('"')?e.replace(/^"/,"").replace(/"(\^\^<[^>]*>)?$/,""):e:typeof e=="object"&&e!==null&&"value"in e?String(e.value):String(e)}function Oa(e){if(e.startsWith("did:dkg:agent:")){const t=e.slice(14);return t.startsWith("0x")?t.slice(0,6)+"…"+t.slice(-4):t.slice(0,6)+"…"+t.slice(-6)}return e.length>18?e.slice(0,8)+"…"+e.slice(-6):e}function Ia(e){return e.startsWith("did:")||e.startsWith("12D3")?e:/^0x[0-9a-fA-F]{40}$/.test(e)?`did:dkg:agent:${e}`:e}function Pa(e,t){const n=`did:dkg:context-graph:${t}/`;if(!e.startsWith(n))return;const r=e.slice(n.length),i=r.indexOf("/");if(i<0)return;const a=r.slice(0,i);if(!(!a||a.startsWith("_")))return a}function za(e){return`PREFIX dkg: <http://dkg.io/ontology/>
4
4
  PREFIX prov: <http://www.w3.org/ns/prov#>
5
5
  SELECT ?op ?root ?agent ?publishedAt ?g WHERE {
6
6
  GRAPH ?g {
@@ -13,7 +13,7 @@ SELECT ?op ?root ?agent ?publishedAt ?g WHERE {
13
13
  STRSTARTS(STR(?g), "${`did:dkg:context-graph:${e}/`}") &&
14
14
  CONTAINS(STR(?g), "_shared_memory_meta")
15
15
  )
16
- } ORDER BY DESC(?publishedAt) LIMIT 5000`}function za(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t)%St.length}function La(e){const t=[...new Set(e)].sort(),n=new Set,r=new Map;for(const i of t){const a=za(i);let o=a;if(n.size<St.length){for(let l=0;l<St.length;l++){const c=(a+l)%St.length;if(!n.has(c)){o=c;break}}n.add(o)}r.set(i,St[o])}return r}function Sr(e){const[t,n]=f.useState(new Map),[r,i]=f.useState([]),[a,o]=f.useState([]),[l,c]=f.useState(new Map),[d,g]=f.useState(null),[h,u]=f.useState(!1),[p,v]=f.useState(void 0),y=f.useRef(0);f.useEffect(()=>{if(!e){y.current+=1,n(new Map),i([]),o([]),c(new Map),u(!1),v(void 0);return}const x=++y.current,k=new AbortController;let S=!1,j;const _=()=>!S&&x===y.current;return u(!0),g(null),(async()=>{var z;try{const E=new Promise((A,M)=>{j=setTimeout(()=>{k.abort(),M(new Error(`SWM attribution query timed out after ${Math.round(vs/1e3)}s`))},vs)}),T=(async()=>{const A=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...un()},signal:k.signal,body:JSON.stringify({sparql:Pa(e)})});if(!A.ok)throw new Error(`SPARQL query failed: ${A.status}`);return A.json()})(),$=await Promise.race([T,E]),Z=(((z=$==null?void 0:$.result)==null?void 0:z.bindings)??[]).slice().reverse(),C=new Map,R=new Map,G=[];for(const A of Z){const M=jt(A.op),F=jt(A.root),B=jt(A.agent),J=jt(A.publishedAt),X=jt(A.g);if(!M||!F||!B||!J)continue;const H=Oa(B),V=X?Ia(X,e):void 0;G.push({opUri:M,rootUri:F,agent:H,publishedAt:J,subGraph:V});const re={agent:H,opUri:M,publishedAt:J,subGraph:V},ye=C.get(F);ye?ye.some(Te=>Te.agent===H)||ye.push(re):C.set(F,[re]);let Ne=R.get(H);Ne||(Ne=new Set,R.set(H,Ne)),Ne.add(F)}const P=La(R.keys()),L=[...R.entries()].map(([A,M])=>({agent:A,color:P.get(A),label:Ta(A),entityCount:M.size})).sort((A,M)=>M.entityCount-A.entityCount);if(!_())return;n(C),i(G),o(L),c(P),v(e)}catch(E){if(!_())return;g((E==null?void 0:E.message)??"Failed to load SWM attributions"),n(new Map),i([]),o([]),c(new Map),v(e)}finally{j&&clearTimeout(j),_()&&u(!1)}})(),()=>{S=!0,j&&clearTimeout(j),k.abort()}},[e]);const{nodeColors:w,conflicts:m}=f.useMemo(()=>{const x={},k=[];for(const[S,j]of t)if(j.length!==0)if(j.length===1){const _=j[0].agent,z=l.get(_);z!==void 0&&(x[S]=z)}else k.push(S),x[S]="#f59e0b";return{nodeColors:x,conflicts:k}},[t,l]);return{resultContextGraphId:p,attributions:t,events:r,palette:a,nodeColors:w,conflicts:m,loading:!!(e&&(h||p!==e)),error:d}}function Ma(e,t){const n=`did:dkg:context-graph:${t}/`;if(!e.startsWith(n))return;const i=e.slice(n.length).split("/");if(i[0]!=="assertion"&&i.length>=2&&i[1]==="assertion")return i[0]}const bs=1e4,On="http://dkg.io/ontology/";function Fa(e){const t=`did:dkg:context-graph:${e}/_meta`;return`PREFIX dkg: <${On}>
16
+ } ORDER BY DESC(?publishedAt) LIMIT 5000`}function La(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t)%St.length}function Ma(e){const t=[...new Set(e)].sort(),n=new Set,r=new Map;for(const i of t){const a=La(i);let o=a;if(n.size<St.length){for(let l=0;l<St.length;l++){const c=(a+l)%St.length;if(!n.has(c)){o=c;break}}n.add(o)}r.set(i,St[o])}return r}function Cr(e){const[t,n]=f.useState(new Map),[r,i]=f.useState([]),[a,o]=f.useState([]),[l,c]=f.useState(new Map),[d,g]=f.useState(null),[h,u]=f.useState(!1),[p,v]=f.useState(void 0),y=f.useRef(0);f.useEffect(()=>{if(!e){y.current+=1,n(new Map),i([]),o([]),c(new Map),u(!1),v(void 0);return}const x=++y.current,k=new AbortController;let N=!1,j;const _=()=>!N&&x===y.current;return u(!0),g(null),(async()=>{var z;try{const E=new Promise((A,M)=>{j=setTimeout(()=>{k.abort(),M(new Error(`SWM attribution query timed out after ${Math.round(vs/1e3)}s`))},vs)}),T=(async()=>{const A=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...un()},signal:k.signal,body:JSON.stringify({sparql:za(e)})});if(!A.ok)throw new Error(`SPARQL query failed: ${A.status}`);return A.json()})(),C=await Promise.race([T,E]),Z=(((z=C==null?void 0:C.result)==null?void 0:z.bindings)??[]).slice().reverse(),$=new Map,R=new Map,G=[];for(const A of Z){const M=jt(A.op),F=jt(A.root),B=jt(A.agent),J=jt(A.publishedAt),X=jt(A.g);if(!M||!F||!B||!J)continue;const Y=Ia(B),V=X?Pa(X,e):void 0;G.push({opUri:M,rootUri:F,agent:Y,publishedAt:J,subGraph:V});const re={agent:Y,opUri:M,publishedAt:J,subGraph:V},ye=$.get(F);ye?ye.some(Re=>Re.agent===Y)||ye.push(re):$.set(F,[re]);let Ne=R.get(Y);Ne||(Ne=new Set,R.set(Y,Ne)),Ne.add(F)}const P=Ma(R.keys()),L=[...R.entries()].map(([A,M])=>({agent:A,color:P.get(A),label:Oa(A),entityCount:M.size})).sort((A,M)=>M.entityCount-A.entityCount);if(!_())return;n($),i(G),o(L),c(P),v(e)}catch(E){if(!_())return;g((E==null?void 0:E.message)??"Failed to load SWM attributions"),n(new Map),i([]),o([]),c(new Map),v(e)}finally{j&&clearTimeout(j),_()&&u(!1)}})(),()=>{N=!0,j&&clearTimeout(j),k.abort()}},[e]);const{nodeColors:w,conflicts:m}=f.useMemo(()=>{const x={},k=[];for(const[N,j]of t)if(j.length!==0)if(j.length===1){const _=j[0].agent,z=l.get(_);z!==void 0&&(x[N]=z)}else k.push(N),x[N]="#f59e0b";return{nodeColors:x,conflicts:k}},[t,l]);return{resultContextGraphId:p,attributions:t,events:r,palette:a,nodeColors:w,conflicts:m,loading:!!(e&&(h||p!==e)),error:d}}function Fa(e,t){const n=`did:dkg:context-graph:${t}/`;if(!e.startsWith(n))return;const i=e.slice(n.length).split("/");if(i[0]!=="assertion"&&i.length>=2&&i[1]==="assertion")return i[0]}const bs=1e4,On="http://dkg.io/ontology/";function Ua(e){const t=`did:dkg:context-graph:${e}/_meta`;return`PREFIX dkg: <${On}>
17
17
  PREFIX prov: <http://www.w3.org/ns/prov#>
18
18
  SELECT ?event ?type ?assertion ?name ?agent ?ts ?subGraphName ?assertionGraph (COUNT(DISTINCT ?root) AS ?entityCount) (COUNT(DISTINCT ?subjRoot) AS ?subjectEntityCount) WHERE {
19
19
  GRAPH <${t}> {
@@ -33,7 +33,7 @@ SELECT ?event ?type ?assertion ?name ?agent ?ts ?subGraphName ?assertionGraph (C
33
33
  OPTIONAL { ?assertion dkg:rootEntity ?subjRoot }
34
34
  }
35
35
  } GROUP BY ?event ?type ?assertion ?name ?agent ?ts ?subGraphName ?assertionGraph
36
- ORDER BY DESC(?ts) LIMIT 5000`}function Ge(e){if(e!=null)return typeof e=="string"?e.startsWith('"')?e.replace(/^"/,"").replace(/"(\^\^<[^>]*>)?$/,""):e:typeof e=="object"&&e!==null&&"value"in e?String(e.value):String(e)}function Ua(e){return e===`${On}AssertionCreated`?"created":e===`${On}AssertionPromoted`?"promoted":null}function Da(e){const[t,n]=f.useState([]),[r,i]=f.useState(!!e),[a,o]=f.useState(null),[l,c]=f.useState(void 0),d=f.useRef(void 0),g=f.useRef(void 0);return f.useEffect(()=>{if(!e){i(!1);return}d.current!=null&&d.current!==e&&(n([]),o(null),c(void 0),g.current=void 0);let h=!1;const u=new AbortController;let p;return d.current=e,i(!0),o(null),(async()=>{var v;try{const y=new Promise((k,S)=>{p=setTimeout(()=>{u.abort(),S(new Error(`Assertion-lifecycle query timed out after ${Math.round(bs/1e3)}s`))},bs)}),w=(async()=>{const k=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...un()},signal:u.signal,body:JSON.stringify({sparql:Fa(e),contextGraphId:e})});if(!k.ok)throw new Error(`SPARQL query failed: ${k.status}`);return k.json()})(),m=await Promise.race([w,y]);if(h||d.current!==e)return;const b=((v=m==null?void 0:m.result)==null?void 0:v.bindings)??[],x=[];for(const k of b){const S=Ge(k.event),j=Ge(k.type),_=Ge(k.assertion),z=Ge(k.name),E=Ge(k.agent),T=Ge(k.ts);if(!S||!_||!E||!T)continue;const $=Ua(j);if(!$)continue;let O;if($==="promoted"){const R=Ge(k.entityCount),G=R!=null?Number(R):NaN;if(Number.isFinite(G)&&G>0)O=G;else{const P=Ge(k.subjectEntityCount),L=P!=null?Number(P):NaN;Number.isFinite(L)&&L>=0&&(O=L)}}let C=Ge(k.subGraphName);if(C===void 0){const R=Ge(k.assertionGraph);R&&(C=Ma(R,e))}x.push({eventUri:S,kind:$,assertionUri:_,assertionName:z??"",agentUri:E,publishedAt:T,subGraph:C,entityCount:O})}n(x),c(e),g.current=e,o(null)}catch(y){if(h||(y==null?void 0:y.name)==="AbortError")return;o(y.message??String(y)),g.current!==e&&n([]),c(e),g.current=e}finally{p&&clearTimeout(p),h||i(!1)}})(),()=>{h=!0,u.abort(),p&&clearTimeout(p)}},[e]),f.useMemo(()=>({resultContextGraphId:l,events:t,loading:r,error:a}),[l,t,r,a])}const Za={wm:"working",swm:"shared",vm:"verified"};function qa(e){var u,p,v,y;const t=new Map;if(!e)return t;const n="http://dkg.io/ontology/decisions/status",r="http://dkg.io/ontology/tasks/status",i="http://dkg.io/ontology/tasks/priority",a="http://dkg.io/ontology/github/state",o="http://dkg.io/ontology/decisions/Decision",l="http://dkg.io/ontology/tasks/Task",c="http://dkg.io/ontology/github/PullRequest";let d=0,g=0,h=0;for(const w of e)if(w.types.includes(o))((u=w.properties.get(n))==null?void 0:u[0])==="proposed"&&d++;else if(w.types.includes(l)){const m=(p=w.properties.get(i))==null?void 0:p[0],b=(v=w.properties.get(r))==null?void 0:v[0];m==="p0"&&b!=="done"&&b!=="cancelled"&&g++}else w.types.includes(c)&&((y=w.properties.get(a))==null?void 0:y[0])==="open"&&h++;return d>0&&t.set("decisions",{label:`${d} proposed`,tone:"warn"}),g>0&&t.set("tasks",{label:`${g} p0`,tone:"danger"}),h>0&&t.set("github",{label:`${h} open`,tone:"info"}),t}const wn=({contextGraphId:e,profile:t,selected:n,onSelect:r,entities:i,layer:a,enabledScope:o,allTriplesTotal:l})=>{const[c,d]=Ce.useState([]),[g,h]=Ce.useState(!0),u=Ce.useMemo(()=>qa(i),[i]),p=Ce.useRef(0),v=Ce.useMemo(()=>o&&o.size>0&&o.size<3?new Set(o):o&&o.size>=3?null:a?new Set([Za[a]]):null,[o,a]),y=Ce.useMemo(()=>{if(!i)return null;const C=new Map;for(const R of i)if(!(v&&!v.has(R.trustLevel)))for(const G of R.subGraphs)C.set(G,(C.get(G)??0)+1);return C},[v,i]),w=Ce.useMemo(()=>{if(!i)return null;let C=0;for(const R of i)v&&!v.has(R.trustLevel)||C++;return C},[v,i]),m=Ce.useMemo(()=>{if(!i)return null;let C=0;for(const R of i)v&&!v.has(R.trustLevel)||R.subGraphs.size>0||C++;return C},[v,i]),b=Ce.useCallback(()=>{const C=++p.current;h(!0),$t.fetchSubGraphs(e).then(R=>{C===p.current&&d(R.subGraphs??[])}).catch(()=>{}).finally(()=>{C===p.current&&h(!1)})},[e]);Ce.useEffect(()=>(b(),()=>{p.current++}),[b]),mr(e,b);const x=Ce.useMemo(()=>c.filter(Qn).map(C=>{const R=t.forSubGraph(C.name),G=y!==null?y.get(C.name)??0:C.entityCount;return{slug:C.name,icon:R.icon??"•",color:R.color??"#64748b",displayName:R.displayName??C.name,description:R.description??C.description,rank:R.rank??99,entityCount:G,tripleCount:C.tripleCount,layerScoped:y!==null}}).sort((C,R)=>C.rank-R.rank),[c,t,y]),S=m!==null&&m>0||n===Ve;if(g&&x.length===0&&!S||x.length===0&&!S)return null;const j=w??x.reduce((C,R)=>C+R.entityCount,0),_=x.reduce((C,R)=>C+R.tripleCount,0),z={working:"Working Memory",shared:"Shared Working Memory",verified:"Verifiable Memory"},E=v?[...v].map(C=>z[C]).join(" + "):null,T=E?` in ${E}`:"",O=`Total distinct entities — includes those in named subgraphs (some may belong to more than one), plus Root entities not in any subgraph · ${j} entities${T}${E?"":` · ${l??_} triples`}`,Z=`All — total distinct entities. Includes those in named subgraphs (some may belong to more than one), plus Root entities not in any subgraph. ${j} entities${T}.`;return s.jsxs("div",{className:"v10-subgraph-bar",children:[s.jsx("div",{className:"v10-subgraph-bar-label",children:"Subgraphs"}),s.jsxs("button",{type:"button",className:`v10-subgraph-chip${n===null?" active":""}`,onClick:()=>r(null),title:O,"aria-label":Z,children:[s.jsx("span",{className:"v10-subgraph-chip-icon",children:"⊚"}),s.jsx("span",{className:"v10-subgraph-chip-label",children:"All"}),s.jsx("span",{className:"v10-subgraph-chip-count",children:j})]}),x.map(C=>{const R=u.get(C.slug);return s.jsxs("button",{type:"button",className:`v10-subgraph-chip${n===C.slug?" active":""}${R?" has-badge":""}`,onClick:()=>r(C.slug,a),title:`${C.displayName}${C.description?" · "+C.description:""} · ${C.entityCount} entities${T}${E?"":` · ${C.tripleCount} triples`}${R?" · "+R.label:""}`,style:{"--sg-color":C.color},children:[s.jsx("span",{className:"v10-subgraph-chip-icon",style:{color:C.color},children:C.icon}),s.jsx("span",{className:"v10-subgraph-chip-label",children:C.displayName}),s.jsx("span",{className:"v10-subgraph-chip-count",children:C.entityCount}),R&&s.jsxs("span",{className:`v10-subgraph-chip-badge tone-${R.tone}`,children:[s.jsx("span",{className:"v10-subgraph-chip-badge-dot"}),R.label]})]},C.slug)}),S&&(()=>{const C=m??0,R=n===Ve;return s.jsxs("button",{type:"button",className:`v10-subgraph-chip v10-subgraph-chip-root${R?" active":""}`,"data-active":R,"data-count":C,onClick:()=>r(Ve,a),title:`Entities not in any subgraph (Context Graph root) · ${C} entities${T}`,"aria-label":"Entities not in any subgraph (Context Graph root)",children:[s.jsx("span",{className:"v10-subgraph-chip-icon",children:"⊘"}),s.jsx("span",{className:"v10-subgraph-chip-label",children:"Root"}),s.jsx("span",{className:"v10-subgraph-chip-count",children:C})]})})()]})},Kn=f.lazy(()=>Pi(()=>import("./index-DHd3qhAk.js").then(e=>e.h),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.RdfGraph}))),Ga="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",Ba=new Map(Mi.map((e,t)=>[e,t]));function In(e){const t=e.trim();return!t||t.startsWith('"')?!1:t.startsWith("_:")||t.startsWith("<")&&t.endsWith(">")?!0:/\s/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function Qe(e){const t=e.trim();return t.startsWith("<")&&t.endsWith(">")?t.slice(1,-1):t}function Wa(e){const t=new Set,n=new Map,r=new Map,i=new Map;for(const l of e){const c=Qe(l.subject);t.add(c);const d=Ba.get(l.predicate);if(d!==void 0){const h=vr(l.object).trim();if(h){const u=i.get(c);(u===void 0||d<u)&&(r.set(c,h),i.set(c,d))}}if(Qe(l.predicate)===Ga||!In(l.object))continue;const g=Qe(l.object);n.set(c,(n.get(c)??0)+1),n.set(g,(n.get(g)??0)+1)}const a=[...t].filter(l=>(n.get(l)??0)===0).map(l=>({uri:l,label:r.get(l)??gr(void 0,l)})).sort((l,c)=>l.label.localeCompare(c.label));if(a.length===0)return{canvasTriples:e,singletonItems:a};const o=new Set(a.map(l=>l.uri));return{canvasTriples:e.filter(l=>!o.has(Qe(l.subject))&&!o.has(Qe(l.object))),singletonItems:a}}function Va(e){return e==="wm"?"Working Memory graph: local entities connected by entity-to-entity triples from loaded layer data.":e==="swm"?"Shared Working Memory graph: promoted shared entities connected by entity-to-entity triples from loaded layer data.":"Verifiable Memory graph: published knowledge assets, provenance anchors, and connected entity-to-entity triples from loaded layer data."}function Qa({items:e,onSelect:t}){return e.length===0?null:s.jsxs("div",{className:"v10-graph-singleton-shelf","aria-label":"Standalone entities without visible links",children:[s.jsxs("div",{className:"v10-graph-singleton-head",title:"Entities with no visible links are grouped here to keep the graph readable.",children:[s.jsx("span",{children:"Standalone entities"}),s.jsx("span",{children:e.length})]}),s.jsx("div",{className:"v10-graph-singleton-list",children:e.map(({uri:n,label:r})=>s.jsx("button",{type:"button",className:"v10-graph-singleton-item",title:n,onClick:()=>t==null?void 0:t(n),children:r},n))})]})}const Ka=2500;function ys(e,t=Ka){if(e.length<=t)return e;const n=new Map;for(const o of e)n.set(o.subject,(n.get(o.subject)??0)+1);const r=[...n.entries()].sort((o,l)=>l[1]-o[1]).map(([o])=>o),i=new Set;let a=0;for(const o of r){const l=n.get(o)??0;a+l>t||(i.add(o),a+=l)}return i.size===0&&r.length>0&&i.add(r[0]),e.filter(o=>i.has(o.subject)).slice(0,t)}function Qt({title:e,scopeLabel:t,tone:n,className:r,rail:i,overlay:a,showScopeLabel:o=!0,singletonItems:l=[],onSingletonClick:c,renderGraph:d}){const[g,h]=f.useState(!1);f.useEffect(()=>{if(!g)return;const v=y=>{y.key==="Escape"&&h(!1)};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[g]);const u=s.jsx("button",{type:"button",className:`v10-graph-expand-btn${o?"":" in-canvas"}`,onClick:()=>h(!0),title:`Expand ${e}`,"aria-label":`Expand ${e}`,children:"⤢"}),p=v=>s.jsxs(s.Fragment,{children:[o&&!v&&s.jsxs("div",{className:"v10-graph-shell-bar",children:[s.jsx("div",{className:"v10-graph-scope",title:t,children:t}),u]}),s.jsxs("div",{className:"v10-graph-body",children:[s.jsxs("div",{className:"v10-graph-canvas",children:[!o&&!v&&u,s.jsx("div",{className:"v10-graph-view",children:d(v)}),a&&s.jsx("div",{className:"v10-graph-overlay",children:a}),s.jsx(Qa,{items:l,onSelect:c})]}),i&&s.jsx("aside",{className:"v10-graph-rail",children:i})]})]});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`v10-graph-shell v10-graph-shell-${n}${r?` ${r}`:""}`,children:!g&&p(!1)}),g&&s.jsx("div",{className:"v10-graph-expanded-backdrop",role:"dialog","aria-modal":"true","aria-label":`${e} expanded`,onClick:v=>{v.target===v.currentTarget&&h(!1)},children:s.jsxs("div",{className:`v10-graph-expanded-panel v10-graph-shell-${n}`,children:[s.jsxs("div",{className:"v10-graph-expanded-head",children:[s.jsxs("div",{children:[s.jsx("div",{className:"v10-graph-expanded-title",children:e}),s.jsx("div",{className:"v10-graph-expanded-subtitle",children:t})]}),s.jsx("button",{type:"button",className:"v10-graph-expanded-close",onClick:()=>h(!1),"aria-label":`Close expanded ${e}`,children:"×"})]}),s.jsx("div",{className:"v10-graph-expanded-body",children:p(!0)})]})})]})}function Cr({layer:e,triples:t,onNodeClick:n,contextGraphId:r,scopeLabel:i,trustLegendActiveLayer:a,title:o,scopeEntities:l,swmAttribution:c,layerEntities:d,nodeColorsOverride:g}){const{title:h}=Oe[e],u=o??h,p=fr(M=>M.theme),v=f.useMemo(()=>{if(e!=="vm")return;const M=new Set;for(const F of t)M.add(F.subject),In(F.object)&&M.add(F.object);return M},[t,e]),{anchors:y,decorationTriples:w}=zi(e==="vm"&&r?r:void 0,v),m=Sr(e==="swm"&&r&&!c?r:void 0),b=c??m,x=f.useMemo(()=>{if(!d||d.length===0)return t;const M=new Set;for(const F of d)M.add(De(F.uri));return Yt(t,M)},[t,d]),k=f.useMemo(()=>{const M=new Set,F=[],B=J=>{const X=`${J.subject}|${J.predicate}|${J.object}`;M.has(X)||(M.add(X),F.push({subject:J.subject,predicate:J.predicate,object:J.object}))};for(const J of x)B(J);for(const J of w)B(J);return F},[x,w]),S=k,j=f.useMemo(()=>{const M=e==="swm"?b.nodeColors:void 0;if(!(!M&&!g))return M?g?{...M,...g}:M:g},[e,b.nodeColors,g]),_=f.useMemo(()=>Li(e,j),[e,j]),{canvasTriples:z,singletonItems:E}=f.useMemo(()=>Wa(S),[S]),T=f.useMemo(()=>{if(!l||l.length===0)return E;const M=new Set(E.map(B=>Qe(B.uri)));for(const B of z)M.add(Qe(B.subject)),In(B.object)&&M.add(Qe(B.object));const F=[];for(const B of l){const J=Qe(B.uri);M.has(J)||(M.add(J),F.push({uri:J,label:B.label||gr(void 0,J)}))}return F.length===0?E:[...E,...F].sort((B,J)=>B.label.localeCompare(J.label))},[E,z,l]),$=`${r??"context"}:${e}`,O=e==="swm"&&!!r&&b.loading,Z=`${u} graph`,C=i??Va(e),R=a===null&&!!i,G=a===null?void 0:a??e,L=e==="vm"&&y.length>0||e==="swm"&&b.palette.length>0?s.jsxs(s.Fragment,{children:[e==="vm"&&y.length>0&&s.jsx(Ya,{anchors:y}),e==="swm"&&b.palette.length>0&&s.jsx(Ja,{palette:b.palette,conflicts:b.conflicts.length})]}):null,A=f.useMemo(()=>({name:`${$}:${p}`,palette:p}),[$,p]);return k.length===0&&T.length===0?s.jsx(Qt,{title:Z,scopeLabel:C,tone:e,className:"v10-graph-view-fill",showScopeLabel:R,renderGraph:()=>s.jsx("div",{className:"v10-layer-empty-shell",children:s.jsx(xe,{compact:!0,tone:At(e),icon:Oe[e].icon,title:`No triples in ${u}`,description:"The graph will appear when this layer has connected triples."})})}):O?s.jsx(Qt,{title:Z,scopeLabel:C,tone:"swm",className:"v10-graph-view-fill",showScopeLabel:R,renderGraph:()=>s.jsx("div",{className:"v10-layer-empty-shell",children:s.jsx(xe,{compact:!0,tone:"swm",icon:Oe.swm.icon,title:"Loading Shared Working Memory attribution...",description:"Agent colors are being prepared before the graph renders."})})}):s.jsx(Qt,{title:Z,scopeLabel:C,tone:e,className:"v10-graph-view-fill",overlay:L,showScopeLabel:R,singletonItems:T,onSingletonClick:M=>n==null?void 0:n(G?{id:M,trustLayer:G}:{id:M}),renderGraph:M=>z.length>0?s.jsx(f.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Kn,{data:z,format:"triples",options:_,viewConfig:A,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:G?F=>n==null?void 0:n({...F,trustLayer:G}):n,initialFit:!0},`${$}:${M?"expanded":"inline"}:${z.length}`)}):s.jsx("div",{className:"v10-graph-placeholder v10-graph-placeholder-centered",children:"Connected graph appears when this layer has linked entities."})})}function Ja({palette:e,conflicts:t}){return s.jsxs("div",{className:"v10-swm-legend","aria-label":"SWM attribution legend",children:[s.jsxs("div",{className:"v10-swm-legend-row v10-swm-legend-head",children:[s.jsx("span",{children:"SWM attribution"}),s.jsxs("span",{className:"v10-swm-legend-count",children:[e.length," agent",e.length===1?"":"s"]})]}),e.slice(0,8).map(n=>s.jsxs("div",{className:"v10-swm-legend-row",title:n.agent,children:[s.jsx("span",{className:"v10-swm-legend-swatch",style:{background:n.color}}),s.jsx("span",{className:"v10-swm-legend-label",children:n.label}),s.jsx("span",{className:"v10-swm-legend-metric",children:n.entityCount})]},n.agent)),t>0&&s.jsxs("div",{className:"v10-swm-legend-row v10-swm-legend-conflict",children:[s.jsx("span",{className:"v10-swm-legend-swatch",style:{background:"#f59e0b"},children:"!"}),s.jsx("span",{className:"v10-swm-legend-label",children:"In review"}),s.jsx("span",{className:"v10-swm-legend-metric",children:t})]})]})}function Ya({anchors:e}){var i;const t=f.useMemo(()=>{const a=new Set;for(const o of e)for(const l of o.agents)a.add(l);return a.size},[e]),n=(i=e[0])==null?void 0:i.publishedAt,r=(()=>{if(!n)return null;try{return new Date(n).toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return null}})();return s.jsxs("div",{className:"v10-vm-legend","aria-label":"Verifiable Memory legend",children:[s.jsxs("div",{className:"v10-vm-legend-row v10-vm-legend-head",children:[s.jsx("span",{children:"VM provenance layer"}),s.jsxs("span",{className:"v10-vm-legend-count",children:[e.length," anchor",e.length===1?"":"s"]})]}),s.jsxs("div",{className:"v10-vm-legend-row",children:[s.jsx("span",{className:"v10-vm-legend-swatch",style:{background:"#f5a524"},children:"◉"}),s.jsx("span",{className:"v10-vm-legend-label",children:"On-chain anchor"})]}),s.jsxs("div",{className:"v10-vm-legend-row",children:[s.jsx("span",{className:"v10-vm-legend-swatch",style:{background:"#c084fc"},children:"◈"}),s.jsxs("span",{className:"v10-vm-legend-label",children:["Agent identity (",t,")"]})]}),s.jsxs("div",{className:"v10-vm-legend-row",children:[s.jsx("span",{className:"v10-vm-legend-swatch",style:{background:"#4ade80"},children:"—"}),s.jsx("span",{className:"v10-vm-legend-label",children:"Signed / anchored edge"})]}),r&&s.jsxs("div",{className:"v10-vm-legend-foot",children:["Latest: ",r]})]})}function Ha({active:e,counts:t,onSwitch:n,onShare:r,onImport:i,onRefresh:a}){const[o,l]=f.useState(!1),c=f.useRef(null),d=g=>{l(!1),n(g)};return f.useEffect(()=>{if(!o)return;const g=h=>{var p;const u=h.target;u&&((p=c.current)!=null&&p.contains(u))||l(!1)};return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[o]),s.jsxs("div",{className:"v10-layer-switcher",children:[s.jsxs("button",{className:`v10-layer-switch-btn ${e==="overview"?"active":""}`,"data-layer":"overview","aria-label":"Overview",title:"Overview",onClick:()=>d("overview"),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"◎"}),s.jsx("span",{className:"v10-layer-switch-label",children:"Overview"})]}),s.jsx("span",{className:"v10-layer-switch-separator","aria-hidden":"true"}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="wm"?"active":""}`,"data-layer":"wm","aria-label":"Working Memory",title:"Working Memory",onClick:()=>d("wm"),children:[s.jsx("span",{className:"v10-layer-switch-icon",style:{color:"#64748b"},children:"◇"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-full",children:"Working Memory"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-compact",children:"WM"}),t.wm>0&&s.jsx("span",{className:"v10-layer-switch-count",children:t.wm})]}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="swm"?"active":""}`,"data-layer":"swm","aria-label":"Shared Working Memory",title:"Shared Working Memory",onClick:()=>d("swm"),children:[s.jsx("span",{className:"v10-layer-switch-icon",style:{color:"#f59e0b"},children:"◈"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-full",children:"Shared Working Memory"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-compact",children:"SWM"}),t.swm>0&&s.jsx("span",{className:"v10-layer-switch-count",children:t.swm})]}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="vm"?"active":""}`,"data-layer":"vm","aria-label":"Verifiable Memory",title:"Verifiable Memory",onClick:()=>d("vm"),children:[s.jsx("span",{className:"v10-layer-switch-icon",style:{color:"#22c55e"},children:"◉"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-full",children:"Verifiable Memory"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-compact",children:"VM"}),t.vm>0&&s.jsx("span",{className:"v10-layer-switch-count",children:t.vm})]}),s.jsx("span",{className:"v10-layer-switch-separator","aria-hidden":"true"}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="graph-overview"?"active":""}`,"data-layer":"graph-overview","aria-label":"Subgraphs",title:"Subgraphs",onClick:()=>d("graph-overview"),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"⌬"}),s.jsx("span",{className:"v10-layer-switch-label",children:"Subgraphs"})]}),s.jsxs("div",{ref:c,className:"v10-layer-more",onBlur:g=>{g.currentTarget.contains(g.relatedTarget)||l(!1)},children:[s.jsxs("button",{type:"button",className:`v10-layer-switch-btn v10-layer-more-btn ${e==="query"?"active":""}`,"data-layer":"query","aria-haspopup":"menu","aria-expanded":o,"aria-label":"More Context Graph views",title:"More Context Graph views",onClick:()=>l(g=>!g),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"⋯"}),s.jsx("span",{className:"v10-layer-switch-label",children:"More"})]}),o&&s.jsx("div",{className:"v10-layer-more-menu",role:"menu",children:s.jsxs("button",{type:"button",role:"menuitem",className:`v10-layer-more-item ${e==="query"?"active":""}`,onClick:()=>d("query"),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"⟐"}),"Query Catalogue"]})})]}),s.jsx("div",{className:"v10-layer-switcher-spacer"}),s.jsxs("div",{className:"v10-layer-switcher-actions",children:[s.jsxs("button",{className:"v10-layer-action-btn",onClick:r,"aria-label":"Share Context Graph",children:[s.jsx("span",{className:"v10-layer-action-icon",children:"⤴"}),s.jsx("span",{className:"v10-layer-action-label",children:"Share"})]}),s.jsxs("button",{className:"v10-layer-action-btn",onClick:i,"aria-label":"Import into Context Graph",children:[s.jsx("span",{className:"v10-layer-action-icon",children:"↑"}),s.jsx("span",{className:"v10-layer-action-label",children:"Import"})]}),s.jsx("button",{className:"v10-layer-action-btn",onClick:a,"aria-label":"Refresh Context Graph data",children:s.jsx("span",{className:"v10-layer-action-icon",children:"↻"})})]})]})}function Xa({cg:e,profile:t,activeSubGraph:n,onClearSubGraph:r}){const i=e.name||t.displayName||e.id;return s.jsxs("div",{className:"v10-project-strip",style:{"--sg-color":(n==null?void 0:n.color)??t.primaryColor},children:[s.jsx("span",{className:"v10-project-strip-dot",style:{background:t.primaryColor}}),s.jsx("button",{type:"button",className:"v10-project-strip-name",onClick:n?r:void 0,disabled:!n,title:n?"Back to context graph overview":e.id,children:i}),n?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"v10-project-strip-sep",children:"›"}),s.jsxs("span",{className:"v10-project-strip-sg",children:[s.jsx("span",{className:"v10-project-strip-sg-icon",style:{color:n.color},children:n.icon??"•"}),n.displayName??n.slug]}),n.description&&s.jsx("span",{className:"v10-project-strip-desc",title:n.description,children:n.description})]}):e.description&&s.jsx("span",{className:"v10-project-strip-desc",title:e.description,children:e.description})]})}function eo(e,t,n,r,i){const a=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"",o=new Set([t==null?void 0:t.agentDid,t==null?void 0:t.agentAddress].filter(d=>typeof d=="string"&&d.trim().length>0).map(Ie)),l=o.size>0;return a&&l&&o.has(Ie(a))?{label:"Curator",title:"This agent is the curator for this Context Graph.",tone:"curator"}:(e==null?void 0:e.callerInvolved)===!0?a&&!l&&n==="loading"?{label:"Role checking",title:"This agent is involved in this Context Graph; curator status is still loading.",tone:"unknown"}:a&&!l&&n==="error"?{label:"Role unknown",title:"This agent is involved in this Context Graph, but curator status could not be confirmed.",tone:"unknown"}:{label:"Joined",title:"This agent is involved in this Context Graph; curator status is shown only when identity metadata confirms it.",tone:"participant"}:(e==null?void 0:e.callerInvolved)===!1?{label:"Not joined",title:"This agent is not listed as curator or participant for this Context Graph.",tone:"viewer"}:i==="ok"&&r.map(d=>d.trim()).filter(Boolean).some(d=>o.has(Ie(d)))?{label:"Joined",title:"This agent is listed as a participant for this Context Graph.",tone:"participant"}:{label:"Role unknown",title:"The node did not provide enough role metadata for this Context Graph.",tone:"unknown"}}function to(e,t,n){if(Gn(e==null?void 0:e.accessPolicy)==="public")return{id:"participants",value:"Open",label:"Public access",tooltip:"Public Context Graphs do not have an authoritative allowlist count."};if(n==="loading")return{id:"participants",value:"...",label:"Agents with access",tooltip:"Participant list is loading."};if(n==="error")return{id:"participants",value:"Unavailable",label:"Agents with access",tooltip:"Participant list unavailable; access count is unknown."};const i=new Set(t.map(o=>o.trim()).filter(Boolean).map(Ie)),a=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"";return a&&i.add(Ie(a)),{id:"participants",value:i.size.toLocaleString(),label:"Agents with access",tooltip:"Includes the curator plus allowlisted participants reported by the node."}}function no(e){const t=Gn(e);return t==="public"?{label:"Public",title:"Public Context Graph.",tone:"public"}:t==="private"?{label:"Curated",title:"Curated Context Graph with access controlled by the curator.",tone:"curated"}:{label:"Access unknown",title:"The node did not provide an access policy for this Context Graph.",tone:"unknown"}}function so({cg:e,currentAgent:t,currentAgentStatus:n="ok"}){var l,c;const r=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"";if(!r)return"unknown";const i=((l=t==null?void 0:t.agentDid)==null?void 0:l.trim())??"",a=((c=t==null?void 0:t.agentAddress)==null?void 0:c.trim())??"",o=i||a;return o?Ie(r)===Ie(o)?"curator":"not-curator":"unknown"}function ro(e){return new Set([e==null?void 0:e.agentDid,e==null?void 0:e.agentAddress].filter(t=>typeof t=="string"&&t.trim().length>0).map(Ie))}function io({cg:e,memory:t,subGraphCount:n,subGraphFetchFailed:r=!1,participants:i,participantsStatus:a="ok",currentAgent:o,currentAgentStatus:l="ok",onSwitchLayer:c,onOpenPrimer:d}){var A,M,F;const{wm:g,swm:h,vm:u}=t.counts,p=g+h+u,v=eo(e,o??null,l,i,a),y=no(e==null?void 0:e.accessPolicy),w=to(e,i,a),m=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"",b=m?Ie(m):"",x=Gn(e==null?void 0:e.accessPolicy)==="public",k=ro(o??null),S=Object.values(t.layerStatus??{}),j=S.filter(B=>B==="error").length,_=!t.loading&&S.length===3&&j===3,z=!t.loading&&j>0,E=t.loading?"Loading memory layers...":_||t.error?"Live memory counts are unavailable.":t.partial||z?"One or more layer counts are currently a lower bound.":"Canonical current-layer entity counts.",T=_?"Unavailable":p.toLocaleString(),{total:$}=Bn(t),O=!t.loading&&(t.partial||z),Z=_?"Unavailable":t.loading&&$===0?"...":O?`${$.toLocaleString()}+`:$.toLocaleString(),C=_?"Live triple counts are unavailable.":O?"One or more layer triple counts are currently a lower bound.":"Canonical triple total across all layers.",R=n==null?r?"Unavailable":"...":n.toLocaleString(),G=n==null?r?"Sub-graph list is currently unavailable.":"Sub-graph count is loading.":"Topical partitions inside this Context Graph.",P=[{key:"wm",label:"Working Memory",desc:"Private staging area",count:g,status:((A=t.layerStatus)==null?void 0:A.wm)??"ok",color:"#64748b"},{key:"swm",label:"Shared Working Memory",desc:"Collaborative review",count:h,status:((M=t.layerStatus)==null?void 0:M.swm)??"ok",color:"#f59e0b"},{key:"vm",label:"Verifiable Memory",desc:"Published on-chain",count:u,status:((F=t.layerStatus)==null?void 0:F.vm)??"ok",color:"#22c55e"}],L=P.some(B=>B.status==="error");return s.jsxs("div",{className:"v10-po",children:[s.jsxs("div",{className:"v10-po-identity","data-section":"identity",children:[s.jsxs("div",{className:"v10-po-identity-pairs",children:[s.jsxs("div",{className:"v10-po-identity-pair",children:[s.jsx("span",{className:"v10-po-identity-label",children:"Your role:"}),s.jsx("span",{className:"v10-po-badge","data-role":v.tone,title:v.title,children:v.label})]}),s.jsxs("div",{className:"v10-po-identity-pair",children:[s.jsx("span",{className:"v10-po-identity-label",children:"Context Graph:"}),s.jsx("span",{className:"v10-po-badge","data-cg-type":y.tone,title:y.title,children:y.label})]})]}),d&&s.jsx("button",{type:"button",className:"v10-po-identity-primer",onClick:d,title:"Open the Context Graph primer",children:"What is a Context Graph?"})]}),s.jsxs("div",{"data-section":"at-a-glance",className:"v10-po-stat-block",children:[s.jsx("div",{className:"v10-po-section-title",children:"At a glance"}),s.jsx(pn,{className:"v10-po-stat-strip",items:[{id:"entities",value:T,label:"Entities",tooltip:E},{id:"triples",value:Z,label:"Triples",tooltip:C},{id:"subgraphs",value:R,label:"Subgraphs",tooltip:G},w]})]}),s.jsxs("div",{className:"v10-po-pipeline","data-section":"pipeline","aria-label":"Knowledge Pipeline",children:[s.jsx("div",{className:"v10-po-pipeline-head",children:s.jsxs("div",{children:[s.jsx("div",{className:"v10-po-section-title",children:"Knowledge Pipeline"}),s.jsx("div",{className:"v10-po-section-desc",children:"Entities move from private staging to shared review; published assertion bundles become Knowledge Assets with on-chain provenance."})]})}),s.jsx("div",{className:"v10-po-pipeline-track","aria-hidden":"true",children:!L&&p>0?P.map(B=>{const J=B.count>0?B.count/p*100:0;return s.jsx("span",{className:`v10-po-pipeline-seg ${B.key}`,style:{width:`${J}%`,background:B.color}},B.key)}):s.jsx("span",{className:"v10-po-pipeline-empty"})}),s.jsx("div",{className:"v10-po-pipeline-steps",children:P.map((B,J)=>s.jsxs("button",{type:"button",className:`v10-po-pipeline-step ${B.key}`,onClick:()=>c==null?void 0:c(B.key),style:{"--po-layer-color":B.color},children:[s.jsx("span",{className:"v10-po-pipeline-step-index",children:J+1}),s.jsxs("span",{className:"v10-po-pipeline-step-copy",children:[s.jsx("span",{className:"v10-po-pipeline-step-label",children:B.label}),s.jsx("span",{className:"v10-po-pipeline-step-desc",children:B.desc})]}),s.jsx("span",{className:"v10-po-pipeline-step-count",children:B.status==="error"?"Unavailable":`${B.count.toLocaleString()} ${We(B.key,B.count)}`})]},B.key))})]}),s.jsxs("div",{className:"v10-po-people","data-section":"participants",children:[s.jsx("div",{className:"v10-po-section-title",children:"Participant agents"}),(()=>{const B="did:dkg:agent:",J=V=>V.toLowerCase().startsWith(B)?V.slice(B.length):V,X=new Set,H=[];if(m&&a==="ok"){const V=Ie(m);X.add(V),H.push({display:J(m),full:m,canonical:V})}if(a==="ok")for(const V of i){const re=Ie(V);X.has(re)||(X.add(re),H.push({display:J(V),full:V,canonical:re}))}if(H.length===0){const V=x?"This Context Graph is public — anyone can subscribe.":a==="loading"?"Loading participant agents...":a==="error"?"Participant list unavailable.":"No participant agents recorded yet.";return s.jsx("div",{className:"v10-po-people-empty",children:V})}return s.jsx("div",{className:"v10-po-participants-list",children:H.map(({display:V,full:re,canonical:ye})=>{const Ne=k.has(ye),Te=!!b&&ye===b,q=`${V.slice(0,6)}…${V.slice(-4)}`,ne=[q];return Ne&&ne.push("you"),Te&&ne.push("curator"),s.jsxs("span",{className:`v10-po-participant${Ne?" is-self":""}${Te?" is-curator":""}`,title:re,"aria-label":ne.join(" "),children:[s.jsx("span",{className:"v10-po-participant-name",children:q}),Ne&&s.jsx("span",{className:"v10-po-participant-tag",children:"you"}),Te&&s.jsx("span",{className:"v10-po-participant-tag",children:"curator"})]},ye)})})})()]})]})}function ao({contextGraphId:e,curatorStatus:t,onParticipantsChanged:n}){const[r,i]=f.useState([]),[a,o]=f.useState(null),[l,c]=f.useState("loading"),d=f.useRef(0),g=f.useCallback(()=>{if(t!=="curator"){i([]),c("idle");return}const p=++d.current;c("loading"),dr(e).then(v=>{d.current===p&&(i(v.requests.filter(y=>y.status==="pending")),c("idle"))}).catch(()=>{d.current===p&&(i([]),c("error"))})},[e,t]);if(f.useEffect(()=>(g(),()=>{d.current++}),[g]),Fi(f.useCallback(p=>{var v;p.type!=="join_request"&&p.type!=="join_approved"&&p.type!=="join_rejected"||((v=p.data)==null?void 0:v.contextGraphId)===e&&g()},[e,g])),t==="not-curator")return null;if(t==="unknown")return s.jsxs("section",{className:"v10-po-join","data-section":"join-requests",children:[s.jsx("header",{className:"v10-po-join-head",children:s.jsx("span",{className:"v10-po-section-title",children:"Pending join requests"})}),s.jsx("div",{className:"v10-po-join-empty",children:"Verifying access…"})]});const h=async p=>{o(p);try{await pr(e,p),i(v=>v.filter(y=>y.agentAddress!==p)),n==null||n()}catch{}finally{o(null)}},u=async p=>{o(p);try{await hr(e,p),i(v=>v.filter(y=>y.agentAddress!==p)),n==null||n()}catch{}finally{o(null)}};return s.jsxs("section",{className:"v10-po-join","data-section":"join-requests",children:[s.jsxs("header",{className:"v10-po-join-head",children:[s.jsx("span",{className:"v10-po-section-title",children:"Pending join requests"}),s.jsx("span",{className:"v10-po-join-count","data-empty":r.length===0?"true":"false",children:r.length})]}),l==="loading"?s.jsx("div",{className:"v10-po-join-empty",children:"Loading join requests..."}):l==="error"?s.jsx("div",{className:"v10-po-join-empty",children:"Join requests are currently unavailable."}):r.length===0?s.jsx("div",{className:"v10-po-join-empty",children:"No pending join requests."}):s.jsx("div",{className:"v10-po-join-list",children:r.map(p=>s.jsxs("div",{className:"v10-po-join-item",children:[s.jsxs("div",{className:"v10-po-join-info",children:[s.jsx("span",{className:"v10-po-join-name",children:p.name||`${p.agentAddress.slice(0,6)}…${p.agentAddress.slice(-4)}`}),s.jsxs("span",{className:"v10-po-join-addr",title:p.agentAddress,children:[p.agentAddress.slice(0,10),"…"]})]}),s.jsxs("div",{className:"v10-po-join-actions",children:[s.jsx("button",{className:"v10-po-join-btn approve",onClick:()=>h(p.agentAddress),disabled:a===p.agentAddress,children:a===p.agentAddress?"…":"✓ Approve"}),s.jsx("button",{className:"v10-po-join-btn reject",onClick:()=>u(p.agentAddress),disabled:a===p.agentAddress,"aria-label":"Reject join request",children:"✕"})]})]},p.agentAddress))})]})}function oo({onOpenPrimer:e}){return s.jsxs("div",{className:"v10-po-primer-footer","data-section":"primer",children:[s.jsx("span",{className:"v10-po-primer-footer-lede",children:"New here?"}),s.jsx("span",{className:"v10-po-primer-footer-arrow","aria-hidden":"true",children:"→"}),s.jsx("button",{type:"button",className:"v10-po-primer-footer-link",onClick:e,children:"What is a Context Graph?"}),s.jsx("div",{className:"v10-po-primer-footer-sub",children:"A short primer on context graphs, the WM → SWM → VM pipeline, and how participant agents collaborate."})]})}const lo=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function co(e,t=0){const n=br(o=>o.trackedIds),r=n.join(","),{data:i,loading:a}=ft(async()=>{if(n.length===0)return{wallets:[],ownerPublish:!1,resolved:!1};const o=await Ui().catch(()=>null),l=(o==null?void 0:o.wallets)??[];let c=!1;try{const{contextGraphs:g}=await Di(),h=(g??[]).find(p=>(p==null?void 0:p.id)===e),u=h==null?void 0:h.curator;if(u){const p=await Zi().catch(()=>null);c=!!(p!=null&&p.agentDid&&Ie(u)===Ie(p.agentDid))}}catch{c=!1}return{wallets:await Promise.all(l.map(async g=>{var k;const h=(k=o==null?void 0:o.balances)==null?void 0:k.find(S=>lo(S.address,g)),u=h==null,p=h!=null&&Number(h.eth)>0,v=h!=null&&Number(h.trac)>0;let y,w=!1,m=!1,b,x=!1;for(const S of n){const j=await cs(S,g,{extended:!0}).catch(()=>null);if(j===null){x=!0;continue}const _=us(j);if(_.outcome==="inconclusive"){x=!0;continue}if(_.outcome!=="unregistered"){if(_.outcome==="covers"){y={accountId:S,discountBps:j.discountBps,untracked:!1};break}_.dead&&(w=!0,b||(b=S)),_.hasBudget||(m=!0)}}if(!y&&!x&&!w&&!m){const S=await qi(g).catch(()=>{});if(S===void 0)x=!0;else if(S.accountId!=null&&!n.includes(S.accountId)){const j=S.accountId,_=await cs(j,g,{extended:!0}).catch(()=>null);if(_===null)x=!0;else{const z=us(_);z.outcome==="covers"?y={accountId:j,discountBps:_.discountBps,untracked:!0}:z.outcome==="uncovered"?(z.dead&&(w=!0,b||(b=j)),z.hasBudget||(m=!0)):x=!0}}}return{wallet:g,covered:!!y,accountId:y==null?void 0:y.accountId,discountBps:y==null?void 0:y.discountBps,coverUntracked:(y==null?void 0:y.untracked)??!1,deadAccountId:y?void 0:b,inconclusive:!y&&x,balanceUnknown:u,gasFunded:p,hasTrac:v,sawExpired:w,sawInsolvent:m}})),ownerPublish:c,resolved:l.length>0}},[r,e],t);return f.useMemo(()=>{const o=(i==null?void 0:i.wallets)??[],l=(i==null?void 0:i.ownerPublish)??!1,c=(i==null?void 0:i.resolved)??!1;if(n.length===0||!c||o.length===0)return{verdict:"unknown",loading:a,ownerPublish:l,anyGasFunded:!1,reasons:[],conditions:{approved:!1,gasFunded:!1,notExpired:!1,solvent:!1},wallets:o};const d=o.filter(m=>m.covered),g=o.filter(m=>!m.covered),h=g.filter(m=>!m.inconclusive&&!m.balanceUnknown),u=g.filter(m=>m.inconclusive||m.balanceUnknown),p={approved:g.length===0,gasFunded:o.every(m=>m.gasFunded),notExpired:!o.some(m=>m.sawExpired),solvent:!o.some(m=>m.sawInsolvent)};let v;const y=[];if(g.length===0)d.some(m=>m.gasFunded||m.balanceUnknown)?v="eligible":(v="fallthrough-no-funds",y.push("every approved signing wallet is out of gas"));else if(h.length===0&&u.length>0)v="unknown";else{const m=o.some(b=>(b.covered||b.hasTrac)&&b.gasFunded);!m&&u.length>0?v="unknown":(v=m?"fallthrough":"fallthrough-no-funds",y.push(`${d.length} of ${o.length} signing wallets approved`),o.some(b=>b.sawExpired)&&y.push("a PCA has expired or been fully swept"),o.some(b=>b.sawInsolvent)&&y.push("a PCA is out of budget"),p.gasFunded||y.push("a signing wallet has no gas"),g.some(b=>b.inconclusive)&&y.push("a wallet’s PCA coverage couldn’t be checked"),g.some(b=>b.balanceUnknown)&&y.push("a signing wallet’s balance couldn’t be checked"))}const w=d.reduce((m,b)=>(b.discountBps??-1)>((m==null?void 0:m.discountBps)??-1)?b:m,void 0);return{verdict:v,loading:a,accountId:w==null?void 0:w.accountId,discountBps:w==null?void 0:w.discountBps,accountUntracked:w==null?void 0:w.coverUntracked,ownerPublish:l,anyGasFunded:o.some(m=>m.gasFunded||m.balanceUnknown),reasons:y,conditions:p,wallets:o}},[i,a,n.length])}function uo(e){return e.verdict==="fallthrough-no-funds"&&!(e.ownerPublish&&e.anyGasFunded)}function po(e){const t=br(o=>o.trackedIds),n=co(e,3e4),r=uo(n),i="Publish will fail — no signing wallet can fund it (coverage or gas).",a=t.length>0;return{blocked:r,reason:i,chipVisible:a,eligibility:n}}function ho({verdict:e,accountId:t,discountBps:n,accountUntracked:r,ownerPublish:i,id:a}){return s.jsx("div",{className:"v10-pca-publish-chip",id:a,"data-testid":"pca-publish-eligibility",children:s.jsx(Ca,{variant:"chip",verdict:e,accountId:t,discountBps:n,accountUntracked:r,ownerPublish:i})})}function Jn({title:e,agent:t,footnote:n,dismissed:r,onDismiss:i,children:a}){return s.jsxs("div",{className:`v10-gen-widget ${r?"dissolved":""}`,children:[s.jsxs("div",{className:"v10-gen-widget-header",children:[s.jsx("span",{className:"v10-gen-widget-title",children:e}),s.jsxs("div",{className:"v10-gen-widget-right",children:[t&&s.jsxs("span",{className:"v10-gen-widget-agent",children:[s.jsx("span",{className:"v10-gen-widget-agent-dot"}),t]}),i&&s.jsx("button",{className:"v10-gen-widget-dismiss",onClick:i,children:"✕"})]})]}),s.jsx("div",{className:"v10-gen-widget-body",children:a}),n&&s.jsx("div",{className:"v10-gen-widget-footnote",children:n})]})}function mo({entities:e}){const t=et(),n=f.useMemo(()=>{const r=new Map;for(const i of e){const{icon:a,type:o}=dn(i,t),l=r.get(o);l?l.count++:r.set(o,{icon:a,count:1})}return[...r.entries()].sort((i,a)=>a[1].count-i[1].count)},[e,t]);return n.length===0?null:s.jsx(Jn,{title:"Entity Types",children:s.jsx(pn,{compact:!0,items:n.map(([r,{icon:i,count:a}])=>({id:r,label:`${i} ${r}`,value:a}))})})}function fo({entities:e,entityCount:t,triples:n,layer:r}){const i=f.useMemo(()=>e.filter(l=>l.properties.has("http://dkg.io/ontology/sourceContentType")).length,[e]),a=f.useMemo(()=>e.reduce((l,c)=>l+c.connections.length,0),[e]),o=e.length>0?(a/e.length).toFixed(1):"0";return s.jsx(Jn,{title:"Layer Stats",children:s.jsx(pn,{compact:!0,layer:r,items:[{id:"entities",label:We(r,t),value:t},{id:"triples",label:"Triples",value:n},{id:"connections",label:"Connections",value:a},{id:"avg",label:"Avg. connections / entity",value:o},...i>0?[{id:"documents",label:"Documents",value:i}]:[]]})})}function $r(e,t){const[n,r]=f.useState(!1),[i,a]=f.useState(null),[o,l]=f.useState(null),c=f.useCallback(async(d,g)=>{r(!0),l(null),a(null);try{const h=await d();a(h),e==null||e({ok:!0,text:h}),t==null||t()}catch(h){const u=g(h);l(u),e==null||e({ok:!1,text:u})}finally{r(!1)}},[e,t]);return{busy:n,result:i,error:o,run:c}}function Er({title:e,footnote:t,context:n,result:r,error:i,extras:a,children:o}){return s.jsxs(Jn,{title:e,footnote:t,children:[s.jsx("div",{className:"v10-decision-context",style:{marginBottom:10},children:n}),r&&s.jsxs("div",{"data-testid":"layer-action-result",style:{fontSize:11,color:"var(--text-success)",marginBottom:8},children:["✓ ",r]}),i&&s.jsxs("div",{"data-testid":"layer-action-error",style:{fontSize:11,color:"var(--text-danger)",marginBottom:8},children:["✕ ",i]}),a,s.jsx("div",{className:"v10-decision-actions",children:o})]})}function go({count:e,contextGraphId:t,onComplete:n,onResult:r}){const{busy:i,result:a,error:o,run:l}=$r(r,n),c=f.useCallback(()=>{let h=null;l(async()=>{const u=await Ht(t,"wm");let p=0;for(const y of u)h=y.name,(await Xt(t,y.name,y.subGraph?{subGraphName:y.subGraph}:{})).promotedCount===0&&(p+=1);const v=u.length-p;if(v>0){const y=p>0?` (${p} already shared or still committing)`:"";return`Shared ${v} complete Knowledge Asset${v!==1?"s":""} to Shared Memory${y}`}return"No Knowledge Assets were newly shared — all were already in Shared Memory or still committing."},u=>{const p=en(h??"an assertion",u);return p?p.message:(u==null?void 0:u.message)??"Action failed"})},[t,l]);if(e===0)return null;const d="#f59e0b",g=We("wm",e).toLowerCase();return s.jsx(Er,{title:"Share complete Knowledge Assets",footnote:"Shares each complete owning Knowledge Asset atomically to Shared Working Memory.",context:s.jsxs(s.Fragment,{children:[e," eligible ",g," will be shared through their complete owning Knowledge Assets for collaborative review."]}),result:a,error:o,children:s.jsx("button",{"data-testid":"widget-promote-all-btn",className:"v10-decision-btn approve",style:{borderColor:`${d}50`,color:"var(--text-warning)",background:`${d}15`,opacity:i?.5:1},disabled:i,onClick:c,children:i?"...":"✓ Share Complete KAs → Shared"})})}function vo({count:e,contextGraphId:t,onComplete:n,onResult:r}){const[i,a]=f.useState(null),{busy:o,result:l,error:c,run:d}=$r(r,n),g=po(t),h=f.useId(),u=f.useId(),p=[g.chipVisible?h:null,g.blocked?u:null].filter(Boolean).join(" ")||void 0,v=f.useCallback(()=>{g.blocked||d(async()=>{a(null);const w=await Ht(t,"swm"),m=await yr(t,w);if(m.published>0){const b=m.failures.length?` (${m.failures.length} assertion${m.failures.length===1?"":"s"} could not be published)`:"",x=m.partial>0?` — ⚠ ${m.partial}: ${tn(m.partialError)}`:"";return a(m.convictionCostCovered??null),`Published ${m.published} knowledge asset${m.published!==1?"s":""} to Verifiable Memory${b}${x}`}if(w.length===0)return"Nothing to publish — promote assertions to Shared Memory first.";throw new Error(m.failures[0]?`${m.failures[0].name}: ${m.failures[0].error}`:"Publish failed")},w=>(w==null?void 0:w.message)??"Action failed")},[t,d,g.blocked]);if(e===0)return null;const y=We("swm",e).toLowerCase();return s.jsx(Er,{title:"Publish",footnote:`Moves ${y} from this layer to Verifiable Memory.`,context:s.jsxs(s.Fragment,{children:[e," ",y," in this layer can be published to Verifiable Memory on-chain."]}),result:l,error:c,extras:s.jsxs(s.Fragment,{children:[s.jsx(Gi,{convictionCostCovered:i}),g.chipVisible&&s.jsx(ho,{...g.eligibility,id:h}),g.blocked&&s.jsx("span",{id:u,className:"v10-sr-only",children:g.reason})]}),children:s.jsx("button",{"data-testid":"widget-publish-vm-btn",className:"v10-decision-btn primary-cta publish-vm",style:{opacity:o||g.blocked?.5:1},disabled:o,"aria-disabled":g.blocked||void 0,title:g.blocked?g.reason:void 0,"aria-describedby":p,onClick:v,children:o?"...":"◉ Publish to Verifiable Memory"})})}function bo({layer:e,entities:t,entityCount:n,actionEntityCount:r=n,tripleCount:i,contextGraphId:a,onComplete:o}){const[l,c]=f.useState(null),d=l&&s.jsxs("div",{"data-testid":l.ok?"layer-action-result":"layer-action-error",style:{fontSize:11,color:l.ok?"var(--text-success)":"var(--text-danger)",marginBottom:8},children:[l.ok?"✓":"✕"," ",l.text]});return n===0?s.jsxs("div",{className:"v10-layer-widgets-strip empty",children:[d,s.jsx(xe,{compact:!0,tone:At(e),icon:Oe[e].icon,title:`No ${We(e,2).toLowerCase()} yet`,description:e==="wm"?"Import data or chat with agents to populate Working Memory.":e==="swm"?"Seal and share complete Knowledge Assets from Working Memory with the team.":"Publish complete Knowledge Assets from Shared Working Memory to verify them on-chain."})]}):s.jsxs("div",{className:"v10-layer-widgets-strip",children:[s.jsxs("div",{className:"v10-layer-widgets-strip-stats",children:[s.jsx(fo,{entities:t,entityCount:n,triples:i,layer:e}),s.jsx(mo,{entities:t})]}),(e==="wm"||e==="swm")&&a&&r>0&&s.jsx("div",{className:"v10-layer-widgets-strip-action",children:e==="wm"?s.jsx(go,{count:r,contextGraphId:a,onComplete:o,onResult:c}):s.jsx(vo,{count:r,contextGraphId:a,onComplete:o,onResult:c})})]})}const yo={working:{layerKey:"wm",icon:"◇",label:"Working"},shared:{layerKey:"swm",icon:"◈",label:"Shared"},verified:{layerKey:"vm",icon:"◉",label:"Verifiable"}},xo=new Set(["http://dkg.io/ontology/profile/QueryCatalog","http://dkg.io/ontology/profile/SavedQuery"]);function jo(e){return e.types.some(t=>xo.has(t))}function _r({entities:e,layerKey:t,layerIcon:n,onSelectEntity:r,onOpenAgent:i,externallySorted:a=!1,sortLabel:o,headerExtra:l,timestampPredicate:c,perEntityTrustBadge:d=!1}){const g=et(),h=It(),u=We(t,e.length).toLowerCase(),p=f.useMemo(()=>{if(a)return e;const w=[...e];return w.sort((m,b)=>{const x=m.tripleCount??0;return(b.tripleCount??0)-x}),w},[e,a]),v=t==="vm"?"Verifiable":t==="swm"?"Shared":"Working";if(e.length===0)return s.jsx("div",{className:"v10-entity-list empty",children:s.jsx(xe,{compact:!0,tone:At(t),icon:n,title:`No ${We(t,2).toLowerCase()} yet`,description:`This view will fill when matching ${We(t,2).toLowerCase()} are available.`})});const y=o??(a?"click to open":"sorted by triples · click to open");return s.jsxs("div",{className:"v10-entity-list",children:[s.jsxs("div",{className:"v10-entity-list-header",children:[s.jsxs("span",{className:"v10-entity-list-count",children:[p.length," ",u]}),s.jsx("span",{className:"v10-entity-list-hint",children:y}),l&&s.jsx("span",{className:"v10-entity-list-extra",children:l})]}),p.map(w=>{const{icon:m,type:b}=dn(w,g),x=w.tripleCount??0,k=Wn(w),S=k?h==null?void 0:h.get(k):null,j=c?Vt(w,c):null;return s.jsxs("div",{className:"v10-entity-card",onClick:_=>{_.stopPropagation(),r(w.uri)},children:[s.jsx("span",{className:"v10-entity-card-icon",children:m}),s.jsxs("div",{className:"v10-entity-card-main",children:[s.jsx("div",{className:"v10-entity-card-title",children:w.label}),s.jsxs("div",{className:"v10-entity-card-meta",children:[(S||k)&&s.jsx(gt,{agent:S??void 0,fallbackUri:k??void 0,size:"sm",onOpenAgent:i}),b&&b!=="Entity"&&s.jsxs("span",{className:"v10-entity-type-pill",children:[m," ",b]}),j!=null&&s.jsx("span",{className:"v10-entity-card-timestamp",title:new Date(j).toLocaleString(),children:Wi(j)}),s.jsxs("span",{className:"v10-entity-card-triples",children:[x," triples"]})]})]}),d?(()=>{const _=yo[w.trustLevel];return s.jsxs("span",{className:`v10-trust-badge ${_.layerKey}`,title:`${_.label} Memory`,children:[_.icon," ",_.label]})})():s.jsxs("span",{className:`v10-trust-badge ${t}`,children:[n," ",v]})]},w.uri)})]})}function wo({layer:e,entities:t,tripleCount:n,layerTriples:r,contextGraphId:i,memory:a,activeTab:o,onTabChange:l,onSelectEntity:c,onNodeClick:d,footer:g,swmAttribution:h,showQueryCatalog:u=!1,onShowQueryCatalogChange:p}){var _;const v=Oe[e],y=We(e,2),w=f.useMemo(()=>t.filter(z=>!jo(z)).length,[t]),m=((_=a.layerStatus)==null?void 0:_.vm)??(a.loading?"loading":a.error?"error":"ok"),b=e==="vm"&&m==="loading"&&t.length===0,x=e==="vm"&&m==="error"&&t.length===0,k=e==="vm"&&m==="ok"&&t.length===0,S=a.counts[e],j=z=>E=>{E.stopPropagation(),l(z)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"v10-layer-expand-tabs",children:[s.jsx("button",{className:`v10-layer-expand-tab ${o==="items"?"active":""}`,onClick:j("items"),children:y}),e!=="vm"&&s.jsx("button",{className:`v10-layer-expand-tab ${o==="assertions"?"active":""}`,onClick:j("assertions"),children:"Assertions"}),s.jsx("button",{className:`v10-layer-expand-tab ${o==="graph"?"active":""}`,onClick:j("graph"),children:"Graph"}),s.jsx("button",{className:`v10-layer-expand-tab ${o==="docs"?"active":""}`,onClick:j("docs"),children:"Documents"}),e!=="vm"&&p&&s.jsxs("label",{className:"v10-query-catalog-visibility",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:z=>p(z.target.checked)}),s.jsx("span",{children:"Show query catalog"})]})]}),o==="items"&&s.jsxs("div",{className:"v10-layer-expand-body entities-tab","data-cg-scroll-key":`layer:${e}:items`,children:[e==="vm"&&!b&&!x&&s.jsx(ko,{entities:t,tripleCount:n,contextGraphId:i}),b?s.jsx("div",{className:"v10-layer-widgets-strip empty",children:s.jsx(xe,{compact:!0,tone:"vm",icon:Oe.vm.icon,title:"Loading Verifiable Memory...",description:"Knowledge Assets are being read from the verified layer."})}):x?s.jsx("div",{className:"v10-layer-widgets-strip empty",children:s.jsx(xe,{compact:!0,tone:"vm",icon:Oe.vm.icon,title:"Verifiable Memory status unavailable.",description:"This node could not read the verified layer right now."})}):!k&&s.jsxs(s.Fragment,{children:[s.jsx(bo,{layer:e,entities:t,entityCount:S,actionEntityCount:w,tripleCount:n,contextGraphId:i,onComplete:a.refresh}),s.jsx(_r,{entities:t,layerKey:e,layerIcon:v.icon,onSelectEntity:c})]}),g]}),o==="assertions"&&e!=="vm"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(No,{contextGraphId:i,layer:e,includeQueryCatalog:u,onComplete:a.refresh,scrollKey:`layer:${e}:assertions`})}),o==="graph"&&s.jsx("div",{className:"v10-layer-expand-body full-width","data-cg-scroll-key":`layer:${e}:graph`,children:s.jsx(Cr,{layer:e,triples:r,onNodeClick:d,contextGraphId:i,swmAttribution:e==="swm"?h:void 0,layerEntities:t})}),o==="docs"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(Ar,{entities:t,contextGraphId:i,scrollKey:`layer:${e}:docs`})})]})}function ko({entities:e,tripleCount:t,contextGraphId:n}){const r=e.length,i=new Set;for(const o of e)for(const l of o.types)i.add(l);const a=i.size;return r===0?s.jsxs("div",{className:"v10-vm-hero v10-vm-hero-empty",children:[s.jsxs("div",{className:"v10-vm-hero-title",children:[s.jsx("span",{className:"v10-vm-hero-badge",children:"◉ Verifiable Memory"}),s.jsxs("div",{className:"v10-vm-hero-heading",children:[s.jsx("span",{className:"v10-vm-hero-headline",children:"Nothing published yet"}),s.jsxs("span",{className:"v10-vm-hero-context",title:n,children:["Context Graph: ",n]})]})]}),s.jsx(xe,{compact:!0,className:"v10-vm-empty-state",tone:"vm",icon:Oe.vm.icon,title:"No Knowledge Assets yet.",description:"Publish complete Knowledge Assets from Shared Working Memory to verify them on-chain."})]}):s.jsxs("div",{className:"v10-vm-hero",children:[s.jsxs("div",{className:"v10-vm-hero-title",children:[s.jsx("span",{className:"v10-vm-hero-badge",children:"◉ Verifiable Memory"}),s.jsxs("div",{className:"v10-vm-hero-heading",children:[s.jsx("span",{className:"v10-vm-hero-headline",children:"On-chain anchored · cryptographically signed"}),s.jsxs("span",{className:"v10-vm-hero-context",title:n,children:["Context Graph: ",n]})]})]}),s.jsx(pn,{className:"v10-vm-hero-stats",layer:"vm",items:[{id:"assets",value:r,label:"Knowledge Assets"},{id:"triples",value:t.toLocaleString(),label:"Verifiable Triples"},{id:"types",value:a,label:"Entity Types"}]}),s.jsxs("div",{className:"v10-vm-hero-strip",children:[s.jsxs("div",{className:"v10-vm-hero-chip",title:"Multi-agent endorsement",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#22c55e"}}),"Consensus"]}),s.jsxs("div",{className:"v10-vm-hero-chip",title:"Published to the DKG blockchain anchor",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#3b82f6"}}),"On-chain"]}),s.jsxs("div",{className:"v10-vm-hero-chip",title:"Each contribution bound to a DID",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#a855f7"}}),"Agent Identity"]}),s.jsxs("div",{className:"v10-vm-hero-chip",title:"Tamper-evident via content hashing",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#f59e0b"}}),"Content Hash"]})]})]})}function No({contextGraphId:e,layer:t,includeQueryCatalog:n=!1,onComplete:r,scrollKey:i}){const{data:a,loading:o,refresh:l}=ft(()=>Ht(e,t,{includeQueryCatalog:n}),[e,t,n],0),{data:c}=ft(()=>Ki(e),[e,t],0),[d,g]=f.useState(null),[h,u]=f.useState(null),[p,v]=f.useState(null),y=f.useCallback(async S=>{g(S.graphUri),u(null),v(null);try{if(t==="wm"){const j=await Xt(e,S.name,S.subGraph?{subGraphName:S.subGraph}:{}),_=xr(S.name,j);u(_.message)}else{const j=await jr(e,S.name,S.subGraph?{subGraphName:S.subGraph}:{});u(j.contextGraphError?`Published ${S.name} on-chain — ⚠ ${tn(j.contextGraphError)}`:`Published ${S.name} to Verifiable Memory`)}l(),r()}catch(j){const _=en(S.name,j);v(_?_.message:(j==null?void 0:j.message)??"Action failed")}finally{g(null)}},[e,t,l,r]),w=f.useCallback(async()=>{g("__all__"),u(null),v(null);let S=null;try{const j=await Ht(e,t);if(j.length===0){u(t==="wm"?"No user Knowledge Assets are ready to share.":"No user Knowledge Assets are ready to publish.");return}if(t==="wm"){let _=0;for(const E of j)S=E.name,(await Xt(e,E.name,E.subGraph?{subGraphName:E.subGraph}:{})).promotedCount===0&&(_+=1);const z=j.length-_;if(z>0){const E=_>0?` (${_} already shared or still committing)`:"";u(`Shared ${z} complete Knowledge Asset${z!==1?"s":""}${E}`)}else u("No Knowledge Assets were newly shared — all were already in Shared Memory or still committing.")}else{const _=await yr(e,j);if(_.published>0){const z=_.failures.length?` (${_.failures.length} could not be published)`:"",E=_.partial>0?` — ⚠ ${_.partial}: ${tn(_.partialError)}`:"";u(`Published ${_.published} knowledge asset${_.published!==1?"s":""} to Verifiable Memory${z}${E}`)}else throw new Error(_.failures[0]?`${_.failures[0].name}: ${_.failures[0].error}`:"Publish failed")}l(),r()}catch(j){const _=en(S??"selected assertion",j);v(_?_.message:(j==null?void 0:j.message)??"Action failed")}finally{g(null)}},[e,t,l,r]),m={flex:1,overflow:"auto"};if(o)return s.jsx("div",{className:"v10-layer-empty-shell",style:m,"data-cg-scroll-key":i,children:s.jsx(xe,{compact:!0,tone:At(t),icon:Oe[t].icon,title:"Loading assertions..."})});if(!(a!=null&&a.length))return s.jsx("div",{className:"v10-layer-empty-shell",style:m,"data-cg-scroll-key":i,children:s.jsx(xe,{tone:At(t),icon:Oe[t].icon,title:t==="swm"?"No Shared Working Memory assertions listed yet.":"No Working Memory assertions yet.",description:t==="swm"?"Promoted assertion contents are available as Shared Working Memory entities. The assertion list will populate once promoted assertions are exposed by the node.":"Create or import data to stage assertions in Working Memory."})});const b=t==="wm"?"Share Complete KA → Shared":"Publish to VM",x=t==="wm"?"Share Complete KAs → Shared":"Publish all to Verifiable Memory",k=a.filter(S=>S.subGraph!=="meta"||!S.name.startsWith("query-catalog-")).length;return s.jsxs("div",{style:m,"data-cg-scroll-key":i,children:[s.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid var(--border-subtle)"},children:[s.jsxs("span",{style:{fontSize:11,color:"var(--text-tertiary)"},children:[a.length," assertion",a.length!==1?"s":""]}),k>0&&s.jsx("button",{className:`v10-layer-expand-footer-btn ${t==="wm"?"promote":"publish"}`,disabled:d!==null,onClick:w,style:{opacity:d==="__all__"?.5:1},children:d==="__all__"?"...":x})]}),h&&s.jsxs("div",{"data-testid":t==="wm"?"assertion-promote-result":"assertion-publish-result",style:{padding:"6px 16px",fontSize:11,color:"var(--text-success)"},children:["✓ ",h]}),p&&s.jsxs("div",{"data-testid":t==="wm"?"assertion-promote-result":"assertion-publish-result",style:{padding:"6px 16px",fontSize:11,color:"var(--text-danger)"},children:["✕ ",p]}),a.map(S=>s.jsxs("div",{className:"v10-item-row","data-testid":"assertion-list-row",children:[s.jsx("span",{className:"v10-item-icon",children:"▤"}),s.jsxs("div",{className:"v10-item-info",children:[s.jsx("div",{className:"v10-item-name",style:{fontFamily:"var(--font-mono)",fontSize:11},children:S.name}),(c==null?void 0:c[S.name])&&s.jsx("div",{className:"v10-item-ual",style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--text-tertiary)",opacity:.7,wordBreak:"break-all",marginTop:1},title:c[S.name],children:c[S.name]}),s.jsxs("div",{className:"v10-item-meta-row",children:[S.tripleCount!=null&&s.jsxs("span",{className:"v10-item-count",children:[S.tripleCount," triples"]}),S.subGraph&&s.jsxs("span",{className:"v10-item-count v10-item-subgraph",title:`In sub-graph: ${S.subGraph}`,children:["› ",ja(S.subGraph,18)]})]})]}),s.jsx("button",{"data-testid":"assertion-row-action",className:`v10-layer-expand-footer-btn ${t==="wm"?"promote":"publish"}`,disabled:d!==null,onClick:j=>{j.stopPropagation(),y(S)},style:{opacity:d===S.graphUri?.5:1,flexShrink:0},children:d===S.graphUri?"...":b})]},S.graphUri))]})}function So({layer:e,memory:t,onNodeClick:n,onSelectEntity:r,contextGraphId:i,activeTab:a,onTabChange:o,swmAttribution:l,showQueryCatalog:c=!1,onShowQueryCatalogChange:d}){const g=Oe[e],h=f.useMemo(()=>t.entityList.filter(p=>p.trustLevel===g.trustLevel),[t.entityList,g.trustLevel]),u=Bi(t,e);return s.jsxs("div",{className:"v10-layer-detail",children:[s.jsxs("div",{className:"v10-layer-detail-header",children:[s.jsx("span",{className:"v10-layer-detail-icon",style:{color:g.color},children:g.icon}),s.jsxs("div",{children:[s.jsx("div",{className:"v10-layer-detail-title",children:g.title}),s.jsx("div",{className:"v10-layer-detail-desc",children:g.desc})]}),s.jsx("div",{className:"v10-layer-detail-actions"})]}),s.jsx("div",{className:"v10-layer-detail-body",children:s.jsx(wo,{layer:e,entities:h,tripleCount:u.length,layerTriples:u,contextGraphId:i,memory:t,activeTab:a,onTabChange:o,onSelectEntity:r,onNodeClick:n,swmAttribution:l,showQueryCatalog:c,onShowQueryCatalogChange:d})})]})}function Ar({entities:e,contextGraphId:t,scrollKey:n}){const r=Vn(o=>o.openTab),i=f.useMemo(()=>e.filter(o=>o.properties.has(jn)),[e]),a=o=>{var u,p,v;const l=(u=o.connections.find(y=>y.predicate===ds))==null?void 0:u.targetUri,c=(p=o.connections.find(y=>y.predicate===ps))==null?void 0:p.targetUri,d=((v=o.properties.get(jn))==null?void 0:v[0])??"",{ref:g,contentType:h}=Vi(l,c,d);r({id:Qi(t??"",g??o.uri,h),label:o.label,closable:!0,icon:"📄"})};return i.length===0?s.jsx("div",{className:"v10-docs-placeholder v10-layer-empty-shell",style:{flex:1},"data-cg-scroll-key":n,children:s.jsx(xe,{compact:!0,title:"No documents in this layer yet.",description:"Import a file to add document-backed entities."})}):s.jsx("div",{className:"v10-layer-detail-content","data-cg-scroll-key":n,children:s.jsx("div",{className:"v10-items-list",children:i.map(o=>{var h,u,p,v;const l=((h=o.properties.get(jn))==null?void 0:h[0])??"",c=(u=o.connections.find(y=>y.predicate===ds||y.predicate===ps))==null?void 0:u.targetUri,d=c?e.find(y=>y.uri===c):void 0,g=((p=d==null?void 0:d.properties.get(hs))==null?void 0:p[0])??((v=o.properties.get(hs))==null?void 0:v[0]);return s.jsxs("div",{className:"v10-item-row",onClick:()=>a(o),children:[s.jsx("span",{className:"v10-item-icon",children:"📄"}),s.jsxs("div",{className:"v10-item-info",children:[s.jsx("div",{className:"v10-item-name",children:o.label}),s.jsxs("div",{className:"v10-item-meta-row",children:[l&&s.jsx("span",{className:"v10-item-type",children:l}),g&&s.jsxs("span",{className:"v10-item-count",children:["· ",Math.round(parseInt(g)/1024),"KB"]})]})]}),s.jsx("button",{className:"v10-item-promote-btn",onClick:y=>{y.stopPropagation(),a(o)},children:"Open →"})]},o.uri)})})})}function Rr(e){return`SELECT ?g ?s ?p ?o WHERE {
36
+ ORDER BY DESC(?ts) LIMIT 5000`}function Ge(e){if(e!=null)return typeof e=="string"?e.startsWith('"')?e.replace(/^"/,"").replace(/"(\^\^<[^>]*>)?$/,""):e:typeof e=="object"&&e!==null&&"value"in e?String(e.value):String(e)}function Da(e){return e===`${On}AssertionCreated`?"created":e===`${On}AssertionPromoted`?"promoted":null}function Za(e){const[t,n]=f.useState([]),[r,i]=f.useState(!!e),[a,o]=f.useState(null),[l,c]=f.useState(void 0),d=f.useRef(void 0),g=f.useRef(void 0);return f.useEffect(()=>{if(!e){i(!1);return}d.current!=null&&d.current!==e&&(n([]),o(null),c(void 0),g.current=void 0);let h=!1;const u=new AbortController;let p;return d.current=e,i(!0),o(null),(async()=>{var v;try{const y=new Promise((k,N)=>{p=setTimeout(()=>{u.abort(),N(new Error(`Assertion-lifecycle query timed out after ${Math.round(bs/1e3)}s`))},bs)}),w=(async()=>{const k=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...un()},signal:u.signal,body:JSON.stringify({sparql:Ua(e),contextGraphId:e})});if(!k.ok)throw new Error(`SPARQL query failed: ${k.status}`);return k.json()})(),m=await Promise.race([w,y]);if(h||d.current!==e)return;const b=((v=m==null?void 0:m.result)==null?void 0:v.bindings)??[],x=[];for(const k of b){const N=Ge(k.event),j=Ge(k.type),_=Ge(k.assertion),z=Ge(k.name),E=Ge(k.agent),T=Ge(k.ts);if(!N||!_||!E||!T)continue;const C=Da(j);if(!C)continue;let O;if(C==="promoted"){const R=Ge(k.entityCount),G=R!=null?Number(R):NaN;if(Number.isFinite(G)&&G>0)O=G;else{const P=Ge(k.subjectEntityCount),L=P!=null?Number(P):NaN;Number.isFinite(L)&&L>=0&&(O=L)}}let $=Ge(k.subGraphName);if($===void 0){const R=Ge(k.assertionGraph);R&&($=Fa(R,e))}x.push({eventUri:N,kind:C,assertionUri:_,assertionName:z??"",agentUri:E,publishedAt:T,subGraph:$,entityCount:O})}n(x),c(e),g.current=e,o(null)}catch(y){if(h||(y==null?void 0:y.name)==="AbortError")return;o(y.message??String(y)),g.current!==e&&n([]),c(e),g.current=e}finally{p&&clearTimeout(p),h||i(!1)}})(),()=>{h=!0,u.abort(),p&&clearTimeout(p)}},[e]),f.useMemo(()=>({resultContextGraphId:l,events:t,loading:r,error:a}),[l,t,r,a])}const qa={wm:"working",swm:"shared",vm:"verified"};function Ga(e){var u,p,v,y;const t=new Map;if(!e)return t;const n="http://dkg.io/ontology/decisions/status",r="http://dkg.io/ontology/tasks/status",i="http://dkg.io/ontology/tasks/priority",a="http://dkg.io/ontology/github/state",o="http://dkg.io/ontology/decisions/Decision",l="http://dkg.io/ontology/tasks/Task",c="http://dkg.io/ontology/github/PullRequest";let d=0,g=0,h=0;for(const w of e)if(w.types.includes(o))((u=w.properties.get(n))==null?void 0:u[0])==="proposed"&&d++;else if(w.types.includes(l)){const m=(p=w.properties.get(i))==null?void 0:p[0],b=(v=w.properties.get(r))==null?void 0:v[0];m==="p0"&&b!=="done"&&b!=="cancelled"&&g++}else w.types.includes(c)&&((y=w.properties.get(a))==null?void 0:y[0])==="open"&&h++;return d>0&&t.set("decisions",{label:`${d} proposed`,tone:"warn"}),g>0&&t.set("tasks",{label:`${g} p0`,tone:"danger"}),h>0&&t.set("github",{label:`${h} open`,tone:"info"}),t}const wn=({contextGraphId:e,profile:t,selected:n,onSelect:r,entities:i,layer:a,enabledScope:o,allTriplesTotal:l})=>{const[c,d]=Ce.useState([]),[g,h]=Ce.useState(!0),u=Ce.useMemo(()=>Ga(i),[i]),p=Ce.useRef(0),v=Ce.useMemo(()=>o&&o.size>0&&o.size<3?new Set(o):o&&o.size>=3?null:a?new Set([qa[a]]):null,[o,a]),y=Ce.useMemo(()=>{if(!i)return null;const $=new Map;for(const R of i)if(!(v&&!v.has(R.trustLevel)))for(const G of R.subGraphs)$.set(G,($.get(G)??0)+1);return $},[v,i]),w=Ce.useMemo(()=>{if(!i)return null;let $=0;for(const R of i)v&&!v.has(R.trustLevel)||$++;return $},[v,i]),m=Ce.useMemo(()=>{if(!i)return null;let $=0;for(const R of i)v&&!v.has(R.trustLevel)||R.subGraphs.size>0||$++;return $},[v,i]),b=Ce.useCallback(()=>{const $=++p.current;h(!0),$t.fetchSubGraphs(e).then(R=>{$===p.current&&d(R.subGraphs??[])}).catch(()=>{}).finally(()=>{$===p.current&&h(!1)})},[e]);Ce.useEffect(()=>(b(),()=>{p.current++}),[b]),mr(e,b);const x=Ce.useMemo(()=>c.filter(Qn).map($=>{const R=t.forSubGraph($.name),G=y!==null?y.get($.name)??0:$.entityCount;return{slug:$.name,icon:R.icon??"•",color:R.color??"#64748b",displayName:R.displayName??$.name,description:R.description??$.description,rank:R.rank??99,entityCount:G,tripleCount:$.tripleCount,layerScoped:y!==null}}).sort(($,R)=>$.rank-R.rank),[c,t,y]),N=m!==null&&m>0||n===Ve;if(g&&x.length===0&&!N||x.length===0&&!N)return null;const j=w??x.reduce(($,R)=>$+R.entityCount,0),_=x.reduce(($,R)=>$+R.tripleCount,0),z={working:"Working Memory",shared:"Shared Working Memory",verified:"Verifiable Memory"},E=v?[...v].map($=>z[$]).join(" + "):null,T=E?` in ${E}`:"",O=`Total distinct entities — includes those in named subgraphs (some may belong to more than one), plus Root entities not in any subgraph · ${j} entities${T}${E?"":` · ${l??_} triples`}`,Z=`All — total distinct entities. Includes those in named subgraphs (some may belong to more than one), plus Root entities not in any subgraph. ${j} entities${T}.`;return s.jsxs("div",{className:"v10-subgraph-bar",children:[s.jsx("div",{className:"v10-subgraph-bar-label",children:"Subgraphs"}),s.jsxs("button",{type:"button",className:`v10-subgraph-chip${n===null?" active":""}`,onClick:()=>r(null),title:O,"aria-label":Z,children:[s.jsx("span",{className:"v10-subgraph-chip-icon",children:"⊚"}),s.jsx("span",{className:"v10-subgraph-chip-label",children:"All"}),s.jsx("span",{className:"v10-subgraph-chip-count",children:j})]}),x.map($=>{const R=u.get($.slug);return s.jsxs("button",{type:"button",className:`v10-subgraph-chip${n===$.slug?" active":""}${R?" has-badge":""}`,onClick:()=>r($.slug,a),title:`${$.displayName}${$.description?" · "+$.description:""} · ${$.entityCount} entities${T}${E?"":` · ${$.tripleCount} triples`}${R?" · "+R.label:""}`,style:{"--sg-color":$.color},children:[s.jsx("span",{className:"v10-subgraph-chip-icon",style:{color:$.color},children:$.icon}),s.jsx("span",{className:"v10-subgraph-chip-label",children:$.displayName}),s.jsx("span",{className:"v10-subgraph-chip-count",children:$.entityCount}),R&&s.jsxs("span",{className:`v10-subgraph-chip-badge tone-${R.tone}`,children:[s.jsx("span",{className:"v10-subgraph-chip-badge-dot"}),R.label]})]},$.slug)}),N&&(()=>{const $=m??0,R=n===Ve;return s.jsxs("button",{type:"button",className:`v10-subgraph-chip v10-subgraph-chip-root${R?" active":""}`,"data-active":R,"data-count":$,onClick:()=>r(Ve,a),title:`Entities not in any subgraph (Context Graph root) · ${$} entities${T}`,"aria-label":"Entities not in any subgraph (Context Graph root)",children:[s.jsx("span",{className:"v10-subgraph-chip-icon",children:"⊘"}),s.jsx("span",{className:"v10-subgraph-chip-label",children:"Root"}),s.jsx("span",{className:"v10-subgraph-chip-count",children:$})]})})()]})},Kn=f.lazy(()=>zi(()=>import("./index-DOGXDQkQ.js").then(e=>e.h),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.RdfGraph}))),Ba="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",Wa=new Map(Fi.map((e,t)=>[e,t]));function In(e){const t=e.trim();return!t||t.startsWith('"')?!1:t.startsWith("_:")||t.startsWith("<")&&t.endsWith(">")?!0:/\s/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function Qe(e){const t=e.trim();return t.startsWith("<")&&t.endsWith(">")?t.slice(1,-1):t}function Va(e){const t=new Set,n=new Map,r=new Map,i=new Map;for(const l of e){const c=Qe(l.subject);t.add(c);const d=Wa.get(l.predicate);if(d!==void 0){const h=vr(l.object).trim();if(h){const u=i.get(c);(u===void 0||d<u)&&(r.set(c,h),i.set(c,d))}}if(Qe(l.predicate)===Ba||!In(l.object))continue;const g=Qe(l.object);n.set(c,(n.get(c)??0)+1),n.set(g,(n.get(g)??0)+1)}const a=[...t].filter(l=>(n.get(l)??0)===0).map(l=>({uri:l,label:r.get(l)??gr(void 0,l)})).sort((l,c)=>l.label.localeCompare(c.label));if(a.length===0)return{canvasTriples:e,singletonItems:a};const o=new Set(a.map(l=>l.uri));return{canvasTriples:e.filter(l=>!o.has(Qe(l.subject))&&!o.has(Qe(l.object))),singletonItems:a}}function Qa(e){return e==="wm"?"Working Memory graph: local entities connected by entity-to-entity triples from loaded layer data.":e==="swm"?"Shared Working Memory graph: promoted shared entities connected by entity-to-entity triples from loaded layer data.":"Verifiable Memory graph: published knowledge assets, provenance anchors, and connected entity-to-entity triples from loaded layer data."}function Ka({items:e,onSelect:t}){return e.length===0?null:s.jsxs("div",{className:"v10-graph-singleton-shelf","aria-label":"Standalone entities without visible links",children:[s.jsxs("div",{className:"v10-graph-singleton-head",title:"Entities with no visible links are grouped here to keep the graph readable.",children:[s.jsx("span",{children:"Standalone entities"}),s.jsx("span",{children:e.length})]}),s.jsx("div",{className:"v10-graph-singleton-list",children:e.map(({uri:n,label:r})=>s.jsx("button",{type:"button",className:"v10-graph-singleton-item",title:n,onClick:()=>t==null?void 0:t(n),children:r},n))})]})}const Ja=2500;function ys(e,t=Ja){if(e.length<=t)return e;const n=new Map;for(const o of e)n.set(o.subject,(n.get(o.subject)??0)+1);const r=[...n.entries()].sort((o,l)=>l[1]-o[1]).map(([o])=>o),i=new Set;let a=0;for(const o of r){const l=n.get(o)??0;a+l>t||(i.add(o),a+=l)}return i.size===0&&r.length>0&&i.add(r[0]),e.filter(o=>i.has(o.subject)).slice(0,t)}function Qt({title:e,scopeLabel:t,tone:n,className:r,rail:i,overlay:a,showScopeLabel:o=!0,singletonItems:l=[],onSingletonClick:c,renderGraph:d}){const[g,h]=f.useState(!1);f.useEffect(()=>{if(!g)return;const v=y=>{y.key==="Escape"&&h(!1)};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[g]);const u=s.jsx("button",{type:"button",className:`v10-graph-expand-btn${o?"":" in-canvas"}`,onClick:()=>h(!0),title:`Expand ${e}`,"aria-label":`Expand ${e}`,children:"⤢"}),p=v=>s.jsxs(s.Fragment,{children:[o&&!v&&s.jsxs("div",{className:"v10-graph-shell-bar",children:[s.jsx("div",{className:"v10-graph-scope",title:t,children:t}),u]}),s.jsxs("div",{className:"v10-graph-body",children:[s.jsxs("div",{className:"v10-graph-canvas",children:[!o&&!v&&u,s.jsx("div",{className:"v10-graph-view",children:d(v)}),a&&s.jsx("div",{className:"v10-graph-overlay",children:a}),s.jsx(Ka,{items:l,onSelect:c})]}),i&&s.jsx("aside",{className:"v10-graph-rail",children:i})]})]});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`v10-graph-shell v10-graph-shell-${n}${r?` ${r}`:""}`,children:!g&&p(!1)}),g&&s.jsx("div",{className:"v10-graph-expanded-backdrop",role:"dialog","aria-modal":"true","aria-label":`${e} expanded`,onClick:v=>{v.target===v.currentTarget&&h(!1)},children:s.jsxs("div",{className:`v10-graph-expanded-panel v10-graph-shell-${n}`,children:[s.jsxs("div",{className:"v10-graph-expanded-head",children:[s.jsxs("div",{children:[s.jsx("div",{className:"v10-graph-expanded-title",children:e}),s.jsx("div",{className:"v10-graph-expanded-subtitle",children:t})]}),s.jsx("button",{type:"button",className:"v10-graph-expanded-close",onClick:()=>h(!1),"aria-label":`Close expanded ${e}`,children:"×"})]}),s.jsx("div",{className:"v10-graph-expanded-body",children:p(!0)})]})})]})}function $r({layer:e,triples:t,onNodeClick:n,contextGraphId:r,scopeLabel:i,trustLegendActiveLayer:a,title:o,scopeEntities:l,swmAttribution:c,layerEntities:d,nodeColorsOverride:g}){const{title:h}=Oe[e],u=o??h,p=fr(M=>M.theme),v=f.useMemo(()=>{if(e!=="vm")return;const M=new Set;for(const F of t)M.add(F.subject),In(F.object)&&M.add(F.object);return M},[t,e]),{anchors:y,decorationTriples:w}=Li(e==="vm"&&r?r:void 0,v),m=Cr(e==="swm"&&r&&!c?r:void 0),b=c??m,x=f.useMemo(()=>{if(!d||d.length===0)return t;const M=new Set;for(const F of d)M.add(De(F.uri));return Ht(t,M)},[t,d]),k=f.useMemo(()=>{const M=new Set,F=[],B=J=>{const X=`${J.subject}|${J.predicate}|${J.object}`;M.has(X)||(M.add(X),F.push({subject:J.subject,predicate:J.predicate,object:J.object}))};for(const J of x)B(J);for(const J of w)B(J);return F},[x,w]),N=k,j=f.useMemo(()=>{const M=e==="swm"?b.nodeColors:void 0;if(!(!M&&!g))return M?g?{...M,...g}:M:g},[e,b.nodeColors,g]),_=f.useMemo(()=>Mi(e,j),[e,j]),{canvasTriples:z,singletonItems:E}=f.useMemo(()=>Va(N),[N]),T=f.useMemo(()=>{if(!l||l.length===0)return E;const M=new Set(E.map(B=>Qe(B.uri)));for(const B of z)M.add(Qe(B.subject)),In(B.object)&&M.add(Qe(B.object));const F=[];for(const B of l){const J=Qe(B.uri);M.has(J)||(M.add(J),F.push({uri:J,label:B.label||gr(void 0,J)}))}return F.length===0?E:[...E,...F].sort((B,J)=>B.label.localeCompare(J.label))},[E,z,l]),C=`${r??"context"}:${e}`,O=e==="swm"&&!!r&&b.loading,Z=`${u} graph`,$=i??Qa(e),R=a===null&&!!i,G=a===null?void 0:a??e,L=e==="vm"&&y.length>0||e==="swm"&&b.palette.length>0?s.jsxs(s.Fragment,{children:[e==="vm"&&y.length>0&&s.jsx(Ya,{anchors:y}),e==="swm"&&b.palette.length>0&&s.jsx(Ha,{palette:b.palette,conflicts:b.conflicts.length})]}):null,A=f.useMemo(()=>({name:`${C}:${p}`,palette:p}),[C,p]);return k.length===0&&T.length===0?s.jsx(Qt,{title:Z,scopeLabel:$,tone:e,className:"v10-graph-view-fill",showScopeLabel:R,renderGraph:()=>s.jsx("div",{className:"v10-layer-empty-shell",children:s.jsx(xe,{compact:!0,tone:At(e),icon:Oe[e].icon,title:`No triples in ${u}`,description:"The graph will appear when this layer has connected triples."})})}):O?s.jsx(Qt,{title:Z,scopeLabel:$,tone:"swm",className:"v10-graph-view-fill",showScopeLabel:R,renderGraph:()=>s.jsx("div",{className:"v10-layer-empty-shell",children:s.jsx(xe,{compact:!0,tone:"swm",icon:Oe.swm.icon,title:"Loading Shared Working Memory attribution...",description:"Agent colors are being prepared before the graph renders."})})}):s.jsx(Qt,{title:Z,scopeLabel:$,tone:e,className:"v10-graph-view-fill",overlay:L,showScopeLabel:R,singletonItems:T,onSingletonClick:M=>n==null?void 0:n(G?{id:M,trustLayer:G}:{id:M}),renderGraph:M=>z.length>0?s.jsx(f.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Kn,{data:z,format:"triples",options:_,viewConfig:A,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:G?F=>n==null?void 0:n({...F,trustLayer:G}):n,initialFit:!0},`${C}:${M?"expanded":"inline"}:${z.length}`)}):s.jsx("div",{className:"v10-graph-placeholder v10-graph-placeholder-centered",children:"Connected graph appears when this layer has linked entities."})})}function Ha({palette:e,conflicts:t}){return s.jsxs("div",{className:"v10-swm-legend","aria-label":"SWM attribution legend",children:[s.jsxs("div",{className:"v10-swm-legend-row v10-swm-legend-head",children:[s.jsx("span",{children:"SWM attribution"}),s.jsxs("span",{className:"v10-swm-legend-count",children:[e.length," agent",e.length===1?"":"s"]})]}),e.slice(0,8).map(n=>s.jsxs("div",{className:"v10-swm-legend-row",title:n.agent,children:[s.jsx("span",{className:"v10-swm-legend-swatch",style:{background:n.color}}),s.jsx("span",{className:"v10-swm-legend-label",children:n.label}),s.jsx("span",{className:"v10-swm-legend-metric",children:n.entityCount})]},n.agent)),t>0&&s.jsxs("div",{className:"v10-swm-legend-row v10-swm-legend-conflict",children:[s.jsx("span",{className:"v10-swm-legend-swatch",style:{background:"#f59e0b"},children:"!"}),s.jsx("span",{className:"v10-swm-legend-label",children:"In review"}),s.jsx("span",{className:"v10-swm-legend-metric",children:t})]})]})}function Ya({anchors:e}){var i;const t=f.useMemo(()=>{const a=new Set;for(const o of e)for(const l of o.agents)a.add(l);return a.size},[e]),n=(i=e[0])==null?void 0:i.publishedAt,r=(()=>{if(!n)return null;try{return new Date(n).toLocaleString(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return null}})();return s.jsxs("div",{className:"v10-vm-legend","aria-label":"Verifiable Memory legend",children:[s.jsxs("div",{className:"v10-vm-legend-row v10-vm-legend-head",children:[s.jsx("span",{children:"VM provenance layer"}),s.jsxs("span",{className:"v10-vm-legend-count",children:[e.length," anchor",e.length===1?"":"s"]})]}),s.jsxs("div",{className:"v10-vm-legend-row",children:[s.jsx("span",{className:"v10-vm-legend-swatch",style:{background:"#f5a524"},children:"◉"}),s.jsx("span",{className:"v10-vm-legend-label",children:"On-chain anchor"})]}),s.jsxs("div",{className:"v10-vm-legend-row",children:[s.jsx("span",{className:"v10-vm-legend-swatch",style:{background:"#c084fc"},children:"◈"}),s.jsxs("span",{className:"v10-vm-legend-label",children:["Agent identity (",t,")"]})]}),s.jsxs("div",{className:"v10-vm-legend-row",children:[s.jsx("span",{className:"v10-vm-legend-swatch",style:{background:"#4ade80"},children:"—"}),s.jsx("span",{className:"v10-vm-legend-label",children:"Signed / anchored edge"})]}),r&&s.jsxs("div",{className:"v10-vm-legend-foot",children:["Latest: ",r]})]})}function Xa({active:e,counts:t,onSwitch:n,onShare:r,onImport:i,onRefresh:a}){const[o,l]=f.useState(!1),c=f.useRef(null),d=g=>{l(!1),n(g)};return f.useEffect(()=>{if(!o)return;const g=h=>{var p;const u=h.target;u&&((p=c.current)!=null&&p.contains(u))||l(!1)};return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[o]),s.jsxs("div",{className:"v10-layer-switcher",children:[s.jsxs("button",{className:`v10-layer-switch-btn ${e==="overview"?"active":""}`,"data-layer":"overview","aria-label":"Overview",title:"Overview",onClick:()=>d("overview"),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"◎"}),s.jsx("span",{className:"v10-layer-switch-label",children:"Overview"})]}),s.jsx("span",{className:"v10-layer-switch-separator","aria-hidden":"true"}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="wm"?"active":""}`,"data-layer":"wm","aria-label":"Working Memory",title:"Working Memory",onClick:()=>d("wm"),children:[s.jsx("span",{className:"v10-layer-switch-icon",style:{color:"#64748b"},children:"◇"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-full",children:"Working Memory"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-compact",children:"WM"}),t.wm>0&&s.jsx("span",{className:"v10-layer-switch-count",children:t.wm})]}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="swm"?"active":""}`,"data-layer":"swm","aria-label":"Shared Working Memory",title:"Shared Working Memory",onClick:()=>d("swm"),children:[s.jsx("span",{className:"v10-layer-switch-icon",style:{color:"#f59e0b"},children:"◈"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-full",children:"Shared Working Memory"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-compact",children:"SWM"}),t.swm>0&&s.jsx("span",{className:"v10-layer-switch-count",children:t.swm})]}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="vm"?"active":""}`,"data-layer":"vm","aria-label":"Verifiable Memory",title:"Verifiable Memory",onClick:()=>d("vm"),children:[s.jsx("span",{className:"v10-layer-switch-icon",style:{color:"#22c55e"},children:"◉"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-full",children:"Verifiable Memory"}),s.jsx("span",{className:"v10-layer-switch-label v10-layer-switch-label-compact",children:"VM"}),t.vm>0&&s.jsx("span",{className:"v10-layer-switch-count",children:t.vm})]}),s.jsx("span",{className:"v10-layer-switch-separator","aria-hidden":"true"}),s.jsxs("button",{className:`v10-layer-switch-btn ${e==="graph-overview"?"active":""}`,"data-layer":"graph-overview","aria-label":"Subgraphs",title:"Subgraphs",onClick:()=>d("graph-overview"),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"⌬"}),s.jsx("span",{className:"v10-layer-switch-label",children:"Subgraphs"})]}),s.jsxs("div",{ref:c,className:"v10-layer-more",onBlur:g=>{g.currentTarget.contains(g.relatedTarget)||l(!1)},children:[s.jsxs("button",{type:"button",className:`v10-layer-switch-btn v10-layer-more-btn ${e==="query"?"active":""}`,"data-layer":"query","aria-haspopup":"menu","aria-expanded":o,"aria-label":"More Context Graph views",title:"More Context Graph views",onClick:()=>l(g=>!g),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"⋯"}),s.jsx("span",{className:"v10-layer-switch-label",children:"More"})]}),o&&s.jsx("div",{className:"v10-layer-more-menu",role:"menu",children:s.jsxs("button",{type:"button",role:"menuitem",className:`v10-layer-more-item ${e==="query"?"active":""}`,onClick:()=>d("query"),children:[s.jsx("span",{className:"v10-layer-switch-icon",children:"⟐"}),"Query Catalogue"]})})]}),s.jsx("div",{className:"v10-layer-switcher-spacer"}),s.jsxs("div",{className:"v10-layer-switcher-actions",children:[s.jsxs("button",{className:"v10-layer-action-btn",onClick:r,"aria-label":"Share Context Graph",children:[s.jsx("span",{className:"v10-layer-action-icon",children:"⤴"}),s.jsx("span",{className:"v10-layer-action-label",children:"Share"})]}),s.jsxs("button",{className:"v10-layer-action-btn",onClick:i,"aria-label":"Import into Context Graph",children:[s.jsx("span",{className:"v10-layer-action-icon",children:"↑"}),s.jsx("span",{className:"v10-layer-action-label",children:"Import"})]}),s.jsx("button",{className:"v10-layer-action-btn",onClick:a,"aria-label":"Refresh Context Graph data",children:s.jsx("span",{className:"v10-layer-action-icon",children:"↻"})})]})]})}function eo({cg:e,profile:t,activeSubGraph:n,onClearSubGraph:r}){const i=e.name||t.displayName||e.id;return s.jsxs("div",{className:"v10-project-strip",style:{"--sg-color":(n==null?void 0:n.color)??t.primaryColor},children:[s.jsx("span",{className:"v10-project-strip-dot",style:{background:t.primaryColor}}),s.jsx("button",{type:"button",className:"v10-project-strip-name",onClick:n?r:void 0,disabled:!n,title:n?"Back to context graph overview":e.id,children:i}),n?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"v10-project-strip-sep",children:"›"}),s.jsxs("span",{className:"v10-project-strip-sg",children:[s.jsx("span",{className:"v10-project-strip-sg-icon",style:{color:n.color},children:n.icon??"•"}),n.displayName??n.slug]}),n.description&&s.jsx("span",{className:"v10-project-strip-desc",title:n.description,children:n.description})]}):e.description&&s.jsx("span",{className:"v10-project-strip-desc",title:e.description,children:e.description})]})}function to(e,t,n,r,i){const a=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"",o=new Set([t==null?void 0:t.agentDid,t==null?void 0:t.agentAddress].filter(d=>typeof d=="string"&&d.trim().length>0).map(Ie)),l=o.size>0;return a&&l&&o.has(Ie(a))?{label:"Curator",title:"This agent is the curator for this Context Graph.",tone:"curator"}:(e==null?void 0:e.callerInvolved)===!0?a&&!l&&n==="loading"?{label:"Role checking",title:"This agent is involved in this Context Graph; curator status is still loading.",tone:"unknown"}:a&&!l&&n==="error"?{label:"Role unknown",title:"This agent is involved in this Context Graph, but curator status could not be confirmed.",tone:"unknown"}:{label:"Joined",title:"This agent is involved in this Context Graph; curator status is shown only when identity metadata confirms it.",tone:"participant"}:(e==null?void 0:e.callerInvolved)===!1?{label:"Not joined",title:"This agent is not listed as curator or participant for this Context Graph.",tone:"viewer"}:i==="ok"&&r.map(d=>d.trim()).filter(Boolean).some(d=>o.has(Ie(d)))?{label:"Joined",title:"This agent is listed as a participant for this Context Graph.",tone:"participant"}:{label:"Role unknown",title:"The node did not provide enough role metadata for this Context Graph.",tone:"unknown"}}function no(e,t,n){if(Gn(e==null?void 0:e.accessPolicy)==="public")return{id:"participants",value:"Open",label:"Public access",tooltip:"Public Context Graphs do not have an authoritative allowlist count."};if(n==="loading")return{id:"participants",value:"...",label:"Agents with access",tooltip:"Participant list is loading."};if(n==="error")return{id:"participants",value:"Unavailable",label:"Agents with access",tooltip:"Participant list unavailable; access count is unknown."};const i=new Set(t.map(o=>o.trim()).filter(Boolean).map(Ie)),a=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"";return a&&i.add(Ie(a)),{id:"participants",value:i.size.toLocaleString(),label:"Agents with access",tooltip:"Includes the curator plus allowlisted participants reported by the node."}}function so(e){const t=Gn(e);return t==="public"?{label:"Public",title:"Public Context Graph.",tone:"public"}:t==="private"?{label:"Curated",title:"Curated Context Graph with access controlled by the curator.",tone:"curated"}:{label:"Access unknown",title:"The node did not provide an access policy for this Context Graph.",tone:"unknown"}}function ro({cg:e,currentAgent:t,currentAgentStatus:n="ok"}){var l,c;const r=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"";if(!r)return"unknown";const i=((l=t==null?void 0:t.agentDid)==null?void 0:l.trim())??"",a=((c=t==null?void 0:t.agentAddress)==null?void 0:c.trim())??"",o=i||a;return o?Ie(r)===Ie(o)?"curator":"not-curator":"unknown"}function io(e){return new Set([e==null?void 0:e.agentDid,e==null?void 0:e.agentAddress].filter(t=>typeof t=="string"&&t.trim().length>0).map(Ie))}function ao({cg:e,memory:t,subGraphCount:n,subGraphFetchFailed:r=!1,participants:i,participantsStatus:a="ok",currentAgent:o,currentAgentStatus:l="ok",onSwitchLayer:c,onOpenPrimer:d}){var A,M,F;const{wm:g,swm:h,vm:u}=t.counts,p=g+h+u,v=to(e,o??null,l,i,a),y=so(e==null?void 0:e.accessPolicy),w=no(e,i,a),m=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"",b=m?Ie(m):"",x=Gn(e==null?void 0:e.accessPolicy)==="public",k=io(o??null),N=Object.values(t.layerStatus??{}),j=N.filter(B=>B==="error").length,_=!t.loading&&N.length===3&&j===3,z=!t.loading&&j>0,E=t.loading?"Loading memory layers...":_||t.error?"Live memory counts are unavailable.":t.partial||z?"One or more layer counts are currently a lower bound.":"Canonical current-layer entity counts.",T=_?"Unavailable":p.toLocaleString(),{total:C}=Bn(t),O=!t.loading&&(t.partial||z),Z=_?"Unavailable":t.loading&&C===0?"...":O?`${C.toLocaleString()}+`:C.toLocaleString(),$=_?"Live triple counts are unavailable.":O?"One or more layer triple counts are currently a lower bound.":"Canonical triple total across all layers.",R=n==null?r?"Unavailable":"...":n.toLocaleString(),G=n==null?r?"Sub-graph list is currently unavailable.":"Sub-graph count is loading.":"Topical partitions inside this Context Graph.",P=[{key:"wm",label:"Working Memory",desc:"Private staging area",count:g,status:((A=t.layerStatus)==null?void 0:A.wm)??"ok",color:"#64748b"},{key:"swm",label:"Shared Working Memory",desc:"Collaborative review",count:h,status:((M=t.layerStatus)==null?void 0:M.swm)??"ok",color:"#f59e0b"},{key:"vm",label:"Verifiable Memory",desc:"Published on-chain",count:u,status:((F=t.layerStatus)==null?void 0:F.vm)??"ok",color:"#22c55e"}],L=P.some(B=>B.status==="error");return s.jsxs("div",{className:"v10-po",children:[s.jsxs("div",{className:"v10-po-identity","data-section":"identity",children:[s.jsxs("div",{className:"v10-po-identity-pairs",children:[s.jsxs("div",{className:"v10-po-identity-pair",children:[s.jsx("span",{className:"v10-po-identity-label",children:"Your role:"}),s.jsx("span",{className:"v10-po-badge","data-role":v.tone,title:v.title,children:v.label})]}),s.jsxs("div",{className:"v10-po-identity-pair",children:[s.jsx("span",{className:"v10-po-identity-label",children:"Context Graph:"}),s.jsx("span",{className:"v10-po-badge","data-cg-type":y.tone,title:y.title,children:y.label})]})]}),d&&s.jsx("button",{type:"button",className:"v10-po-identity-primer",onClick:d,title:"Open the Context Graph primer",children:"What is a Context Graph?"})]}),s.jsxs("div",{"data-section":"at-a-glance",className:"v10-po-stat-block",children:[s.jsx("div",{className:"v10-po-section-title",children:"At a glance"}),s.jsx(pn,{className:"v10-po-stat-strip",items:[{id:"entities",value:T,label:"Entities",tooltip:E},{id:"triples",value:Z,label:"Triples",tooltip:$},{id:"subgraphs",value:R,label:"Subgraphs",tooltip:G},w]})]}),s.jsxs("div",{className:"v10-po-pipeline","data-section":"pipeline","aria-label":"Knowledge Pipeline",children:[s.jsx("div",{className:"v10-po-pipeline-head",children:s.jsxs("div",{children:[s.jsx("div",{className:"v10-po-section-title",children:"Knowledge Pipeline"}),s.jsx("div",{className:"v10-po-section-desc",children:"Entities move from private staging to shared review; published assertion bundles become Knowledge Assets with on-chain provenance."})]})}),s.jsx("div",{className:"v10-po-pipeline-track","aria-hidden":"true",children:!L&&p>0?P.map(B=>{const J=B.count>0?B.count/p*100:0;return s.jsx("span",{className:`v10-po-pipeline-seg ${B.key}`,style:{width:`${J}%`,background:B.color}},B.key)}):s.jsx("span",{className:"v10-po-pipeline-empty"})}),s.jsx("div",{className:"v10-po-pipeline-steps",children:P.map((B,J)=>s.jsxs("button",{type:"button",className:`v10-po-pipeline-step ${B.key}`,onClick:()=>c==null?void 0:c(B.key),style:{"--po-layer-color":B.color},children:[s.jsx("span",{className:"v10-po-pipeline-step-index",children:J+1}),s.jsxs("span",{className:"v10-po-pipeline-step-copy",children:[s.jsx("span",{className:"v10-po-pipeline-step-label",children:B.label}),s.jsx("span",{className:"v10-po-pipeline-step-desc",children:B.desc})]}),s.jsx("span",{className:"v10-po-pipeline-step-count",children:B.status==="error"?"Unavailable":`${B.count.toLocaleString()} ${We(B.key,B.count)}`})]},B.key))})]}),s.jsxs("div",{className:"v10-po-people","data-section":"participants",children:[s.jsx("div",{className:"v10-po-section-title",children:"Participant agents"}),(()=>{const B="did:dkg:agent:",J=V=>V.toLowerCase().startsWith(B)?V.slice(B.length):V,X=new Set,Y=[];if(m&&a==="ok"){const V=Ie(m);X.add(V),Y.push({display:J(m),full:m,canonical:V})}if(a==="ok")for(const V of i){const re=Ie(V);X.has(re)||(X.add(re),Y.push({display:J(V),full:V,canonical:re}))}if(Y.length===0){const V=x?"This Context Graph is public — anyone can subscribe.":a==="loading"?"Loading participant agents...":a==="error"?"Participant list unavailable.":"No participant agents recorded yet.";return s.jsx("div",{className:"v10-po-people-empty",children:V})}return s.jsx("div",{className:"v10-po-participants-list",children:Y.map(({display:V,full:re,canonical:ye})=>{const Ne=k.has(ye),Re=!!b&&ye===b,q=`${V.slice(0,6)}…${V.slice(-4)}`,ne=[q];return Ne&&ne.push("you"),Re&&ne.push("curator"),s.jsxs("span",{className:`v10-po-participant${Ne?" is-self":""}${Re?" is-curator":""}`,title:re,"aria-label":ne.join(" "),children:[s.jsx("span",{className:"v10-po-participant-name",children:q}),Ne&&s.jsx("span",{className:"v10-po-participant-tag",children:"you"}),Re&&s.jsx("span",{className:"v10-po-participant-tag",children:"curator"})]},ye)})})})()]})]})}function oo({contextGraphId:e,curatorStatus:t,onParticipantsChanged:n}){const[r,i]=f.useState([]),[a,o]=f.useState(null),[l,c]=f.useState("loading"),d=f.useRef(0),g=f.useCallback(()=>{if(t!=="curator"){i([]),c("idle");return}const p=++d.current;c("loading"),dr(e).then(v=>{d.current===p&&(i(v.requests.filter(y=>y.status==="pending")),c("idle"))}).catch(()=>{d.current===p&&(i([]),c("error"))})},[e,t]);if(f.useEffect(()=>(g(),()=>{d.current++}),[g]),Ui(f.useCallback(p=>{var v;p.type!=="join_request"&&p.type!=="join_approved"&&p.type!=="join_rejected"||((v=p.data)==null?void 0:v.contextGraphId)===e&&g()},[e,g])),t==="not-curator")return null;if(t==="unknown")return s.jsxs("section",{className:"v10-po-join","data-section":"join-requests",children:[s.jsx("header",{className:"v10-po-join-head",children:s.jsx("span",{className:"v10-po-section-title",children:"Pending join requests"})}),s.jsx("div",{className:"v10-po-join-empty",children:"Verifying access…"})]});const h=async p=>{o(p);try{await pr(e,p),i(v=>v.filter(y=>y.agentAddress!==p)),n==null||n()}catch{}finally{o(null)}},u=async p=>{o(p);try{await hr(e,p),i(v=>v.filter(y=>y.agentAddress!==p)),n==null||n()}catch{}finally{o(null)}};return s.jsxs("section",{className:"v10-po-join","data-section":"join-requests",children:[s.jsxs("header",{className:"v10-po-join-head",children:[s.jsx("span",{className:"v10-po-section-title",children:"Pending join requests"}),s.jsx("span",{className:"v10-po-join-count","data-empty":r.length===0?"true":"false",children:r.length})]}),l==="loading"?s.jsx("div",{className:"v10-po-join-empty",children:"Loading join requests..."}):l==="error"?s.jsx("div",{className:"v10-po-join-empty",children:"Join requests are currently unavailable."}):r.length===0?s.jsx("div",{className:"v10-po-join-empty",children:"No pending join requests."}):s.jsx("div",{className:"v10-po-join-list",children:r.map(p=>s.jsxs("div",{className:"v10-po-join-item",children:[s.jsxs("div",{className:"v10-po-join-info",children:[s.jsx("span",{className:"v10-po-join-name",children:p.name||`${p.agentAddress.slice(0,6)}…${p.agentAddress.slice(-4)}`}),s.jsxs("span",{className:"v10-po-join-addr",title:p.agentAddress,children:[p.agentAddress.slice(0,10),"…"]})]}),s.jsxs("div",{className:"v10-po-join-actions",children:[s.jsx("button",{className:"v10-po-join-btn approve",onClick:()=>h(p.agentAddress),disabled:a===p.agentAddress,children:a===p.agentAddress?"…":"✓ Approve"}),s.jsx("button",{className:"v10-po-join-btn reject",onClick:()=>u(p.agentAddress),disabled:a===p.agentAddress,"aria-label":"Reject join request",children:"✕"})]})]},p.agentAddress))})]})}function lo({onOpenPrimer:e}){return s.jsxs("div",{className:"v10-po-primer-footer","data-section":"primer",children:[s.jsx("span",{className:"v10-po-primer-footer-lede",children:"New here?"}),s.jsx("span",{className:"v10-po-primer-footer-arrow","aria-hidden":"true",children:"→"}),s.jsx("button",{type:"button",className:"v10-po-primer-footer-link",onClick:e,children:"What is a Context Graph?"}),s.jsx("div",{className:"v10-po-primer-footer-sub",children:"A short primer on context graphs, the WM → SWM → VM pipeline, and how participant agents collaborate."})]})}const co=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function uo(e,t=0){const n=br(o=>o.trackedIds),r=n.join(","),{data:i,loading:a}=ft(async()=>{if(n.length===0)return{wallets:[],ownerPublish:!1,resolved:!1};const o=await Di().catch(()=>null),l=(o==null?void 0:o.wallets)??[];let c=!1;try{const{contextGraphs:g}=await Zi(),h=(g??[]).find(p=>(p==null?void 0:p.id)===e),u=h==null?void 0:h.curator;if(u){const p=await qi().catch(()=>null);c=!!(p!=null&&p.agentDid&&Ie(u)===Ie(p.agentDid))}}catch{c=!1}return{wallets:await Promise.all(l.map(async g=>{var k;const h=(k=o==null?void 0:o.balances)==null?void 0:k.find(N=>co(N.address,g)),u=h==null,p=h!=null&&Number(h.eth)>0,v=h!=null&&Number(h.trac)>0;let y,w=!1,m=!1,b,x=!1;for(const N of n){const j=await cs(N,g,{extended:!0}).catch(()=>null);if(j===null){x=!0;continue}const _=us(j);if(_.outcome==="inconclusive"){x=!0;continue}if(_.outcome!=="unregistered"){if(_.outcome==="covers"){y={accountId:N,discountBps:j.discountBps,untracked:!1};break}_.dead&&(w=!0,b||(b=N)),_.hasBudget||(m=!0)}}if(!y&&!x&&!w&&!m){const N=await Gi(g).catch(()=>{});if(N===void 0)x=!0;else if(N.accountId!=null&&!n.includes(N.accountId)){const j=N.accountId,_=await cs(j,g,{extended:!0}).catch(()=>null);if(_===null)x=!0;else{const z=us(_);z.outcome==="covers"?y={accountId:j,discountBps:_.discountBps,untracked:!0}:z.outcome==="uncovered"?(z.dead&&(w=!0,b||(b=j)),z.hasBudget||(m=!0)):x=!0}}}return{wallet:g,covered:!!y,accountId:y==null?void 0:y.accountId,discountBps:y==null?void 0:y.discountBps,coverUntracked:(y==null?void 0:y.untracked)??!1,deadAccountId:y?void 0:b,inconclusive:!y&&x,balanceUnknown:u,gasFunded:p,hasTrac:v,sawExpired:w,sawInsolvent:m}})),ownerPublish:c,resolved:l.length>0}},[r,e],t);return f.useMemo(()=>{const o=(i==null?void 0:i.wallets)??[],l=(i==null?void 0:i.ownerPublish)??!1,c=(i==null?void 0:i.resolved)??!1;if(n.length===0||!c||o.length===0)return{verdict:"unknown",loading:a,ownerPublish:l,anyGasFunded:!1,reasons:[],conditions:{approved:!1,gasFunded:!1,notExpired:!1,solvent:!1},wallets:o};const d=o.filter(m=>m.covered),g=o.filter(m=>!m.covered),h=g.filter(m=>!m.inconclusive&&!m.balanceUnknown),u=g.filter(m=>m.inconclusive||m.balanceUnknown),p={approved:g.length===0,gasFunded:o.every(m=>m.gasFunded),notExpired:!o.some(m=>m.sawExpired),solvent:!o.some(m=>m.sawInsolvent)};let v;const y=[];if(g.length===0)d.some(m=>m.gasFunded||m.balanceUnknown)?v="eligible":(v="fallthrough-no-funds",y.push("every approved signing wallet is out of gas"));else if(h.length===0&&u.length>0)v="unknown";else{const m=o.some(b=>(b.covered||b.hasTrac)&&b.gasFunded);!m&&u.length>0?v="unknown":(v=m?"fallthrough":"fallthrough-no-funds",y.push(`${d.length} of ${o.length} signing wallets approved`),o.some(b=>b.sawExpired)&&y.push("a PCA has expired or been fully swept"),o.some(b=>b.sawInsolvent)&&y.push("a PCA is out of budget"),p.gasFunded||y.push("a signing wallet has no gas"),g.some(b=>b.inconclusive)&&y.push("a wallet’s PCA coverage couldn’t be checked"),g.some(b=>b.balanceUnknown)&&y.push("a signing wallet’s balance couldn’t be checked"))}const w=d.reduce((m,b)=>(b.discountBps??-1)>((m==null?void 0:m.discountBps)??-1)?b:m,void 0);return{verdict:v,loading:a,accountId:w==null?void 0:w.accountId,discountBps:w==null?void 0:w.discountBps,accountUntracked:w==null?void 0:w.coverUntracked,ownerPublish:l,anyGasFunded:o.some(m=>m.gasFunded||m.balanceUnknown),reasons:y,conditions:p,wallets:o}},[i,a,n.length])}function po(e){return e.verdict==="fallthrough-no-funds"&&!(e.ownerPublish&&e.anyGasFunded)}function ho(e){const t=br(o=>o.trackedIds),n=uo(e,3e4),r=po(n),i="Publish will fail — no signing wallet can fund it (coverage or gas).",a=t.length>0;return{blocked:r,reason:i,chipVisible:a,eligibility:n}}function mo({verdict:e,accountId:t,discountBps:n,accountUntracked:r,ownerPublish:i,id:a}){return s.jsx("div",{className:"v10-pca-publish-chip",id:a,"data-testid":"pca-publish-eligibility",children:s.jsx($a,{variant:"chip",verdict:e,accountId:t,discountBps:n,accountUntracked:r,ownerPublish:i})})}function Jn({title:e,agent:t,footnote:n,dismissed:r,onDismiss:i,children:a}){return s.jsxs("div",{className:`v10-gen-widget ${r?"dissolved":""}`,children:[s.jsxs("div",{className:"v10-gen-widget-header",children:[s.jsx("span",{className:"v10-gen-widget-title",children:e}),s.jsxs("div",{className:"v10-gen-widget-right",children:[t&&s.jsxs("span",{className:"v10-gen-widget-agent",children:[s.jsx("span",{className:"v10-gen-widget-agent-dot"}),t]}),i&&s.jsx("button",{className:"v10-gen-widget-dismiss",onClick:i,children:"✕"})]})]}),s.jsx("div",{className:"v10-gen-widget-body",children:a}),n&&s.jsx("div",{className:"v10-gen-widget-footnote",children:n})]})}function fo({entities:e}){const t=et(),n=f.useMemo(()=>{const r=new Map;for(const i of e){const{icon:a,type:o}=dn(i,t),l=r.get(o);l?l.count++:r.set(o,{icon:a,count:1})}return[...r.entries()].sort((i,a)=>a[1].count-i[1].count)},[e,t]);return n.length===0?null:s.jsx(Jn,{title:"Entity Types",children:s.jsx(pn,{compact:!0,items:n.map(([r,{icon:i,count:a}])=>({id:r,label:`${i} ${r}`,value:a}))})})}function go({entities:e,entityCount:t,triples:n,layer:r}){const i=f.useMemo(()=>e.filter(l=>l.properties.has("http://dkg.io/ontology/sourceContentType")).length,[e]),a=f.useMemo(()=>e.reduce((l,c)=>l+c.connections.length,0),[e]),o=e.length>0?(a/e.length).toFixed(1):"0";return s.jsx(Jn,{title:"Layer Stats",children:s.jsx(pn,{compact:!0,layer:r,items:[{id:"entities",label:We(r,t),value:t},{id:"triples",label:"Triples",value:n},{id:"connections",label:"Connections",value:a},{id:"avg",label:"Avg. connections / entity",value:o},...i>0?[{id:"documents",label:"Documents",value:i}]:[]]})})}function Er(e,t){const[n,r]=f.useState(!1),[i,a]=f.useState(null),[o,l]=f.useState(null),c=f.useCallback(async(d,g)=>{r(!0),l(null),a(null);try{const h=await d();a(h),e==null||e({ok:!0,text:h}),t==null||t()}catch(h){const u=g(h);l(u),e==null||e({ok:!1,text:u})}finally{r(!1)}},[e,t]);return{busy:n,result:i,error:o,run:c}}function _r({title:e,footnote:t,context:n,result:r,error:i,extras:a,children:o}){return s.jsxs(Jn,{title:e,footnote:t,children:[s.jsx("div",{className:"v10-decision-context",style:{marginBottom:10},children:n}),r&&s.jsxs("div",{"data-testid":"layer-action-result",style:{fontSize:11,color:"var(--text-success)",marginBottom:8},children:["✓ ",r]}),i&&s.jsxs("div",{"data-testid":"layer-action-error",style:{fontSize:11,color:"var(--text-danger)",marginBottom:8},children:["✕ ",i]}),a,s.jsx("div",{className:"v10-decision-actions",children:o})]})}function vo({count:e,contextGraphId:t,onComplete:n,onResult:r}){const{busy:i,result:a,error:o,run:l}=Er(r,n),c=f.useCallback(()=>{let h=null;l(async()=>{const u=await Yt(t,"wm");let p=0;for(const y of u)h=y.name,(await Xt(t,y.name,y.subGraph?{subGraphName:y.subGraph}:{})).promotedCount===0&&(p+=1);const v=u.length-p;if(v>0){const y=p>0?` (${p} already shared or still committing)`:"";return`Shared ${v} complete Knowledge Asset${v!==1?"s":""} to Shared Memory${y}`}return"No Knowledge Assets were newly shared — all were already in Shared Memory or still committing."},u=>{const p=en(h??"an assertion",u);return p?p.message:(u==null?void 0:u.message)??"Action failed"})},[t,l]);if(e===0)return null;const d="#f59e0b",g=We("wm",e).toLowerCase();return s.jsx(_r,{title:"Share complete Knowledge Assets",footnote:"Shares each complete owning Knowledge Asset atomically to Shared Working Memory.",context:s.jsxs(s.Fragment,{children:[e," eligible ",g," will be shared through their complete owning Knowledge Assets for collaborative review."]}),result:a,error:o,children:s.jsx("button",{"data-testid":"widget-promote-all-btn",className:"v10-decision-btn approve",style:{borderColor:`${d}50`,color:"var(--text-warning)",background:`${d}15`,opacity:i?.5:1},disabled:i,onClick:c,children:i?"...":"✓ Share Complete KAs → Shared"})})}function bo({count:e,contextGraphId:t,onComplete:n,onResult:r}){const[i,a]=f.useState(null),{busy:o,result:l,error:c,run:d}=Er(r,n),g=ho(t),h=f.useId(),u=f.useId(),p=[g.chipVisible?h:null,g.blocked?u:null].filter(Boolean).join(" ")||void 0,v=f.useCallback(()=>{g.blocked||d(async()=>{a(null);const w=await Yt(t,"swm"),m=await yr(t,w),b=xr(m),x=b?` — ⚠ ${b}`:"";if(m.published>0){const k=m.failures.length?` (${m.failures.length} assertion${m.failures.length===1?"":"s"} could not be published)`:"",N=m.partial>0?` — ⚠ ${m.partial}: ${tn(m.partialError)}`:"";return a(m.convictionCostCovered??null),`Published ${m.published} knowledge asset${m.published!==1?"s":""} to Verifiable Memory${k}${N}${x}`}if(w.length===0)return"Nothing to publish — promote assertions to Shared Memory first.";if(b&&m.failures.length===0)return`⚠ ${b}`;throw new Error(`${m.failures[0]?`${m.failures[0].name}: ${m.failures[0].error}`:"Publish failed"}${x}`)},w=>(w==null?void 0:w.message)??"Action failed")},[t,d,g.blocked]);if(e===0)return null;const y=We("swm",e).toLowerCase();return s.jsx(_r,{title:"Publish",footnote:`Moves ${y} from this layer to Verifiable Memory.`,context:s.jsxs(s.Fragment,{children:[e," ",y," in this layer can be published to Verifiable Memory on-chain."]}),result:l,error:c,extras:s.jsxs(s.Fragment,{children:[s.jsx(Bi,{convictionCostCovered:i}),g.chipVisible&&s.jsx(mo,{...g.eligibility,id:h}),g.blocked&&s.jsx("span",{id:u,className:"v10-sr-only",children:g.reason})]}),children:s.jsx("button",{"data-testid":"widget-publish-vm-btn",className:"v10-decision-btn primary-cta publish-vm",style:{opacity:o||g.blocked?.5:1},disabled:o,"aria-disabled":g.blocked||void 0,title:g.blocked?g.reason:void 0,"aria-describedby":p,onClick:v,children:o?"...":"◉ Publish to Verifiable Memory"})})}function yo({layer:e,entities:t,entityCount:n,actionEntityCount:r=n,tripleCount:i,contextGraphId:a,onComplete:o}){const[l,c]=f.useState(null),d=l&&s.jsxs("div",{"data-testid":l.ok?"layer-action-result":"layer-action-error",style:{fontSize:11,color:l.ok?"var(--text-success)":"var(--text-danger)",marginBottom:8},children:[l.ok?"✓":"✕"," ",l.text]});return n===0?s.jsxs("div",{className:"v10-layer-widgets-strip empty",children:[d,s.jsx(xe,{compact:!0,tone:At(e),icon:Oe[e].icon,title:`No ${We(e,2).toLowerCase()} yet`,description:e==="wm"?"Import data or chat with agents to populate Working Memory.":e==="swm"?"Seal and share complete Knowledge Assets from Working Memory with the team.":"Publish complete Knowledge Assets from Shared Working Memory to verify them on-chain."})]}):s.jsxs("div",{className:"v10-layer-widgets-strip",children:[s.jsxs("div",{className:"v10-layer-widgets-strip-stats",children:[s.jsx(go,{entities:t,entityCount:n,triples:i,layer:e}),s.jsx(fo,{entities:t})]}),(e==="wm"||e==="swm")&&a&&r>0&&s.jsx("div",{className:"v10-layer-widgets-strip-action",children:e==="wm"?s.jsx(vo,{count:r,contextGraphId:a,onComplete:o,onResult:c}):s.jsx(bo,{count:r,contextGraphId:a,onComplete:o,onResult:c})})]})}const xo={working:{layerKey:"wm",icon:"◇",label:"Working"},shared:{layerKey:"swm",icon:"◈",label:"Shared"},verified:{layerKey:"vm",icon:"◉",label:"Verifiable"}},jo=new Set(["http://dkg.io/ontology/profile/QueryCatalog","http://dkg.io/ontology/profile/SavedQuery"]);function wo(e){return e.types.some(t=>jo.has(t))}function Ar({entities:e,layerKey:t,layerIcon:n,onSelectEntity:r,onOpenAgent:i,externallySorted:a=!1,sortLabel:o,headerExtra:l,timestampPredicate:c,perEntityTrustBadge:d=!1}){const g=et(),h=It(),u=We(t,e.length).toLowerCase(),p=f.useMemo(()=>{if(a)return e;const w=[...e];return w.sort((m,b)=>{const x=m.tripleCount??0;return(b.tripleCount??0)-x}),w},[e,a]),v=t==="vm"?"Verifiable":t==="swm"?"Shared":"Working";if(e.length===0)return s.jsx("div",{className:"v10-entity-list empty",children:s.jsx(xe,{compact:!0,tone:At(t),icon:n,title:`No ${We(t,2).toLowerCase()} yet`,description:`This view will fill when matching ${We(t,2).toLowerCase()} are available.`})});const y=o??(a?"click to open":"sorted by triples · click to open");return s.jsxs("div",{className:"v10-entity-list",children:[s.jsxs("div",{className:"v10-entity-list-header",children:[s.jsxs("span",{className:"v10-entity-list-count",children:[p.length," ",u]}),s.jsx("span",{className:"v10-entity-list-hint",children:y}),l&&s.jsx("span",{className:"v10-entity-list-extra",children:l})]}),p.map(w=>{const{icon:m,type:b}=dn(w,g),x=w.tripleCount??0,k=Wn(w),N=k?h==null?void 0:h.get(k):null,j=c?Vt(w,c):null;return s.jsxs("div",{className:"v10-entity-card",onClick:_=>{_.stopPropagation(),r(w.uri)},children:[s.jsx("span",{className:"v10-entity-card-icon",children:m}),s.jsxs("div",{className:"v10-entity-card-main",children:[s.jsx("div",{className:"v10-entity-card-title",children:w.label}),s.jsxs("div",{className:"v10-entity-card-meta",children:[(N||k)&&s.jsx(gt,{agent:N??void 0,fallbackUri:k??void 0,size:"sm",onOpenAgent:i}),b&&b!=="Entity"&&s.jsxs("span",{className:"v10-entity-type-pill",children:[m," ",b]}),j!=null&&s.jsx("span",{className:"v10-entity-card-timestamp",title:new Date(j).toLocaleString(),children:Vi(j)}),s.jsxs("span",{className:"v10-entity-card-triples",children:[x," triples"]})]})]}),d?(()=>{const _=xo[w.trustLevel];return s.jsxs("span",{className:`v10-trust-badge ${_.layerKey}`,title:`${_.label} Memory`,children:[_.icon," ",_.label]})})():s.jsxs("span",{className:`v10-trust-badge ${t}`,children:[n," ",v]})]},w.uri)})]})}function ko({layer:e,entities:t,tripleCount:n,layerTriples:r,contextGraphId:i,memory:a,activeTab:o,onTabChange:l,onSelectEntity:c,onNodeClick:d,footer:g,swmAttribution:h,showQueryCatalog:u=!1,onShowQueryCatalogChange:p}){var _;const v=Oe[e],y=We(e,2),w=f.useMemo(()=>t.filter(z=>!wo(z)).length,[t]),m=((_=a.layerStatus)==null?void 0:_.vm)??(a.loading?"loading":a.error?"error":"ok"),b=e==="vm"&&m==="loading"&&t.length===0,x=e==="vm"&&m==="error"&&t.length===0,k=e==="vm"&&m==="ok"&&t.length===0,N=a.counts[e],j=z=>E=>{E.stopPropagation(),l(z)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"v10-layer-expand-tabs",children:[s.jsx("button",{className:`v10-layer-expand-tab ${o==="items"?"active":""}`,onClick:j("items"),children:y}),e!=="vm"&&s.jsx("button",{className:`v10-layer-expand-tab ${o==="assertions"?"active":""}`,onClick:j("assertions"),children:"Assertions"}),s.jsx("button",{className:`v10-layer-expand-tab ${o==="graph"?"active":""}`,onClick:j("graph"),children:"Graph"}),s.jsx("button",{className:`v10-layer-expand-tab ${o==="docs"?"active":""}`,onClick:j("docs"),children:"Documents"}),e!=="vm"&&p&&s.jsxs("label",{className:"v10-query-catalog-visibility",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:z=>p(z.target.checked)}),s.jsx("span",{children:"Show query catalog"})]})]}),o==="items"&&s.jsxs("div",{className:"v10-layer-expand-body entities-tab","data-cg-scroll-key":`layer:${e}:items`,children:[e==="vm"&&!b&&!x&&s.jsx(No,{entities:t,tripleCount:n,contextGraphId:i}),b?s.jsx("div",{className:"v10-layer-widgets-strip empty",children:s.jsx(xe,{compact:!0,tone:"vm",icon:Oe.vm.icon,title:"Loading Verifiable Memory...",description:"Knowledge Assets are being read from the verified layer."})}):x?s.jsx("div",{className:"v10-layer-widgets-strip empty",children:s.jsx(xe,{compact:!0,tone:"vm",icon:Oe.vm.icon,title:"Verifiable Memory status unavailable.",description:"This node could not read the verified layer right now."})}):!k&&s.jsxs(s.Fragment,{children:[s.jsx(yo,{layer:e,entities:t,entityCount:N,actionEntityCount:w,tripleCount:n,contextGraphId:i,onComplete:a.refresh}),s.jsx(Ar,{entities:t,layerKey:e,layerIcon:v.icon,onSelectEntity:c})]}),g]}),o==="assertions"&&e!=="vm"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(So,{contextGraphId:i,layer:e,includeQueryCatalog:u,onComplete:a.refresh,scrollKey:`layer:${e}:assertions`})}),o==="graph"&&s.jsx("div",{className:"v10-layer-expand-body full-width","data-cg-scroll-key":`layer:${e}:graph`,children:s.jsx($r,{layer:e,triples:r,onNodeClick:d,contextGraphId:i,swmAttribution:e==="swm"?h:void 0,layerEntities:t})}),o==="docs"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(Tr,{entities:t,contextGraphId:i,scrollKey:`layer:${e}:docs`})})]})}function No({entities:e,tripleCount:t,contextGraphId:n}){const r=e.length,i=new Set;for(const o of e)for(const l of o.types)i.add(l);const a=i.size;return r===0?s.jsxs("div",{className:"v10-vm-hero v10-vm-hero-empty",children:[s.jsxs("div",{className:"v10-vm-hero-title",children:[s.jsx("span",{className:"v10-vm-hero-badge",children:"◉ Verifiable Memory"}),s.jsxs("div",{className:"v10-vm-hero-heading",children:[s.jsx("span",{className:"v10-vm-hero-headline",children:"Nothing published yet"}),s.jsxs("span",{className:"v10-vm-hero-context",title:n,children:["Context Graph: ",n]})]})]}),s.jsx(xe,{compact:!0,className:"v10-vm-empty-state",tone:"vm",icon:Oe.vm.icon,title:"No Knowledge Assets yet.",description:"Publish complete Knowledge Assets from Shared Working Memory to verify them on-chain."})]}):s.jsxs("div",{className:"v10-vm-hero",children:[s.jsxs("div",{className:"v10-vm-hero-title",children:[s.jsx("span",{className:"v10-vm-hero-badge",children:"◉ Verifiable Memory"}),s.jsxs("div",{className:"v10-vm-hero-heading",children:[s.jsx("span",{className:"v10-vm-hero-headline",children:"On-chain anchored · cryptographically signed"}),s.jsxs("span",{className:"v10-vm-hero-context",title:n,children:["Context Graph: ",n]})]})]}),s.jsx(pn,{className:"v10-vm-hero-stats",layer:"vm",items:[{id:"assets",value:r,label:"Knowledge Assets"},{id:"triples",value:t.toLocaleString(),label:"Verifiable Triples"},{id:"types",value:a,label:"Entity Types"}]}),s.jsxs("div",{className:"v10-vm-hero-strip",children:[s.jsxs("div",{className:"v10-vm-hero-chip",title:"Multi-agent endorsement",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#22c55e"}}),"Consensus"]}),s.jsxs("div",{className:"v10-vm-hero-chip",title:"Published to the DKG blockchain anchor",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#3b82f6"}}),"On-chain"]}),s.jsxs("div",{className:"v10-vm-hero-chip",title:"Each contribution bound to a DID",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#a855f7"}}),"Agent Identity"]}),s.jsxs("div",{className:"v10-vm-hero-chip",title:"Tamper-evident via content hashing",children:[s.jsx("span",{className:"v10-vm-hero-chip-dot",style:{background:"#f59e0b"}}),"Content Hash"]})]})]})}function So({contextGraphId:e,layer:t,includeQueryCatalog:n=!1,onComplete:r,scrollKey:i}){const{data:a,loading:o,refresh:l}=ft(()=>Yt(e,t,{includeQueryCatalog:n}),[e,t,n],0),{data:c}=ft(()=>Ji(e),[e,t],0),[d,g]=f.useState(null),[h,u]=f.useState(null),[p,v]=f.useState(null),y=f.useCallback(async N=>{g(N.graphUri),u(null),v(null);try{if(t==="wm"){const j=await Xt(e,N.name,N.subGraph?{subGraphName:N.subGraph}:{}),_=jr(N.name,j);u(_.message)}else{const j=await wr(e,N.name,N.subGraph?{subGraphName:N.subGraph}:{});u(j.contextGraphError?`Published ${N.name} on-chain — ⚠ ${tn(j.contextGraphError)}`:`Published ${N.name} to Verifiable Memory`)}l(),r()}catch(j){const _=en(N.name,j);v(_?_.message:(j==null?void 0:j.message)??"Action failed")}finally{g(null)}},[e,t,l,r]),w=f.useCallback(async()=>{g("__all__"),u(null),v(null);let N=null;try{const j=await Yt(e,t);if(j.length===0){u(t==="wm"?"No user Knowledge Assets are ready to share.":"No user Knowledge Assets are ready to publish.");return}if(t==="wm"){let _=0;for(const E of j)N=E.name,(await Xt(e,E.name,E.subGraph?{subGraphName:E.subGraph}:{})).promotedCount===0&&(_+=1);const z=j.length-_;if(z>0){const E=_>0?` (${_} already shared or still committing)`:"";u(`Shared ${z} complete Knowledge Asset${z!==1?"s":""}${E}`)}else u("No Knowledge Assets were newly shared — all were already in Shared Memory or still committing.")}else{const _=await yr(e,j),z=xr(_),E=z?` — ⚠ ${z}`:"";if(_.published>0){const T=_.failures.length?` (${_.failures.length} could not be published)`:"",C=_.partial>0?` — ⚠ ${_.partial}: ${tn(_.partialError)}`:"";u(`Published ${_.published} knowledge asset${_.published!==1?"s":""} to Verifiable Memory${T}${C}${E}`)}else if(z&&_.failures.length===0)u(`⚠ ${z}`);else throw new Error(`${_.failures[0]?`${_.failures[0].name}: ${_.failures[0].error}`:"Publish failed"}${E}`)}l(),r()}catch(j){const _=en(N??"selected assertion",j);v(_?_.message:(j==null?void 0:j.message)??"Action failed")}finally{g(null)}},[e,t,l,r]),m={flex:1,overflow:"auto"};if(o)return s.jsx("div",{className:"v10-layer-empty-shell",style:m,"data-cg-scroll-key":i,children:s.jsx(xe,{compact:!0,tone:At(t),icon:Oe[t].icon,title:"Loading assertions..."})});if(!(a!=null&&a.length))return s.jsx("div",{className:"v10-layer-empty-shell",style:m,"data-cg-scroll-key":i,children:s.jsx(xe,{tone:At(t),icon:Oe[t].icon,title:t==="swm"?"No Shared Working Memory assertions listed yet.":"No Working Memory assertions yet.",description:t==="swm"?"Promoted assertion contents are available as Shared Working Memory entities. The assertion list will populate once promoted assertions are exposed by the node.":"Create or import data to stage assertions in Working Memory."})});const b=t==="wm"?"Share Complete KA → Shared":"Publish to VM",x=t==="wm"?"Share Complete KAs → Shared":"Publish all to Verifiable Memory",k=a.filter(N=>N.subGraph!=="meta"||!N.name.startsWith("query-catalog-")).length;return s.jsxs("div",{style:m,"data-cg-scroll-key":i,children:[s.jsxs("div",{style:{padding:"8px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid var(--border-subtle)"},children:[s.jsxs("span",{style:{fontSize:11,color:"var(--text-tertiary)"},children:[a.length," assertion",a.length!==1?"s":""]}),k>0&&s.jsx("button",{className:`v10-layer-expand-footer-btn ${t==="wm"?"promote":"publish"}`,disabled:d!==null,onClick:w,style:{opacity:d==="__all__"?.5:1},children:d==="__all__"?"...":x})]}),h&&s.jsxs("div",{"data-testid":t==="wm"?"assertion-promote-result":"assertion-publish-result",style:{padding:"6px 16px",fontSize:11,color:"var(--text-success)"},children:["✓ ",h]}),p&&s.jsxs("div",{"data-testid":t==="wm"?"assertion-promote-result":"assertion-publish-result",style:{padding:"6px 16px",fontSize:11,color:"var(--text-danger)"},children:["✕ ",p]}),a.map(N=>s.jsxs("div",{className:"v10-item-row","data-testid":"assertion-list-row",children:[s.jsx("span",{className:"v10-item-icon",children:"▤"}),s.jsxs("div",{className:"v10-item-info",children:[s.jsx("div",{className:"v10-item-name",style:{fontFamily:"var(--font-mono)",fontSize:11},children:N.name}),(c==null?void 0:c[N.name])&&s.jsx("div",{className:"v10-item-ual",style:{fontFamily:"var(--font-mono)",fontSize:10,color:"var(--text-tertiary)",opacity:.7,wordBreak:"break-all",marginTop:1},title:c[N.name],children:c[N.name]}),s.jsxs("div",{className:"v10-item-meta-row",children:[N.tripleCount!=null&&s.jsxs("span",{className:"v10-item-count",children:[N.tripleCount," triples"]}),N.subGraph&&s.jsxs("span",{className:"v10-item-count v10-item-subgraph",title:`In sub-graph: ${N.subGraph}`,children:["› ",wa(N.subGraph,18)]})]})]}),s.jsx("button",{"data-testid":"assertion-row-action",className:`v10-layer-expand-footer-btn ${t==="wm"?"promote":"publish"}`,disabled:d!==null,onClick:j=>{j.stopPropagation(),y(N)},style:{opacity:d===N.graphUri?.5:1,flexShrink:0},children:d===N.graphUri?"...":b})]},N.graphUri))]})}function Co({layer:e,memory:t,onNodeClick:n,onSelectEntity:r,contextGraphId:i,activeTab:a,onTabChange:o,swmAttribution:l,showQueryCatalog:c=!1,onShowQueryCatalogChange:d}){const g=Oe[e],h=f.useMemo(()=>t.entityList.filter(p=>p.trustLevel===g.trustLevel),[t.entityList,g.trustLevel]),u=Wi(t,e);return s.jsxs("div",{className:"v10-layer-detail",children:[s.jsxs("div",{className:"v10-layer-detail-header",children:[s.jsx("span",{className:"v10-layer-detail-icon",style:{color:g.color},children:g.icon}),s.jsxs("div",{children:[s.jsx("div",{className:"v10-layer-detail-title",children:g.title}),s.jsx("div",{className:"v10-layer-detail-desc",children:g.desc})]}),s.jsx("div",{className:"v10-layer-detail-actions"})]}),s.jsx("div",{className:"v10-layer-detail-body",children:s.jsx(ko,{layer:e,entities:h,tripleCount:u.length,layerTriples:u,contextGraphId:i,memory:t,activeTab:a,onTabChange:o,onSelectEntity:r,onNodeClick:n,swmAttribution:l,showQueryCatalog:c,onShowQueryCatalogChange:d})})]})}function Tr({entities:e,contextGraphId:t,scrollKey:n}){const r=Vn(o=>o.openTab),i=f.useMemo(()=>e.filter(o=>o.properties.has(jn)),[e]),a=o=>{var u,p,v;const l=(u=o.connections.find(y=>y.predicate===ds))==null?void 0:u.targetUri,c=(p=o.connections.find(y=>y.predicate===ps))==null?void 0:p.targetUri,d=((v=o.properties.get(jn))==null?void 0:v[0])??"",{ref:g,contentType:h}=Qi(l,c,d);r({id:Ki(t??"",g??o.uri,h),label:o.label,closable:!0,icon:"📄"})};return i.length===0?s.jsx("div",{className:"v10-docs-placeholder v10-layer-empty-shell",style:{flex:1},"data-cg-scroll-key":n,children:s.jsx(xe,{compact:!0,title:"No documents in this layer yet.",description:"Import a file to add document-backed entities."})}):s.jsx("div",{className:"v10-layer-detail-content","data-cg-scroll-key":n,children:s.jsx("div",{className:"v10-items-list",children:i.map(o=>{var h,u,p,v;const l=((h=o.properties.get(jn))==null?void 0:h[0])??"",c=(u=o.connections.find(y=>y.predicate===ds||y.predicate===ps))==null?void 0:u.targetUri,d=c?e.find(y=>y.uri===c):void 0,g=((p=d==null?void 0:d.properties.get(hs))==null?void 0:p[0])??((v=o.properties.get(hs))==null?void 0:v[0]);return s.jsxs("div",{className:"v10-item-row",onClick:()=>a(o),children:[s.jsx("span",{className:"v10-item-icon",children:"📄"}),s.jsxs("div",{className:"v10-item-info",children:[s.jsx("div",{className:"v10-item-name",children:o.label}),s.jsxs("div",{className:"v10-item-meta-row",children:[l&&s.jsx("span",{className:"v10-item-type",children:l}),g&&s.jsxs("span",{className:"v10-item-count",children:["· ",Math.round(parseInt(g)/1024),"KB"]})]})]}),s.jsx("button",{className:"v10-item-promote-btn",onClick:y=>{y.stopPropagation(),a(o)},children:"Open →"})]},o.uri)})})})}function Rr(e){return`SELECT ?g ?s ?p ?o WHERE {
37
37
  GRAPH ?g { ?s ?p ?o }
38
38
  ${Pn(e)}
39
39
  }
@@ -43,7 +43,7 @@ LIMIT 1000`}const rn="User-created SPARQL saved in this node profile for this Co
43
43
  STRSTARTS(STR(?g), ${xs(n)})
44
44
  ) &&
45
45
  !CONTAINS(STR(?g), "/_private")
46
- )`}function Co(e){const t="whole-context-graph",n="Context graph",i=Xe,a=o=>({subGraph:i,catalogSlug:t,catalogName:n,catalogDescription:"Ready-made SPARQL included with the Node UI for common Context Graph checks.",catalogRank:-100,resultColumn:"",parameters:[],...o});return{slug:t,subGraph:i,name:n,description:"Ready-made SPARQL included with the Node UI for common Context Graph checks.",rank:-100,queries:[a({slug:"all-triples",name:"All triples",description:"Show triples across available non-private graphs in this context graph.",sparql:Rr(e),resultColumn:"o",rank:1}),a({slug:"graphs",name:"Graphs",description:"List available non-private named graphs and triple counts.",sparql:`SELECT ?g (COUNT(*) AS ?triples) WHERE {
46
+ )`}function $o(e){const t="whole-context-graph",n="Context graph",i=Xe,a=o=>({subGraph:i,catalogSlug:t,catalogName:n,catalogDescription:"Ready-made SPARQL included with the Node UI for common Context Graph checks.",catalogRank:-100,resultColumn:"",parameters:[],...o});return{slug:t,subGraph:i,name:n,description:"Ready-made SPARQL included with the Node UI for common Context Graph checks.",rank:-100,queries:[a({slug:"all-triples",name:"All triples",description:"Show triples across available non-private graphs in this context graph.",sparql:Rr(e),resultColumn:"o",rank:1}),a({slug:"graphs",name:"Graphs",description:"List available non-private named graphs and triple counts.",sparql:`SELECT ?g (COUNT(*) AS ?triples) WHERE {
47
47
  GRAPH ?g { ?s ?p ?o }
48
48
  ${Pn(e)}
49
49
  }
@@ -55,10 +55,10 @@ LIMIT 100`,resultColumn:"g",rank:2}),a({slug:"types",name:"Types",description:"C
55
55
  }
56
56
  GROUP BY ?type
57
57
  ORDER BY DESC(?entities)
58
- LIMIT 100`,resultColumn:"type",rank:3})]}}function $o(e,t,n,r,i=[],a,o=Xe){const l=Date.now(),c=o===Xe?nn:`${nn}-${ma(o)}`,d=fa({contextGraphId:e,name:t,description:n||void 0,sparql:r,subGraph:o,catalogSlug:c,catalogName:sn,catalogDescription:rn,rank:l,catalogRank:50,parameters:i,view:a});return{query:{slug:d.savedQuery.slug,subGraph:o,catalogSlug:c,catalogName:sn,catalogDescription:rn,catalogRank:50,name:t,description:n||void 0,sparql:r,resultColumn:"",rank:l,parameters:[...i],view:a},quads:d.quads}}function Eo(e,t){const n=`${t.subGraph}|${t.catalogSlug}`,r=e.map(a=>({...a,queries:[...a.queries]})),i=r.find(a=>`${a.subGraph}|${a.slug}`===n);return i?(i.queries=[...i.queries,t].sort((a,o)=>a.rank-o.rank||a.name.localeCompare(o.name)),r):[...r,{slug:t.catalogSlug,subGraph:t.subGraph,name:sn,description:rn,rank:50,queries:[t]}]}function js(e){const t=new Map;for(const n of e){const r=`${n.subGraph}|${n.slug}`,i=t.get(r);if(!i){t.set(r,{...n,queries:[...n.queries]});continue}const a=new Map(i.queries.map(o=>[`${o.subGraph}|${o.catalogSlug}|${o.slug}`,o]));for(const o of n.queries){const l=`${o.subGraph}|${o.catalogSlug}|${o.slug}`;a.has(l)||a.set(l,o)}i.queries=Array.from(a.values()).sort((o,l)=>o.rank-l.rank||o.name.localeCompare(l.name))}return Array.from(t.values()).sort((n,r)=>n.subGraph.localeCompare(r.subGraph)||n.rank-r.rank||n.name.localeCompare(r.name))}function _o(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&"value"in e?String(e.value):String(e)}function Ao(e){return e?e.length<=140?e:`${e.slice(0,110)}...${e.slice(-24)}`:"—"}function hn(e){return e.subGraph===Xe&&e.slug==="whole-context-graph"}function Ro(e){return e.subGraph===Xe?"context":"subgraph"}function To(e,t,n){return hn(e)?"Built-in presets":e.subGraph===Xe&&e.slug===nn?sn:t==="context"?e.name:`${n??e.subGraph}: ${e.name}`}function Oo(e){return hn(e)?"UI-provided SPARQL for common Context Graph checks.":e.subGraph===Xe&&e.slug===nn?rn:e.description??""}function Io(e,t){return hn(e)?"Preset":t==="context"?"Saved":"Subgraph"}function Po(e){return s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Review the query or node response details, then try again."}),e&&s.jsx("span",{className:"v10-cg-query-error-detail",children:e})]})}function zo({contextGraphId:e}){var Te;const t=et(),n=f.useMemo(()=>Rr(e),[e]),[r,i]=f.useState({kind:"ad-hoc",draft:n}),[a,o]=f.useState({sparql:n}),[l,c]=f.useState([]),[d,g]=f.useState(!1),[h,u]=f.useState(""),[p,v]=f.useState(""),[y,w]=f.useState(!1),[m,b]=f.useState(null),[x,k]=f.useState(null),[S,j]=f.useState(null),_=f.useMemo(()=>Co(e),[e]),z=f.useMemo(()=>js([_,...l,...(t==null?void 0:t.queryCatalogs)??[]]),[_,l,t==null?void 0:t.queryCatalogs]),E=f.useMemo(()=>t!=null&&t.loading||t!=null&&t.error?js([_,...l]):z,[_,l,t==null?void 0:t.error,t==null?void 0:t.loading,z]),T=f.useMemo(()=>r.kind==="catalog"?r.query:void 0,[r]),$=r.kind==="catalog"?r.key:null,O=r.draft,Z=r.kind==="catalog"?r.values:{};f.useEffect(()=>{i({kind:"ad-hoc",draft:n}),o({sparql:n}),c([]),g(!1),u(""),v(""),b(null),k(null),j(null)},[n]);const{data:C,loading:R,error:G,refresh:P}=ft(()=>wr(a.sparql,{contextGraphId:e,view:a.view,subGraphName:a.subGraphName}),[a.sparql,a.subGraphName,a.view,e],0),L=f.useMemo(()=>{if(r.kind!=="catalog")return!0;if(a.sourceKey!==r.key)return!1;try{const q=Nt(r.query,r.values);return q.sparql===a.sparql&&q.view===a.view&&q.subGraphName===a.subGraphName}catch{return!1}},[a,r]),A=L?C==null?void 0:C.result:void 0,M=A==null?void 0:A.type,F=f.useMemo(()=>M==="quads"?A.quads:M==="bindings"?A.bindings:[],[A,M]),B=M==="boolean"?A.value:void 0,J=f.useMemo(()=>z.some(q=>!hn(q)&&q.queries.length>0),[z]),X=f.useMemo(()=>{const q=[];for(const ne of F)for(const se of Object.keys(ne))q.includes(se)||q.push(se);return q},[F]),H=f.useCallback(()=>{const q=r.draft.trim();if(!q)return;let ne;if(r.kind==="catalog"&&q===r.query.sparql.trim())try{ne={...Nt(r.query,r.values),sourceKey:r.key},j(null)}catch(se){j((se==null?void 0:se.message)??String(se));return}else ne={sparql:q},r.kind==="catalog"&&i({kind:"ad-hoc",draft:q}),j(null);if(k(null),b(null),ne.sparql===a.sparql&&ne.view===a.view&&ne.subGraphName===a.subGraphName){o(ne),P();return}o(ne)},[a,P,r]),V=f.useCallback(()=>{if(i({kind:"ad-hoc",draft:n}),k(null),b(null),j(null),a.sparql===n&&a.view===void 0&&a.subGraphName===void 0){P();return}o({sparql:n})},[a,n,P]),re=f.useCallback((q,ne)=>{const se=ne.sparql.trim();if(!se)return;k(null),b(null),j(null);const $e=ne.parameters??[],fe=Object.fromEntries($e.filter(Se=>Se.defaultValue!==void 0).map(Se=>[Se.name,String(Se.defaultValue)]));if(i({kind:"catalog",key:q,query:ne,values:fe,draft:se}),$e.length>0)return;const ge={...Nt(ne,fe),sourceKey:q};if(a.sparql===ge.sparql&&a.view===ge.view&&a.subGraphName===ge.subGraphName){o(ge),P();return}o(ge)},[a,P]),ye=f.useCallback(()=>{const q=O.trim().split(`
59
- `).find(ne=>ne.trim());u(q?q.replace(/\s+/g," ").slice(0,60):""),v(""),b(null),k(null),g(!0)},[O]),Ne=f.useCallback(async q=>{q.preventDefault();const ne=h.trim(),se=p.trim(),$e=O.trim();if(!ne){b("Name is required.");return}if(!$e){b("Query is empty.");return}w(!0),b(null),k(null);try{const fe=T&&T.sparql.trim()===$e?T:void 0,{query:ge,quads:Se}=$o(e,ne,se,$e,(fe==null?void 0:fe.parameters)??[],fe==null?void 0:fe.view,(fe==null?void 0:fe.subGraph)??Xe);await Ji(e,Se),c(ue=>Eo(ue,ge));const be=`${ge.subGraph}|${ge.catalogSlug}|${ge.slug}`,Ze=r.kind==="catalog"?r.values:{};i({kind:"catalog",key:be,query:ge,values:Ze,draft:ge.sparql});try{const ue=Nt(ge,Ze);o(Me=>Me.sparql===ue.sparql&&Me.view===ue.view&&Me.subGraphName===ue.subGraphName?{...Me,sourceKey:be}:Me)}catch{}u(""),v(""),g(!1),k("Saved to catalogue.")}catch(fe){b((fe==null?void 0:fe.message)??"Failed to save query.")}finally{w(!1)}},[e,O,p,h,T,r]);return s.jsxs("div",{className:"v10-memory-layer-view v10-cg-query-view",children:[s.jsxs("div",{className:"v10-mlv-header",children:[s.jsx("span",{className:"v10-mlv-icon",children:"⟐"}),s.jsxs("div",{children:[s.jsx("h2",{className:"v10-mlv-title",children:"Query Catalogue"}),s.jsx("p",{className:"v10-mlv-desc",children:"Reusable SPARQL for this Context Graph. Use UI presets or save queries for people and local agents to reuse."})]})]}),s.jsxs("section",{className:"v10-cg-query-zone v10-cg-query-zone-catalog","aria-labelledby":"query-catalogue-saved-title",children:[s.jsx("div",{className:"v10-cg-query-zone-header",children:s.jsxs("div",{children:[s.jsx("span",{className:"v10-cg-query-eyebrow",children:"Query Library"}),s.jsx("h3",{id:"query-catalogue-saved-title",children:"Choose a query"}),s.jsx("p",{children:"Load a preset or saved query into the editor below."})]})}),(t==null?void 0:t.loading)&&s.jsx(xe,{compact:!0,inline:!0,tone:"query",icon:"?",title:"Loading saved queries...",description:"Built-in presets are available while saved queries load from this node profile."}),(t==null?void 0:t.error)&&s.jsx(xe,{compact:!0,inline:!0,tone:"danger",icon:"!",title:"Saved query catalogue unavailable",description:t.error}),E.length>0&&s.jsx("div",{className:"v10-cg-query-catalog-groups",children:E.map(q=>{const ne=Ro(q),se=ne==="context"||t==null?void 0:t.forSubGraph(q.subGraph),$e=(se==null?void 0:se.color)??"#38bdf8",fe=To(q,ne,se==null?void 0:se.displayName),ge=Oo(q),Se=Io(q,ne);return s.jsxs("div",{className:"v10-cg-query-catalog-group",style:{"--sg-color":$e},children:[s.jsx("div",{className:"v10-cg-query-catalog-group-header",children:s.jsxs("div",{children:[s.jsxs("div",{className:"v10-cg-query-catalog-title-row",children:[s.jsx("span",{className:"v10-cg-query-catalog-kind",children:Se}),s.jsx("h4",{children:fe})]}),ge&&s.jsx("p",{children:ge})]})}),s.jsx("div",{className:"v10-cg-query-list",children:q.queries.map(be=>{const Ze=`${be.subGraph}|${be.catalogSlug}|${be.slug}`,ue=$===Ze,Me=be.description?`${be.name}. ${be.description}`:be.name;return s.jsxs("button",{type:"button",className:`v10-cg-query-chip${ue?" active":""}`,title:Me,"aria-label":`Load query: ${Me}`,onClick:()=>re(Ze,be),children:[s.jsx("span",{className:"v10-cg-query-chip-title",children:be.name}),be.description&&s.jsx("span",{className:"v10-cg-query-chip-desc",children:be.description})]},Ze)})})]},`${q.subGraph}|${q.slug}`)})}),!(t!=null&&t.loading)&&!(t!=null&&t.error)&&z.length>0&&!J&&s.jsx(xe,{compact:!0,inline:!0,tone:"query",icon:"?",title:"No saved queries yet.",description:"Use Save after editing SPARQL to keep a reusable query for this Context Graph."})]}),s.jsxs("section",{className:"v10-cg-query-zone v10-cg-query-zone-editor","aria-labelledby":"query-catalogue-editor-title",children:[s.jsx("div",{className:"v10-cg-query-zone-header",children:s.jsxs("div",{children:[s.jsx("span",{className:"v10-cg-query-eyebrow",children:"Ad-hoc SPARQL"}),s.jsx("h3",{id:"query-catalogue-editor-title",children:"Editor and results"}),s.jsx("p",{children:"Run a one-off query against this Context Graph, or save it when it should become reusable."})]})}),s.jsxs("div",{className:"v10-cg-query-editor",children:[T&&(((Te=T.parameters)==null?void 0:Te.length)??0)>0&&s.jsx("div",{className:"v10-cg-query-parameters","aria-label":"Query parameters",children:(T.parameters??[]).map(q=>s.jsxs("label",{className:"v10-cg-query-parameter",children:[s.jsx("span",{children:q.label??q.name}),q.type==="boolean"?s.jsxs("select",{className:"v10-form-input","aria-label":q.label??q.name,value:Z[q.name]??"",onChange:ne=>i(se=>se.kind==="catalog"?{...se,values:{...se.values,[q.name]:ne.target.value}}:se),children:[s.jsx("option",{value:"",children:"Choose..."}),s.jsx("option",{value:"true",children:"True"}),s.jsx("option",{value:"false",children:"False"})]}):s.jsx("input",{className:"v10-form-input","aria-label":q.label??q.name,type:q.type==="integer"||q.type==="number"?"number":"text",step:q.type==="integer"?"1":q.type==="number"?"any":void 0,required:ha(q),value:Z[q.name]??"",placeholder:q.description,onChange:ne=>i(se=>se.kind==="catalog"?{...se,values:{...se.values,[q.name]:ne.target.value}}:se)}),q.description&&s.jsx("small",{children:q.description})]},q.name))}),S&&s.jsx("span",{className:"v10-cg-query-error-detail",children:S}),s.jsx("textarea",{className:"v10-cg-query-textarea","aria-label":"SPARQL editor",value:O,onChange:q=>{i({kind:"ad-hoc",draft:q.target.value}),j(null)},spellCheck:!1}),s.jsxs("div",{className:"v10-cg-query-actions",children:[s.jsx("button",{className:"v10-mlv-run-btn",type:"button",onClick:H,children:"Run"}),s.jsx("button",{className:"v10-mlv-save-btn",type:"button",onClick:ye,children:"Save"}),s.jsx("button",{className:"v10-mlv-clear-btn",type:"button",onClick:V,children:"Reset"})]})]}),d&&s.jsxs("form",{className:"v10-cg-query-save-panel",onSubmit:Ne,children:[s.jsxs("label",{className:"v10-cg-query-save-field",children:[s.jsx("span",{children:"Name"}),s.jsx("input",{type:"text",value:h,onChange:q=>u(q.target.value),placeholder:"Query name",maxLength:80})]}),s.jsxs("label",{className:"v10-cg-query-save-field",children:[s.jsx("span",{children:"Description"}),s.jsx("input",{type:"text",value:p,onChange:q=>v(q.target.value),placeholder:"Optional",maxLength:180})]}),s.jsxs("div",{className:"v10-cg-query-save-actions",children:[s.jsx("button",{type:"button",className:"v10-mlv-clear-btn",onClick:()=>g(!1),disabled:y,children:"Cancel"}),s.jsx("button",{type:"submit",className:"v10-mlv-run-btn",disabled:y,children:y?"Saving...":"Save query"})]})]}),x&&s.jsx("p",{className:"v10-mlv-status",style:{color:"var(--text-success)"},children:x}),m&&s.jsx("p",{className:"v10-mlv-status",style:{color:"var(--text-danger)"},children:m}),s.jsxs("div",{className:"v10-cg-query-results",children:[!L&&s.jsx(xe,{compact:!0,tone:"query",icon:"?",title:"Enter parameters, then run this query.",description:"Previous query results are hidden so they are not presented as results for the newly selected template."}),L&&R&&s.jsx(xe,{compact:!0,tone:"query",icon:"?",title:"Loading query results..."}),L&&G&&s.jsx(xe,{compact:!0,tone:"danger",icon:"!",title:"Query could not run.",description:Po(G)}),L&&!R&&!G&&B===void 0&&F.length===0&&s.jsx(xe,{compact:!0,tone:"query",icon:"?",title:"No results for this query.",description:"Adjust the query or run a saved query against this Context Graph."}),L&&!R&&!G&&B!==void 0&&s.jsxs("div",{className:"v10-mlv-table-wrap","aria-label":"ASK result",children:[s.jsx("div",{className:"v10-mlv-result-count",children:"ASK result"}),s.jsx("strong",{children:String(B)})]}),L&&!R&&!G&&B===void 0&&F.length>0&&s.jsxs("div",{className:"v10-mlv-table-wrap",children:[s.jsxs("div",{className:"v10-mlv-result-count",children:[F.length," ",M==="quads"?`quad${F.length===1?"":"s"}`:`result${F.length===1?"":"s"}`]}),s.jsxs("table",{className:"v10-mlv-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:X.map(q=>s.jsx("th",{children:q},q))})}),s.jsx("tbody",{children:F.map((q,ne)=>s.jsx("tr",{children:X.map(se=>{const $e=_o(q[se]);return s.jsx("td",{className:"v10-mlv-cell",title:$e,children:Ao($e)},se)})},ne))})]})]})]})]})]})}const Lo=({contextGraphId:e,entityUri:t,enabled:n})=>{const r=It(),i=wa(e,t,n),a=ka(e,t,n),{data:o}=ft(Yi,[],6e4),l=o==null?void 0:o.blockExplorerUrl,c=a.ual??i.ual,d=a.status==="verified";if(!n||i.loading||!i.ual&&!i.owner&&!i.publishedAt&&!d)return null;const g=i.publishedAt?Mo(i.publishedAt):null,h=i.publisherPeerId&&r?fs(i.publisherPeerId,r.agents):null,u=h?(r==null?void 0:r.get(h))??null:null,p=i.owner&&r?fs(i.owner,r.agents):null,v=p?(r==null?void 0:r.get(p))??null:null,y=w=>{var m;(m=navigator.clipboard)==null||m.writeText(w).catch(()=>{})};return s.jsxs("div",{className:"v10-vm-identity",children:[s.jsxs("div",{className:"v10-vm-identity-head",children:[s.jsx("span",{className:"v10-vm-identity-glyph",children:"◉"}),s.jsx("span",{className:"v10-vm-identity-title",children:"On-chain identity"}),s.jsx("span",{className:"v10-vm-identity-badge",children:"VERIFIED"})]}),c&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"UAL"}),s.jsx("span",{className:"v10-vm-identity-val mono",title:c,children:c}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(c),title:"Copy UAL",children:"⎘"})]}),d&&a.txHash&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"Tx"}),l?s.jsxs("a",{className:"v10-vm-identity-val mono",href:`${l}/tx/${a.txHash}`,target:"_blank",rel:"noopener noreferrer",title:a.txHash,children:[dt(a.txHash,10,8)," ↗"]}):s.jsx("span",{className:"v10-vm-identity-val mono",title:a.txHash,children:dt(a.txHash,10,8)}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(a.txHash),title:"Copy transaction hash",children:"⎘"}),a.blockNumber&&s.jsxs("span",{className:"v10-vm-identity-opid mono",children:["· block ",a.blockNumber]})]}),d&&a.kaId&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"KA id"}),s.jsx("span",{className:"v10-vm-identity-val mono",title:a.kaId,children:dt(a.kaId,8,8)}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(a.kaId),title:"Copy KA id",children:"⎘"})]}),(v||i.owner)&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"Owner"}),v?s.jsxs("span",{className:"v10-vm-identity-val",children:[s.jsx(gt,{agent:v,size:"sm"}),v.walletAddress&&s.jsx("span",{className:"v10-vm-identity-wallet mono",title:v.walletAddress,children:dt(v.walletAddress,6,4)})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"v10-vm-identity-val mono",title:i.owner??"",children:dt(i.owner,8,6)}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(i.owner),title:"Copy owner id",children:"⎘"})]})]}),g&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"Published"}),s.jsx("span",{className:"v10-vm-identity-val",title:i.publishedAt??"",children:g}),i.opId&&s.jsxs("span",{className:"v10-vm-identity-opid mono",title:`Anchor op: ${i.opId}`,children:["· anchor ",i.opId.slice(0,10)]})]}),(u||i.publisherPeerId)&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"By"}),u?s.jsx(gt,{agent:u,size:"sm"}):s.jsx("span",{className:"v10-vm-identity-val mono",title:i.publisherPeerId??"",children:dt(i.publisherPeerId,8,6)})]})]})};function Mo(e){const t=new Date(e.replace(/^"|"$/g,""));return Number.isFinite(t.getTime())?t.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):e}function I(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const g in o.prototype)g in l||Object.defineProperty(l,g,{value:o.prototype[g].bind(l)});l._zod.constr=o,l._zod.def=c}const i=(n==null?void 0:n.Parent)??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(l){var c;const d=n!=null&&n.Parent?new a:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const g of d._zod.deferred)g();return d}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:l=>{var c,d;return n!=null&&n.Parent&&l instanceof n.Parent?!0:(d=(c=l==null?void 0:l._zod)==null?void 0:c.traits)==null?void 0:d.has(e)}}),Object.defineProperty(o,"name",{value:e}),o}class Rt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Tr={};function st(e){return Tr}function Or(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Fo(e,t){return typeof t=="bigint"?t.toString():t}function Ir(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Yn(e){return e==null}function Hn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Uo(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return a%o/10**i}function he(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Xn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function wt(e){return JSON.stringify(e)}const Pr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Do=Ir(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ln(e){if(zn(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(zn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const Zo=new Set(["string","number","symbol"]);function mn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function it(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function Y(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qo(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Go={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Bo(e,t){const n={},r=e._zod.def;for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(n[i]=r.shape[i])}return it(e,{...e._zod.def,shape:n,checks:[]})}function Wo(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete n[i]}return it(e,{...e._zod.def,shape:n,checks:[]})}function Vo(e,t){if(!Ln(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Xn(this,"shape",r),r},checks:[]};return it(e,n)}function Qo(e,t){return it(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Xn(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Ko(e,t,n){const r=t._zod.def.shape,i={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(i[a]=e?new e({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)i[a]=e?new e({type:"optional",innerType:r[a]}):r[a];return it(t,{...t._zod.def,shape:i,checks:[]})}function Jo(e,t,n){const r=t._zod.def.shape,i={...r};if(n)for(const a in n){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(i[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)i[a]=new e({type:"nonoptional",innerType:r[a]});return it(t,{...t._zod.def,shape:i,checks:[]})}function Et(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function es(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ft(e){return typeof e=="string"?e:e==null?void 0:e.message}function rt(e,t,n){var i,a,o,l,c,d;const r={...e,path:e.path??[]};if(!e.message){const g=Ft((o=(a=(i=e.inst)==null?void 0:i._zod.def)==null?void 0:a.error)==null?void 0:o.call(a,e))??Ft((l=t==null?void 0:t.error)==null?void 0:l.call(t,e))??Ft((c=n.customError)==null?void 0:c.call(n,e))??Ft((d=n.localeError)==null?void 0:d.call(n,e))??"Invalid input";r.message=g}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function ts(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Tt(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const zr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Fo,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Lr=I("$ZodError",zr),Mr=I("$ZodError",zr,{Parent:Error});function Yo(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ho(e,t){const n=t||function(a){return a.message},r={_errors:[]},i=a=>{for(const o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(l=>i({issues:l}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){const d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],c++}}};return i(e),r}const Xo=e=>(t,n,r,i)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Rt;if(o.issues.length){const l=new((i==null?void 0:i.Err)??e)(o.issues.map(c=>rt(c,a,st())));throw Pr(l,i==null?void 0:i.callee),l}return o.value},el=e=>async(t,n,r,i)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const l=new((i==null?void 0:i.Err)??e)(o.issues.map(c=>rt(c,a,st())));throw Pr(l,i==null?void 0:i.callee),l}return o.value},Fr=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Rt;return a.issues.length?{success:!1,error:new(e??Lr)(a.issues.map(o=>rt(o,i,st())))}:{success:!0,data:a.value}},tl=Fr(Mr),Ur=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(o=>rt(o,i,st())))}:{success:!0,data:a.value}},nl=Ur(Mr),sl=/^[cC][^\s-]{8,}$/,rl=/^[0-9a-z]+$/,il=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,al=/^[0-9a-vA-V]{20}$/,ol=/^[A-Za-z0-9]{27}$/,ll=/^[a-zA-Z0-9_-]{21}$/,cl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ul=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ws=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,dl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,pl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hl(){return new RegExp(pl,"u")}const ml=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,fl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,gl=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,vl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Dr=/^[A-Za-z0-9_-]*$/,yl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,xl=/^\+(?:[0-9]){6,14}[0-9]$/,Zr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",jl=new RegExp(`^${Zr}$`);function qr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function wl(e){return new RegExp(`^${qr(e)}$`)}function kl(e){const t=qr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Zr}T(?:${r})$`)}const Nl=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Sl=/^\d+$/,Cl=/^-?\d+(?:\.\d+)?/i,$l=/^[^A-Z]*$/,El=/^[^a-z]*$/,Re=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Gr={number:"number",bigint:"bigint",object:"date"},Br=I("$ZodCheckLessThan",(e,t)=>{Re.init(e,t);const n=Gr[typeof t.value];e._zod.onattach.push(r=>{const i=r._zod.bag,a=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wr=I("$ZodCheckGreaterThan",(e,t)=>{Re.init(e,t);const n=Gr[typeof t.value];e._zod.onattach.push(r=>{const i=r._zod.bag,a=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_l=I("$ZodCheckMultipleOf",(e,t)=>{Re.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Uo(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Al=I("$ZodCheckNumberFormat",(e,t)=>{var o;Re.init(e,t),t.format=t.format||"float64";const n=(o=t.format)==null?void 0:o.includes("int"),r=n?"int":"number",[i,a]=Go[t.format];e._zod.onattach.push(l=>{const c=l._zod.bag;c.format=t.format,c.minimum=i,c.maximum=a,n&&(c.pattern=Sl)}),e._zod.check=l=>{const c=l.value;if(n){if(!Number.isInteger(c)){l.issues.push({expected:r,format:t.format,code:"invalid_type",input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?l.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):l.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}c<i&&l.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>a&&l.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inst:e})}}),Rl=I("$ZodCheckMaxLength",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Yn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const i=r.value;if(i.length<=t.maximum)return;const o=ts(i);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Tl=I("$ZodCheckMinLength",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Yn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const o=ts(i);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ol=I("$ZodCheckLengthEquals",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Yn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,a=i.length;if(a===t.length)return;const o=ts(i),l=a>t.length;r.issues.push({origin:o,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),fn=I("$ZodCheckStringFormat",(e,t)=>{var n,r;Re.init(e,t),e._zod.onattach.push(i=>{const a=i._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Il=I("$ZodCheckRegex",(e,t)=>{fn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Pl=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=$l),fn.init(e,t)}),zl=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=El),fn.init(e,t)}),Ll=I("$ZodCheckIncludes",(e,t)=>{Re.init(e,t);const n=mn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Ml=I("$ZodCheckStartsWith",(e,t)=>{Re.init(e,t);const n=new RegExp(`^${mn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Fl=I("$ZodCheckEndsWith",(e,t)=>{Re.init(e,t);const n=new RegExp(`.*${mn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Ul=I("$ZodCheckOverwrite",(e,t)=>{Re.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Dl{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
58
+ LIMIT 100`,resultColumn:"type",rank:3})]}}function Eo(e,t,n,r,i=[],a,o=Xe){const l=Date.now(),c=o===Xe?nn:`${nn}-${fa(o)}`,d=ga({contextGraphId:e,name:t,description:n||void 0,sparql:r,subGraph:o,catalogSlug:c,catalogName:sn,catalogDescription:rn,rank:l,catalogRank:50,parameters:i,view:a});return{query:{slug:d.savedQuery.slug,subGraph:o,catalogSlug:c,catalogName:sn,catalogDescription:rn,catalogRank:50,name:t,description:n||void 0,sparql:r,resultColumn:"",rank:l,parameters:[...i],view:a},quads:d.quads}}function _o(e,t){const n=`${t.subGraph}|${t.catalogSlug}`,r=e.map(a=>({...a,queries:[...a.queries]})),i=r.find(a=>`${a.subGraph}|${a.slug}`===n);return i?(i.queries=[...i.queries,t].sort((a,o)=>a.rank-o.rank||a.name.localeCompare(o.name)),r):[...r,{slug:t.catalogSlug,subGraph:t.subGraph,name:sn,description:rn,rank:50,queries:[t]}]}function js(e){const t=new Map;for(const n of e){const r=`${n.subGraph}|${n.slug}`,i=t.get(r);if(!i){t.set(r,{...n,queries:[...n.queries]});continue}const a=new Map(i.queries.map(o=>[`${o.subGraph}|${o.catalogSlug}|${o.slug}`,o]));for(const o of n.queries){const l=`${o.subGraph}|${o.catalogSlug}|${o.slug}`;a.has(l)||a.set(l,o)}i.queries=Array.from(a.values()).sort((o,l)=>o.rank-l.rank||o.name.localeCompare(l.name))}return Array.from(t.values()).sort((n,r)=>n.subGraph.localeCompare(r.subGraph)||n.rank-r.rank||n.name.localeCompare(r.name))}function Ao(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&"value"in e?String(e.value):String(e)}function To(e){return e?e.length<=140?e:`${e.slice(0,110)}...${e.slice(-24)}`:"—"}function hn(e){return e.subGraph===Xe&&e.slug==="whole-context-graph"}function Ro(e){return e.subGraph===Xe?"context":"subgraph"}function Oo(e,t,n){return hn(e)?"Built-in presets":e.subGraph===Xe&&e.slug===nn?sn:t==="context"?e.name:`${n??e.subGraph}: ${e.name}`}function Io(e){return hn(e)?"UI-provided SPARQL for common Context Graph checks.":e.subGraph===Xe&&e.slug===nn?rn:e.description??""}function Po(e,t){return hn(e)?"Preset":t==="context"?"Saved":"Subgraph"}function zo(e){return s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Review the query or node response details, then try again."}),e&&s.jsx("span",{className:"v10-cg-query-error-detail",children:e})]})}function Lo({contextGraphId:e}){var Re;const t=et(),n=f.useMemo(()=>Rr(e),[e]),[r,i]=f.useState({kind:"ad-hoc",draft:n}),[a,o]=f.useState({sparql:n}),[l,c]=f.useState([]),[d,g]=f.useState(!1),[h,u]=f.useState(""),[p,v]=f.useState(""),[y,w]=f.useState(!1),[m,b]=f.useState(null),[x,k]=f.useState(null),[N,j]=f.useState(null),_=f.useMemo(()=>$o(e),[e]),z=f.useMemo(()=>js([_,...l,...(t==null?void 0:t.queryCatalogs)??[]]),[_,l,t==null?void 0:t.queryCatalogs]),E=f.useMemo(()=>t!=null&&t.loading||t!=null&&t.error?js([_,...l]):z,[_,l,t==null?void 0:t.error,t==null?void 0:t.loading,z]),T=f.useMemo(()=>r.kind==="catalog"?r.query:void 0,[r]),C=r.kind==="catalog"?r.key:null,O=r.draft,Z=r.kind==="catalog"?r.values:{};f.useEffect(()=>{i({kind:"ad-hoc",draft:n}),o({sparql:n}),c([]),g(!1),u(""),v(""),b(null),k(null),j(null)},[n]);const{data:$,loading:R,error:G,refresh:P}=ft(()=>kr(a.sparql,{contextGraphId:e,view:a.view,subGraphName:a.subGraphName}),[a.sparql,a.subGraphName,a.view,e],0),L=f.useMemo(()=>{if(r.kind!=="catalog")return!0;if(a.sourceKey!==r.key)return!1;try{const q=Nt(r.query,r.values);return q.sparql===a.sparql&&q.view===a.view&&q.subGraphName===a.subGraphName}catch{return!1}},[a,r]),A=L?$==null?void 0:$.result:void 0,M=A==null?void 0:A.type,F=f.useMemo(()=>M==="quads"?A.quads:M==="bindings"?A.bindings:[],[A,M]),B=M==="boolean"?A.value:void 0,J=f.useMemo(()=>z.some(q=>!hn(q)&&q.queries.length>0),[z]),X=f.useMemo(()=>{const q=[];for(const ne of F)for(const se of Object.keys(ne))q.includes(se)||q.push(se);return q},[F]),Y=f.useCallback(()=>{const q=r.draft.trim();if(!q)return;let ne;if(r.kind==="catalog"&&q===r.query.sparql.trim())try{ne={...Nt(r.query,r.values),sourceKey:r.key},j(null)}catch(se){j((se==null?void 0:se.message)??String(se));return}else ne={sparql:q},r.kind==="catalog"&&i({kind:"ad-hoc",draft:q}),j(null);if(k(null),b(null),ne.sparql===a.sparql&&ne.view===a.view&&ne.subGraphName===a.subGraphName){o(ne),P();return}o(ne)},[a,P,r]),V=f.useCallback(()=>{if(i({kind:"ad-hoc",draft:n}),k(null),b(null),j(null),a.sparql===n&&a.view===void 0&&a.subGraphName===void 0){P();return}o({sparql:n})},[a,n,P]),re=f.useCallback((q,ne)=>{const se=ne.sparql.trim();if(!se)return;k(null),b(null),j(null);const $e=ne.parameters??[],fe=Object.fromEntries($e.filter(Se=>Se.defaultValue!==void 0).map(Se=>[Se.name,String(Se.defaultValue)]));if(i({kind:"catalog",key:q,query:ne,values:fe,draft:se}),$e.length>0)return;const ge={...Nt(ne,fe),sourceKey:q};if(a.sparql===ge.sparql&&a.view===ge.view&&a.subGraphName===ge.subGraphName){o(ge),P();return}o(ge)},[a,P]),ye=f.useCallback(()=>{const q=O.trim().split(`
59
+ `).find(ne=>ne.trim());u(q?q.replace(/\s+/g," ").slice(0,60):""),v(""),b(null),k(null),g(!0)},[O]),Ne=f.useCallback(async q=>{q.preventDefault();const ne=h.trim(),se=p.trim(),$e=O.trim();if(!ne){b("Name is required.");return}if(!$e){b("Query is empty.");return}w(!0),b(null),k(null);try{const fe=T&&T.sparql.trim()===$e?T:void 0,{query:ge,quads:Se}=Eo(e,ne,se,$e,(fe==null?void 0:fe.parameters)??[],fe==null?void 0:fe.view,(fe==null?void 0:fe.subGraph)??Xe);await Hi(e,Se),c(ue=>_o(ue,ge));const be=`${ge.subGraph}|${ge.catalogSlug}|${ge.slug}`,Ze=r.kind==="catalog"?r.values:{};i({kind:"catalog",key:be,query:ge,values:Ze,draft:ge.sparql});try{const ue=Nt(ge,Ze);o(Me=>Me.sparql===ue.sparql&&Me.view===ue.view&&Me.subGraphName===ue.subGraphName?{...Me,sourceKey:be}:Me)}catch{}u(""),v(""),g(!1),k("Saved to catalogue.")}catch(fe){b((fe==null?void 0:fe.message)??"Failed to save query.")}finally{w(!1)}},[e,O,p,h,T,r]);return s.jsxs("div",{className:"v10-memory-layer-view v10-cg-query-view",children:[s.jsxs("div",{className:"v10-mlv-header",children:[s.jsx("span",{className:"v10-mlv-icon",children:"⟐"}),s.jsxs("div",{children:[s.jsx("h2",{className:"v10-mlv-title",children:"Query Catalogue"}),s.jsx("p",{className:"v10-mlv-desc",children:"Reusable SPARQL for this Context Graph. Use UI presets or save queries for people and local agents to reuse."})]})]}),s.jsxs("section",{className:"v10-cg-query-zone v10-cg-query-zone-catalog","aria-labelledby":"query-catalogue-saved-title",children:[s.jsx("div",{className:"v10-cg-query-zone-header",children:s.jsxs("div",{children:[s.jsx("span",{className:"v10-cg-query-eyebrow",children:"Query Library"}),s.jsx("h3",{id:"query-catalogue-saved-title",children:"Choose a query"}),s.jsx("p",{children:"Load a preset or saved query into the editor below."})]})}),(t==null?void 0:t.loading)&&s.jsx(xe,{compact:!0,inline:!0,tone:"query",icon:"?",title:"Loading saved queries...",description:"Built-in presets are available while saved queries load from this node profile."}),(t==null?void 0:t.error)&&s.jsx(xe,{compact:!0,inline:!0,tone:"danger",icon:"!",title:"Saved query catalogue unavailable",description:t.error}),E.length>0&&s.jsx("div",{className:"v10-cg-query-catalog-groups",children:E.map(q=>{const ne=Ro(q),se=ne==="context"||t==null?void 0:t.forSubGraph(q.subGraph),$e=(se==null?void 0:se.color)??"#38bdf8",fe=Oo(q,ne,se==null?void 0:se.displayName),ge=Io(q),Se=Po(q,ne);return s.jsxs("div",{className:"v10-cg-query-catalog-group",style:{"--sg-color":$e},children:[s.jsx("div",{className:"v10-cg-query-catalog-group-header",children:s.jsxs("div",{children:[s.jsxs("div",{className:"v10-cg-query-catalog-title-row",children:[s.jsx("span",{className:"v10-cg-query-catalog-kind",children:Se}),s.jsx("h4",{children:fe})]}),ge&&s.jsx("p",{children:ge})]})}),s.jsx("div",{className:"v10-cg-query-list",children:q.queries.map(be=>{const Ze=`${be.subGraph}|${be.catalogSlug}|${be.slug}`,ue=C===Ze,Me=be.description?`${be.name}. ${be.description}`:be.name;return s.jsxs("button",{type:"button",className:`v10-cg-query-chip${ue?" active":""}`,title:Me,"aria-label":`Load query: ${Me}`,onClick:()=>re(Ze,be),children:[s.jsx("span",{className:"v10-cg-query-chip-title",children:be.name}),be.description&&s.jsx("span",{className:"v10-cg-query-chip-desc",children:be.description})]},Ze)})})]},`${q.subGraph}|${q.slug}`)})}),!(t!=null&&t.loading)&&!(t!=null&&t.error)&&z.length>0&&!J&&s.jsx(xe,{compact:!0,inline:!0,tone:"query",icon:"?",title:"No saved queries yet.",description:"Use Save after editing SPARQL to keep a reusable query for this Context Graph."})]}),s.jsxs("section",{className:"v10-cg-query-zone v10-cg-query-zone-editor","aria-labelledby":"query-catalogue-editor-title",children:[s.jsx("div",{className:"v10-cg-query-zone-header",children:s.jsxs("div",{children:[s.jsx("span",{className:"v10-cg-query-eyebrow",children:"Ad-hoc SPARQL"}),s.jsx("h3",{id:"query-catalogue-editor-title",children:"Editor and results"}),s.jsx("p",{children:"Run a one-off query against this Context Graph, or save it when it should become reusable."})]})}),s.jsxs("div",{className:"v10-cg-query-editor",children:[T&&(((Re=T.parameters)==null?void 0:Re.length)??0)>0&&s.jsx("div",{className:"v10-cg-query-parameters","aria-label":"Query parameters",children:(T.parameters??[]).map(q=>s.jsxs("label",{className:"v10-cg-query-parameter",children:[s.jsx("span",{children:q.label??q.name}),q.type==="boolean"?s.jsxs("select",{className:"v10-form-input","aria-label":q.label??q.name,value:Z[q.name]??"",onChange:ne=>i(se=>se.kind==="catalog"?{...se,values:{...se.values,[q.name]:ne.target.value}}:se),children:[s.jsx("option",{value:"",children:"Choose..."}),s.jsx("option",{value:"true",children:"True"}),s.jsx("option",{value:"false",children:"False"})]}):s.jsx("input",{className:"v10-form-input","aria-label":q.label??q.name,type:q.type==="integer"||q.type==="number"?"number":"text",step:q.type==="integer"?"1":q.type==="number"?"any":void 0,required:ma(q),value:Z[q.name]??"",placeholder:q.description,onChange:ne=>i(se=>se.kind==="catalog"?{...se,values:{...se.values,[q.name]:ne.target.value}}:se)}),q.description&&s.jsx("small",{children:q.description})]},q.name))}),N&&s.jsx("span",{className:"v10-cg-query-error-detail",children:N}),s.jsx("textarea",{className:"v10-cg-query-textarea","aria-label":"SPARQL editor",value:O,onChange:q=>{i({kind:"ad-hoc",draft:q.target.value}),j(null)},spellCheck:!1}),s.jsxs("div",{className:"v10-cg-query-actions",children:[s.jsx("button",{className:"v10-mlv-run-btn",type:"button",onClick:Y,children:"Run"}),s.jsx("button",{className:"v10-mlv-save-btn",type:"button",onClick:ye,children:"Save"}),s.jsx("button",{className:"v10-mlv-clear-btn",type:"button",onClick:V,children:"Reset"})]})]}),d&&s.jsxs("form",{className:"v10-cg-query-save-panel",onSubmit:Ne,children:[s.jsxs("label",{className:"v10-cg-query-save-field",children:[s.jsx("span",{children:"Name"}),s.jsx("input",{type:"text",value:h,onChange:q=>u(q.target.value),placeholder:"Query name",maxLength:80})]}),s.jsxs("label",{className:"v10-cg-query-save-field",children:[s.jsx("span",{children:"Description"}),s.jsx("input",{type:"text",value:p,onChange:q=>v(q.target.value),placeholder:"Optional",maxLength:180})]}),s.jsxs("div",{className:"v10-cg-query-save-actions",children:[s.jsx("button",{type:"button",className:"v10-mlv-clear-btn",onClick:()=>g(!1),disabled:y,children:"Cancel"}),s.jsx("button",{type:"submit",className:"v10-mlv-run-btn",disabled:y,children:y?"Saving...":"Save query"})]})]}),x&&s.jsx("p",{className:"v10-mlv-status",style:{color:"var(--text-success)"},children:x}),m&&s.jsx("p",{className:"v10-mlv-status",style:{color:"var(--text-danger)"},children:m}),s.jsxs("div",{className:"v10-cg-query-results",children:[!L&&s.jsx(xe,{compact:!0,tone:"query",icon:"?",title:"Enter parameters, then run this query.",description:"Previous query results are hidden so they are not presented as results for the newly selected template."}),L&&R&&s.jsx(xe,{compact:!0,tone:"query",icon:"?",title:"Loading query results..."}),L&&G&&s.jsx(xe,{compact:!0,tone:"danger",icon:"!",title:"Query could not run.",description:zo(G)}),L&&!R&&!G&&B===void 0&&F.length===0&&s.jsx(xe,{compact:!0,tone:"query",icon:"?",title:"No results for this query.",description:"Adjust the query or run a saved query against this Context Graph."}),L&&!R&&!G&&B!==void 0&&s.jsxs("div",{className:"v10-mlv-table-wrap","aria-label":"ASK result",children:[s.jsx("div",{className:"v10-mlv-result-count",children:"ASK result"}),s.jsx("strong",{children:String(B)})]}),L&&!R&&!G&&B===void 0&&F.length>0&&s.jsxs("div",{className:"v10-mlv-table-wrap",children:[s.jsxs("div",{className:"v10-mlv-result-count",children:[F.length," ",M==="quads"?`quad${F.length===1?"":"s"}`:`result${F.length===1?"":"s"}`]}),s.jsxs("table",{className:"v10-mlv-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:X.map(q=>s.jsx("th",{children:q},q))})}),s.jsx("tbody",{children:F.map((q,ne)=>s.jsx("tr",{children:X.map(se=>{const $e=Ao(q[se]);return s.jsx("td",{className:"v10-mlv-cell",title:$e,children:To($e)},se)})},ne))})]})]})]})]})]})}const Mo=({contextGraphId:e,entityUri:t,enabled:n})=>{const r=It(),i=ka(e,t,n),a=Na(e,t,n),{data:o}=ft(Yi,[],6e4),l=o==null?void 0:o.blockExplorerUrl,c=a.ual??i.ual,d=a.status==="verified";if(!n||i.loading||!i.ual&&!i.owner&&!i.publishedAt&&!d)return null;const g=i.publishedAt?Fo(i.publishedAt):null,h=i.publisherPeerId&&r?fs(i.publisherPeerId,r.agents):null,u=h?(r==null?void 0:r.get(h))??null:null,p=i.owner&&r?fs(i.owner,r.agents):null,v=p?(r==null?void 0:r.get(p))??null:null,y=w=>{var m;(m=navigator.clipboard)==null||m.writeText(w).catch(()=>{})};return s.jsxs("div",{className:"v10-vm-identity",children:[s.jsxs("div",{className:"v10-vm-identity-head",children:[s.jsx("span",{className:"v10-vm-identity-glyph",children:"◉"}),s.jsx("span",{className:"v10-vm-identity-title",children:"On-chain identity"}),s.jsx("span",{className:"v10-vm-identity-badge",children:"VERIFIED"})]}),c&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"UAL"}),s.jsx("span",{className:"v10-vm-identity-val mono",title:c,children:c}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(c),title:"Copy UAL",children:"⎘"})]}),d&&a.txHash&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"Tx"}),l?s.jsxs("a",{className:"v10-vm-identity-val mono",href:`${l}/tx/${a.txHash}`,target:"_blank",rel:"noopener noreferrer",title:a.txHash,children:[dt(a.txHash,10,8)," ↗"]}):s.jsx("span",{className:"v10-vm-identity-val mono",title:a.txHash,children:dt(a.txHash,10,8)}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(a.txHash),title:"Copy transaction hash",children:"⎘"}),a.blockNumber&&s.jsxs("span",{className:"v10-vm-identity-opid mono",children:["· block ",a.blockNumber]})]}),d&&a.kaId&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"KA id"}),s.jsx("span",{className:"v10-vm-identity-val mono",title:a.kaId,children:dt(a.kaId,8,8)}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(a.kaId),title:"Copy KA id",children:"⎘"})]}),(v||i.owner)&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"Owner"}),v?s.jsxs("span",{className:"v10-vm-identity-val",children:[s.jsx(gt,{agent:v,size:"sm"}),v.walletAddress&&s.jsx("span",{className:"v10-vm-identity-wallet mono",title:v.walletAddress,children:dt(v.walletAddress,6,4)})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"v10-vm-identity-val mono",title:i.owner??"",children:dt(i.owner,8,6)}),s.jsx("button",{type:"button",className:"v10-vm-identity-copy",onClick:()=>y(i.owner),title:"Copy owner id",children:"⎘"})]})]}),g&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"Published"}),s.jsx("span",{className:"v10-vm-identity-val",title:i.publishedAt??"",children:g}),i.opId&&s.jsxs("span",{className:"v10-vm-identity-opid mono",title:`Anchor op: ${i.opId}`,children:["· anchor ",i.opId.slice(0,10)]})]}),(u||i.publisherPeerId)&&s.jsxs("div",{className:"v10-vm-identity-row",children:[s.jsx("span",{className:"v10-vm-identity-lbl",children:"By"}),u?s.jsx(gt,{agent:u,size:"sm"}):s.jsx("span",{className:"v10-vm-identity-val mono",title:i.publisherPeerId??"",children:dt(i.publisherPeerId,8,6)})]})]})};function Fo(e){const t=new Date(e.replace(/^"|"$/g,""));return Number.isFinite(t.getTime())?t.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):e}function I(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const g in o.prototype)g in l||Object.defineProperty(l,g,{value:o.prototype[g].bind(l)});l._zod.constr=o,l._zod.def=c}const i=(n==null?void 0:n.Parent)??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(l){var c;const d=n!=null&&n.Parent?new a:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const g of d._zod.deferred)g();return d}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:l=>{var c,d;return n!=null&&n.Parent&&l instanceof n.Parent?!0:(d=(c=l==null?void 0:l._zod)==null?void 0:c.traits)==null?void 0:d.has(e)}}),Object.defineProperty(o,"name",{value:e}),o}class Tt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Or={};function st(e){return Or}function Ir(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Uo(e,t){return typeof t=="bigint"?t.toString():t}function Pr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Hn(e){return e==null}function Yn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Do(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return a%o/10**i}function he(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Xn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function wt(e){return JSON.stringify(e)}const zr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Zo=Pr(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ln(e){if(zn(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(zn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const qo=new Set(["string","number","symbol"]);function mn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function it(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function H(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Go(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Bo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Wo(e,t){const n={},r=e._zod.def;for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(n[i]=r.shape[i])}return it(e,{...e._zod.def,shape:n,checks:[]})}function Vo(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const i in t){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete n[i]}return it(e,{...e._zod.def,shape:n,checks:[]})}function Qo(e,t){if(!Ln(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Xn(this,"shape",r),r},checks:[]};return it(e,n)}function Ko(e,t){return it(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Xn(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Jo(e,t,n){const r=t._zod.def.shape,i={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(i[a]=e?new e({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)i[a]=e?new e({type:"optional",innerType:r[a]}):r[a];return it(t,{...t._zod.def,shape:i,checks:[]})}function Ho(e,t,n){const r=t._zod.def.shape,i={...r};if(n)for(const a in n){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(i[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)i[a]=new e({type:"nonoptional",innerType:r[a]});return it(t,{...t._zod.def,shape:i,checks:[]})}function Et(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function es(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ft(e){return typeof e=="string"?e:e==null?void 0:e.message}function rt(e,t,n){var i,a,o,l,c,d;const r={...e,path:e.path??[]};if(!e.message){const g=Ft((o=(a=(i=e.inst)==null?void 0:i._zod.def)==null?void 0:a.error)==null?void 0:o.call(a,e))??Ft((l=t==null?void 0:t.error)==null?void 0:l.call(t,e))??Ft((c=n.customError)==null?void 0:c.call(n,e))??Ft((d=n.localeError)==null?void 0:d.call(n,e))??"Invalid input";r.message=g}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function ts(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Rt(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const Lr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Uo,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Mr=I("$ZodError",Lr),Fr=I("$ZodError",Lr,{Parent:Error});function Yo(e,t=n=>n.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Xo(e,t){const n=t||function(a){return a.message},r={_errors:[]},i=a=>{for(const o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(l=>i({issues:l}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){const d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],c++}}};return i(e),r}const el=e=>(t,n,r,i)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Tt;if(o.issues.length){const l=new((i==null?void 0:i.Err)??e)(o.issues.map(c=>rt(c,a,st())));throw zr(l,i==null?void 0:i.callee),l}return o.value},tl=e=>async(t,n,r,i)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const l=new((i==null?void 0:i.Err)??e)(o.issues.map(c=>rt(c,a,st())));throw zr(l,i==null?void 0:i.callee),l}return o.value},Ur=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Tt;return a.issues.length?{success:!1,error:new(e??Mr)(a.issues.map(o=>rt(o,i,st())))}:{success:!0,data:a.value}},nl=Ur(Fr),Dr=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(o=>rt(o,i,st())))}:{success:!0,data:a.value}},sl=Dr(Fr),rl=/^[cC][^\s-]{8,}$/,il=/^[0-9a-z]+$/,al=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ol=/^[0-9a-vA-V]{20}$/,ll=/^[A-Za-z0-9]{27}$/,cl=/^[a-zA-Z0-9_-]{21}$/,ul=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dl=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ws=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,pl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ml(){return new RegExp(hl,"u")}const fl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,vl=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bl=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,yl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zr=/^[A-Za-z0-9_-]*$/,xl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,jl=/^\+(?:[0-9]){6,14}[0-9]$/,qr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",wl=new RegExp(`^${qr}$`);function Gr(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function kl(e){return new RegExp(`^${Gr(e)}$`)}function Nl(e){const t=Gr({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${qr}T(?:${r})$`)}const Sl=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Cl=/^\d+$/,$l=/^-?\d+(?:\.\d+)?/i,El=/^[^A-Z]*$/,_l=/^[^a-z]*$/,Te=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Br={number:"number",bigint:"bigint",object:"date"},Wr=I("$ZodCheckLessThan",(e,t)=>{Te.init(e,t);const n=Br[typeof t.value];e._zod.onattach.push(r=>{const i=r._zod.bag,a=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Vr=I("$ZodCheckGreaterThan",(e,t)=>{Te.init(e,t);const n=Br[typeof t.value];e._zod.onattach.push(r=>{const i=r._zod.bag,a=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Al=I("$ZodCheckMultipleOf",(e,t)=>{Te.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Do(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Tl=I("$ZodCheckNumberFormat",(e,t)=>{var o;Te.init(e,t),t.format=t.format||"float64";const n=(o=t.format)==null?void 0:o.includes("int"),r=n?"int":"number",[i,a]=Bo[t.format];e._zod.onattach.push(l=>{const c=l._zod.bag;c.format=t.format,c.minimum=i,c.maximum=a,n&&(c.pattern=Cl)}),e._zod.check=l=>{const c=l.value;if(n){if(!Number.isInteger(c)){l.issues.push({expected:r,format:t.format,code:"invalid_type",input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?l.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):l.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}c<i&&l.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>a&&l.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inst:e})}}),Rl=I("$ZodCheckMaxLength",(e,t)=>{var n;Te.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Hn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const i=r.value;if(i.length<=t.maximum)return;const o=ts(i);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ol=I("$ZodCheckMinLength",(e,t)=>{var n;Te.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Hn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const i=r.value;if(i.length>=t.minimum)return;const o=ts(i);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Il=I("$ZodCheckLengthEquals",(e,t)=>{var n;Te.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Hn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{const i=r.value,a=i.length;if(a===t.length)return;const o=ts(i),l=a>t.length;r.issues.push({origin:o,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),fn=I("$ZodCheckStringFormat",(e,t)=>{var n,r;Te.init(e,t),e._zod.onattach.push(i=>{const a=i._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Pl=I("$ZodCheckRegex",(e,t)=>{fn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zl=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=El),fn.init(e,t)}),Ll=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=_l),fn.init(e,t)}),Ml=I("$ZodCheckIncludes",(e,t)=>{Te.init(e,t);const n=mn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Fl=I("$ZodCheckStartsWith",(e,t)=>{Te.init(e,t);const n=new RegExp(`^${mn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Ul=I("$ZodCheckEndsWith",(e,t)=>{Te.init(e,t);const n=new RegExp(`.*${mn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Dl=I("$ZodCheckOverwrite",(e,t)=>{Te.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Zl{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
60
60
  `).filter(o=>o),i=Math.min(...r.map(o=>o.length-o.trimStart().length)),a=r.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(const o of a)this.content.push(o)}compile(){const t=Function,n=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(a=>` ${a}`)];return new t(...n,i.join(`
61
- `))}}const Zl={major:4,minor:0,patch:0},je=I("$ZodType",(e,t)=>{var i;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zl;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const o of a._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(i=e._zod.deferred)==null||i.push(()=>{e._zod.run=e._zod.parse});else{const a=(o,l,c)=>{let d=Et(o),g;for(const h of l){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(d)continue;const u=o.issues.length,p=h._zod.check(o);if(p instanceof Promise&&(c==null?void 0:c.async)===!1)throw new Rt;if(g||p instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await p,o.issues.length!==u&&(d||(d=Et(o,u)))});else{if(o.issues.length===u)continue;d||(d=Et(o,u))}}return g?g.then(()=>o):o};e._zod.run=(o,l)=>{const c=e._zod.parse(o,l);if(c instanceof Promise){if(l.async===!1)throw new Rt;return c.then(d=>a(d,r,l))}return a(c,r,l)}}e["~standard"]={validate:a=>{var o;try{const l=tl(e,a);return l.success?{value:l.data}:{issues:(o=l.error)==null?void 0:o.issues}}catch{return nl(e,a).then(c=>{var d;return c.success?{value:c.data}:{issues:(d=c.error)==null?void 0:d.issues}})}},vendor:"zod",version:1}}),ns=I("$ZodString",(e,t)=>{var n;je.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??Nl(e._zod.bag),e._zod.parse=(r,i)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),me=I("$ZodStringFormat",(e,t)=>{fn.init(e,t),ns.init(e,t)}),ql=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ul),me.init(e,t)}),Gl=I("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ws(r))}else t.pattern??(t.pattern=ws());me.init(e,t)}),Bl=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=dl),me.init(e,t)}),Wl=I("$ZodURL",(e,t)=>{me.init(e,t),e._zod.check=n=>{try{const r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:yl.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&a.endsWith("/")?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Vl=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=hl()),me.init(e,t)}),Ql=I("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ll),me.init(e,t)}),Kl=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=sl),me.init(e,t)}),Jl=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=rl),me.init(e,t)}),Yl=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=il),me.init(e,t)}),Hl=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=al),me.init(e,t)}),Xl=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ol),me.init(e,t)}),ec=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=kl(t)),me.init(e,t)}),tc=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=jl),me.init(e,t)}),nc=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=wl(t)),me.init(e,t)}),sc=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=cl),me.init(e,t)}),rc=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ml),me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),ic=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=fl),me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ac=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=gl),me.init(e,t)}),oc=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=vl),me.init(e,t),e._zod.check=n=>{const[r,i]=n.value.split("/");try{if(!i)throw new Error;const a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Vr(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const lc=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=bl),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Vr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function cc(e){if(!Dr.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Vr(n)}const uc=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Dr),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{cc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),dc=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xl),me.init(e,t)});function pc(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const hc=I("$ZodJWT",(e,t)=>{me.init(e,t),e._zod.check=n=>{pc(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Qr=I("$ZodNumber",(e,t)=>{je.init(e,t),e._zod.pattern=e._zod.bag.pattern??Cl,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const a=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),n}}),mc=I("$ZodNumber",(e,t)=>{Al.init(e,t),Qr.init(e,t)}),fc=I("$ZodUnknown",(e,t)=>{je.init(e,t),e._zod.parse=n=>n}),gc=I("$ZodNever",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function ks(e,t,n){e.issues.length&&t.issues.push(...es(n,e.issues)),t.value[n]=e.value}const vc=I("$ZodArray",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const a=[];for(let o=0;o<i.length;o++){const l=i[o],c=t.element._zod.run({value:l,issues:[]},r);c instanceof Promise?a.push(c.then(d=>ks(d,n,o))):ks(c,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function Ut(e,t,n){e.issues.length&&t.issues.push(...es(n,e.issues)),t.value[n]=e.value}function Ns(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...es(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const bc=I("$ZodObject",(e,t)=>{je.init(e,t);const n=Ir(()=>{const h=Object.keys(t.shape);for(const p of h)if(!(t.shape[p]instanceof je))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);const u=qo(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(u)}});he(e._zod,"propValues",()=>{const h=t.shape,u={};for(const p in h){const v=h[p]._zod;if(v.values){u[p]??(u[p]=new Set);for(const y of v.values)u[p].add(y)}}return u});const r=h=>{const u=new Dl(["shape","payload","ctx"]),p=n.value,v=b=>{const x=wt(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};u.write("const input = payload.value;");const y=Object.create(null);let w=0;for(const b of p.keys)y[b]=`key_${w++}`;u.write("const newResult = {}");for(const b of p.keys)if(p.optionalKeys.has(b)){const x=y[b];u.write(`const ${x} = ${v(b)};`);const k=wt(b);u.write(`
61
+ `))}}const ql={major:4,minor:0,patch:0},je=I("$ZodType",(e,t)=>{var i;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ql;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const o of a._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(i=e._zod.deferred)==null||i.push(()=>{e._zod.run=e._zod.parse});else{const a=(o,l,c)=>{let d=Et(o),g;for(const h of l){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(d)continue;const u=o.issues.length,p=h._zod.check(o);if(p instanceof Promise&&(c==null?void 0:c.async)===!1)throw new Tt;if(g||p instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await p,o.issues.length!==u&&(d||(d=Et(o,u)))});else{if(o.issues.length===u)continue;d||(d=Et(o,u))}}return g?g.then(()=>o):o};e._zod.run=(o,l)=>{const c=e._zod.parse(o,l);if(c instanceof Promise){if(l.async===!1)throw new Tt;return c.then(d=>a(d,r,l))}return a(c,r,l)}}e["~standard"]={validate:a=>{var o;try{const l=nl(e,a);return l.success?{value:l.data}:{issues:(o=l.error)==null?void 0:o.issues}}catch{return sl(e,a).then(c=>{var d;return c.success?{value:c.data}:{issues:(d=c.error)==null?void 0:d.issues}})}},vendor:"zod",version:1}}),ns=I("$ZodString",(e,t)=>{var n;je.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??Sl(e._zod.bag),e._zod.parse=(r,i)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),me=I("$ZodStringFormat",(e,t)=>{fn.init(e,t),ns.init(e,t)}),Gl=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=dl),me.init(e,t)}),Bl=I("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ws(r))}else t.pattern??(t.pattern=ws());me.init(e,t)}),Wl=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=pl),me.init(e,t)}),Vl=I("$ZodURL",(e,t)=>{me.init(e,t),e._zod.check=n=>{try{const r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:xl.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&a.endsWith("/")?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Ql=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ml()),me.init(e,t)}),Kl=I("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=cl),me.init(e,t)}),Jl=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=rl),me.init(e,t)}),Hl=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=il),me.init(e,t)}),Yl=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=al),me.init(e,t)}),Xl=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ol),me.init(e,t)}),ec=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ll),me.init(e,t)}),tc=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Nl(t)),me.init(e,t)}),nc=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=wl),me.init(e,t)}),sc=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=kl(t)),me.init(e,t)}),rc=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ul),me.init(e,t)}),ic=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=fl),me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),ac=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=gl),me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),oc=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=vl),me.init(e,t)}),lc=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bl),me.init(e,t),e._zod.check=n=>{const[r,i]=n.value.split("/");try{if(!i)throw new Error;const a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Qr(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const cc=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=yl),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Qr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function uc(e){if(!Zr.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Qr(n)}const dc=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Zr),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{uc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),pc=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=jl),me.init(e,t)});function hc(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const mc=I("$ZodJWT",(e,t)=>{me.init(e,t),e._zod.check=n=>{hc(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Kr=I("$ZodNumber",(e,t)=>{je.init(e,t),e._zod.pattern=e._zod.bag.pattern??$l,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const a=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),n}}),fc=I("$ZodNumber",(e,t)=>{Tl.init(e,t),Kr.init(e,t)}),gc=I("$ZodUnknown",(e,t)=>{je.init(e,t),e._zod.parse=n=>n}),vc=I("$ZodNever",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function ks(e,t,n){e.issues.length&&t.issues.push(...es(n,e.issues)),t.value[n]=e.value}const bc=I("$ZodArray",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const a=[];for(let o=0;o<i.length;o++){const l=i[o],c=t.element._zod.run({value:l,issues:[]},r);c instanceof Promise?a.push(c.then(d=>ks(d,n,o))):ks(c,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function Ut(e,t,n){e.issues.length&&t.issues.push(...es(n,e.issues)),t.value[n]=e.value}function Ns(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...es(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const yc=I("$ZodObject",(e,t)=>{je.init(e,t);const n=Pr(()=>{const h=Object.keys(t.shape);for(const p of h)if(!(t.shape[p]instanceof je))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);const u=Go(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(u)}});he(e._zod,"propValues",()=>{const h=t.shape,u={};for(const p in h){const v=h[p]._zod;if(v.values){u[p]??(u[p]=new Set);for(const y of v.values)u[p].add(y)}}return u});const r=h=>{const u=new Zl(["shape","payload","ctx"]),p=n.value,v=b=>{const x=wt(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};u.write("const input = payload.value;");const y=Object.create(null);let w=0;for(const b of p.keys)y[b]=`key_${w++}`;u.write("const newResult = {}");for(const b of p.keys)if(p.optionalKeys.has(b)){const x=y[b];u.write(`const ${x} = ${v(b)};`);const k=wt(b);u.write(`
62
62
  if (${x}.issues.length) {
63
63
  if (input[${k}] === undefined) {
64
64
  if (${k} in input) {
@@ -81,10 +81,10 @@ LIMIT 100`,resultColumn:"type",rank:3})]}}function $o(e,t,n,r,i=[],a,o=Xe){const
81
81
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
82
82
  ...iss,
83
83
  path: iss.path ? [${wt(b)}, ...iss.path] : [${wt(b)}]
84
- })));`),u.write(`newResult[${wt(b)}] = ${x}.value`)}u.write("payload.value = newResult;"),u.write("return payload;");const m=u.compile();return(b,x)=>m(h,b,x)};let i;const a=zn,o=!Tr.jitless,c=o&&Do.value,d=t.catchall;let g;e._zod.parse=(h,u)=>{g??(g=n.value);const p=h.value;if(!a(p))return h.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),h;const v=[];if(o&&c&&(u==null?void 0:u.async)===!1&&u.jitless!==!0)i||(i=r(t.shape)),h=i(h,u);else{h.value={};const x=g.shape;for(const k of g.keys){const S=x[k],j=S._zod.run({value:p[k],issues:[]},u),_=S._zod.optin==="optional"&&S._zod.optout==="optional";j instanceof Promise?v.push(j.then(z=>_?Ns(z,h,k,p):Ut(z,h,k))):_?Ns(j,h,k,p):Ut(j,h,k)}}if(!d)return v.length?Promise.all(v).then(()=>h):h;const y=[],w=g.keySet,m=d._zod,b=m.def.type;for(const x of Object.keys(p)){if(w.has(x))continue;if(b==="never"){y.push(x);continue}const k=m.run({value:p[x],issues:[]},u);k instanceof Promise?v.push(k.then(S=>Ut(S,h,x))):Ut(k,h,x)}return y.length&&h.issues.push({code:"unrecognized_keys",keys:y,input:p,inst:e}),v.length?Promise.all(v).then(()=>h):h}});function Ss(e,t,n,r){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(a=>rt(a,r,st())))}),t}const yc=I("$ZodUnion",(e,t)=>{je.init(e,t),he(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),he(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),he(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),he(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Hn(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let i=!1;const a=[];for(const o of t.options){const l=o._zod.run({value:n.value,issues:[]},r);if(l instanceof Promise)a.push(l),i=!0;else{if(l.issues.length===0)return l;a.push(l)}}return i?Promise.all(a).then(o=>Ss(o,n,e,r)):Ss(a,n,e,r)}}),xc=I("$ZodIntersection",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,a=t.left._zod.run({value:i,issues:[]},r),o=t.right._zod.run({value:i,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([c,d])=>Cs(n,c,d)):Cs(n,a,o)}});function Mn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ln(e)&&Ln(t)){const n=Object.keys(t),r=Object.keys(e).filter(a=>n.indexOf(a)!==-1),i={...e,...t};for(const a of r){const o=Mn(e[a],t[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};i[a]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r],a=t[r],o=Mn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Cs(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Et(e))return e;const r=Mn(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const jc=I("$ZodEnum",(e,t)=>{je.init(e,t);const n=Or(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>Zo.has(typeof r)).map(r=>typeof r=="string"?mn(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const a=r.value;return e._zod.values.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),wc=I("$ZodTransform",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>{const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(n.value=o,n));if(i instanceof Promise)throw new Rt;return n.value=i,n}}),kc=I("$ZodOptional",(e,t)=>{je.init(e,t),e._zod.optin="optional",e._zod.optout="optional",he(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),he(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Hn(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Nc=I("$ZodNullable",(e,t)=>{je.init(e,t),he(e._zod,"optin",()=>t.innerType._zod.optin),he(e._zod,"optout",()=>t.innerType._zod.optout),he(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Hn(n.source)}|null)$`):void 0}),he(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Sc=I("$ZodDefault",(e,t)=>{je.init(e,t),e._zod.optin="optional",he(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(a=>$s(a,t)):$s(i,t)}});function $s(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Cc=I("$ZodPrefault",(e,t)=>{je.init(e,t),e._zod.optin="optional",he(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),$c=I("$ZodNonOptional",(e,t)=>{je.init(e,t),he(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(a=>Es(a,e)):Es(i,e)}});function Es(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ec=I("$ZodCatch",(e,t)=>{je.init(e,t),e._zod.optin="optional",he(e._zod,"optout",()=>t.innerType._zod.optout),he(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(a=>(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(o=>rt(o,r,st()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(a=>rt(a,r,st()))},input:n.value}),n.issues=[]),n)}}),_c=I("$ZodPipe",(e,t)=>{je.init(e,t),he(e._zod,"values",()=>t.in._zod.values),he(e._zod,"optin",()=>t.in._zod.optin),he(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(a=>_s(a,t,r)):_s(i,t,r)}});function _s(e,t,n){return Et(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Ac=I("$ZodReadonly",(e,t)=>{je.init(e,t),he(e._zod,"propValues",()=>t.innerType._zod.propValues),he(e._zod,"values",()=>t.innerType._zod.values),he(e._zod,"optin",()=>t.innerType._zod.optin),he(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(As):As(i)}});function As(e){return e.value=Object.freeze(e.value),e}const Rc=I("$ZodCustom",(e,t)=>{Re.init(e,t),je.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(a=>Rs(a,n,r,e));Rs(i,n,r,e)}});function Rs(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Tt(i))}}class Kr{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function Jr(){return new Kr}const Ct=Jr();function Tc(e,t){return new e({type:"string",...Y(t)})}function Oc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Y(t)})}function Ts(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Y(t)})}function Ic(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Y(t)})}function Pc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y(t)})}function zc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y(t)})}function Lc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y(t)})}function Mc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Y(t)})}function Fc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Y(t)})}function Uc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y(t)})}function Dc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Y(t)})}function Zc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y(t)})}function qc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Y(t)})}function Gc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Y(t)})}function Bc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y(t)})}function Wc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y(t)})}function Vc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y(t)})}function Qc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y(t)})}function Kc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y(t)})}function Jc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Y(t)})}function Yc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Y(t)})}function Hc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Y(t)})}function Xc(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Y(t)})}function eu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y(t)})}function tu(e,t){return new e({type:"string",format:"date",check:"string_format",...Y(t)})}function nu(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Y(t)})}function su(e,t){return new e({type:"string",format:"duration",check:"string_format",...Y(t)})}function ru(e,t){return new e({type:"number",checks:[],...Y(t)})}function iu(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Y(t)})}function au(e){return new e({type:"unknown"})}function ou(e,t){return new e({type:"never",...Y(t)})}function Os(e,t){return new Br({check:"less_than",...Y(t),value:e,inclusive:!1})}function kn(e,t){return new Br({check:"less_than",...Y(t),value:e,inclusive:!0})}function Is(e,t){return new Wr({check:"greater_than",...Y(t),value:e,inclusive:!1})}function Nn(e,t){return new Wr({check:"greater_than",...Y(t),value:e,inclusive:!0})}function Ps(e,t){return new _l({check:"multiple_of",...Y(t),value:e})}function Yr(e,t){return new Rl({check:"max_length",...Y(t),maximum:e})}function an(e,t){return new Tl({check:"min_length",...Y(t),minimum:e})}function Hr(e,t){return new Ol({check:"length_equals",...Y(t),length:e})}function lu(e,t){return new Il({check:"string_format",format:"regex",...Y(t),pattern:e})}function cu(e){return new Pl({check:"string_format",format:"lowercase",...Y(e)})}function uu(e){return new zl({check:"string_format",format:"uppercase",...Y(e)})}function du(e,t){return new Ll({check:"string_format",format:"includes",...Y(t),includes:e})}function pu(e,t){return new Ml({check:"string_format",format:"starts_with",...Y(t),prefix:e})}function hu(e,t){return new Fl({check:"string_format",format:"ends_with",...Y(t),suffix:e})}function Pt(e){return new Ul({check:"overwrite",tx:e})}function mu(e){return Pt(t=>t.normalize(e))}function fu(){return Pt(e=>e.trim())}function gu(){return Pt(e=>e.toLowerCase())}function vu(){return Pt(e=>e.toUpperCase())}function bu(e,t,n){return new e({type:"array",element:t,...Y(n)})}function yu(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Y(n)})}class zs{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??Ct,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var h,u,p;var r;const i=t._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,n.schemaPath.includes(t)&&(o.cycle=n.path),o.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,l);const c=(u=(h=t._zod).toJSONSchema)==null?void 0:u.call(h);if(c)l.schema=c;else{const v={...n,schemaPath:[...n.schemaPath,t],path:n.path},y=t._zod.parent;if(y)l.ref=y,this.process(y,v),this.seen.get(y).isParent=!0;else{const w=l.schema;switch(i.type){case"string":{const m=w;m.type="string";const{minimum:b,maximum:x,format:k,patterns:S,contentEncoding:j}=t._zod.bag;if(typeof b=="number"&&(m.minLength=b),typeof x=="number"&&(m.maxLength=x),k&&(m.format=a[k]??k,m.format===""&&delete m.format),j&&(m.contentEncoding=j),S&&S.size>0){const _=[...S];_.length===1?m.pattern=_[0].source:_.length>1&&(l.schema.allOf=[..._.map(z=>({...this.target==="draft-7"?{type:"string"}:{},pattern:z.source}))])}break}case"number":{const m=w,{minimum:b,maximum:x,format:k,multipleOf:S,exclusiveMaximum:j,exclusiveMinimum:_}=t._zod.bag;typeof k=="string"&&k.includes("int")?m.type="integer":m.type="number",typeof _=="number"&&(m.exclusiveMinimum=_),typeof b=="number"&&(m.minimum=b,typeof _=="number"&&(_>=b?delete m.minimum:delete m.exclusiveMinimum)),typeof j=="number"&&(m.exclusiveMaximum=j),typeof x=="number"&&(m.maximum=x,typeof j=="number"&&(j<=x?delete m.maximum:delete m.exclusiveMaximum)),typeof S=="number"&&(m.multipleOf=S);break}case"boolean":{const m=w;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{w.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{w.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=w,{minimum:b,maximum:x}=t._zod.bag;typeof b=="number"&&(m.minItems=b),typeof x=="number"&&(m.maxItems=x),m.type="array",m.items=this.process(i.element,{...v,path:[...v.path,"items"]});break}case"object":{const m=w;m.type="object",m.properties={};const b=i.shape;for(const S in b)m.properties[S]=this.process(b[S],{...v,path:[...v.path,"properties",S]});const x=new Set(Object.keys(b)),k=new Set([...x].filter(S=>{const j=i.shape[S]._zod;return this.io==="input"?j.optin===void 0:j.optout===void 0}));k.size>0&&(m.required=Array.from(k)),((p=i.catchall)==null?void 0:p._zod.def.type)==="never"?m.additionalProperties=!1:i.catchall?i.catchall&&(m.additionalProperties=this.process(i.catchall,{...v,path:[...v.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=w;m.anyOf=i.options.map((b,x)=>this.process(b,{...v,path:[...v.path,"anyOf",x]}));break}case"intersection":{const m=w,b=this.process(i.left,{...v,path:[...v.path,"allOf",0]}),x=this.process(i.right,{...v,path:[...v.path,"allOf",1]}),k=j=>"allOf"in j&&Object.keys(j).length===1,S=[...k(b)?b.allOf:[b],...k(x)?x.allOf:[x]];m.allOf=S;break}case"tuple":{const m=w;m.type="array";const b=i.items.map((S,j)=>this.process(S,{...v,path:[...v.path,"prefixItems",j]}));if(this.target==="draft-2020-12"?m.prefixItems=b:m.items=b,i.rest){const S=this.process(i.rest,{...v,path:[...v.path,"items"]});this.target==="draft-2020-12"?m.items=S:m.additionalItems=S}i.rest&&(m.items=this.process(i.rest,{...v,path:[...v.path,"items"]}));const{minimum:x,maximum:k}=t._zod.bag;typeof x=="number"&&(m.minItems=x),typeof k=="number"&&(m.maxItems=k);break}case"record":{const m=w;m.type="object",m.propertyNames=this.process(i.keyType,{...v,path:[...v.path,"propertyNames"]}),m.additionalProperties=this.process(i.valueType,{...v,path:[...v.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const m=w,b=Or(i.entries);b.every(x=>typeof x=="number")&&(m.type="number"),b.every(x=>typeof x=="string")&&(m.type="string"),m.enum=b;break}case"literal":{const m=w,b=[];for(const x of i.values)if(x===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof x=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(x))}else b.push(x);if(b.length!==0)if(b.length===1){const x=b[0];m.type=x===null?"null":typeof x,m.const=x}else b.every(x=>typeof x=="number")&&(m.type="number"),b.every(x=>typeof x=="string")&&(m.type="string"),b.every(x=>typeof x=="boolean")&&(m.type="string"),b.every(x=>x===null)&&(m.type="null"),m.enum=b;break}case"file":{const m=w,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:x,maximum:k,mime:S}=t._zod.bag;x!==void 0&&(b.minLength=x),k!==void 0&&(b.maxLength=k),S?S.length===1?(b.contentMediaType=S[0],Object.assign(m,b)):m.anyOf=S.map(j=>({...b,contentMediaType:j})):Object.assign(m,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(i.innerType,v);w.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,v),l.ref=i.innerType;break}case"success":{const m=w;m.type="boolean";break}case"default":{this.process(i.innerType,v),l.ref=i.innerType,w.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,v),l.ref=i.innerType,this.io==="input"&&(w._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,v),l.ref=i.innerType;let m;try{m=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}w.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=w,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=b.source;break}case"pipe":{const m=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(m,v),l.ref=m;break}case"readonly":{this.process(i.innerType,v),l.ref=i.innerType,w.readOnly=!0;break}case"promise":{this.process(i.innerType,v),l.ref=i.innerType;break}case"optional":{this.process(i.innerType,v),l.ref=i.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,v),l.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const d=this.metadataRegistry.get(t);return d&&Object.assign(l.schema,d),this.io==="input"&&we(t)&&(delete l.schema.examples,delete l.schema.default),this.io==="input"&&l.schema._prefault&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,this.seen.get(t).schema}emit(t,n){var g,h,u,p,v,y;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},i=this.seen.get(t);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=w=>{var S;const m=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const j=(S=r.external.registry.get(w[0]))==null?void 0:S.id,_=r.external.uri??(E=>E);if(j)return{ref:_(j)};const z=w[1].defId??w[1].schema.id??`schema${this.counter++}`;return w[1].defId=z,{defId:z,ref:`${_("__shared")}#/${m}/${z}`}}if(w[1]===i)return{ref:"#"};const x=`#/${m}/`,k=w[1].schema.id??`__schema${this.counter++}`;return{defId:k,ref:x+k}},o=w=>{if(w[1].schema.$ref)return;const m=w[1],{ref:b,defId:x}=a(w);m.def={...m.schema},x&&(m.defId=x);const k=m.schema;for(const S in k)delete k[S];k.$ref=b};if(r.cycles==="throw")for(const w of this.seen.entries()){const m=w[1];if(m.cycle)throw new Error(`Cycle detected: #/${(g=m.cycle)==null?void 0:g.join("/")}/<root>
84
+ })));`),u.write(`newResult[${wt(b)}] = ${x}.value`)}u.write("payload.value = newResult;"),u.write("return payload;");const m=u.compile();return(b,x)=>m(h,b,x)};let i;const a=zn,o=!Or.jitless,c=o&&Zo.value,d=t.catchall;let g;e._zod.parse=(h,u)=>{g??(g=n.value);const p=h.value;if(!a(p))return h.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),h;const v=[];if(o&&c&&(u==null?void 0:u.async)===!1&&u.jitless!==!0)i||(i=r(t.shape)),h=i(h,u);else{h.value={};const x=g.shape;for(const k of g.keys){const N=x[k],j=N._zod.run({value:p[k],issues:[]},u),_=N._zod.optin==="optional"&&N._zod.optout==="optional";j instanceof Promise?v.push(j.then(z=>_?Ns(z,h,k,p):Ut(z,h,k))):_?Ns(j,h,k,p):Ut(j,h,k)}}if(!d)return v.length?Promise.all(v).then(()=>h):h;const y=[],w=g.keySet,m=d._zod,b=m.def.type;for(const x of Object.keys(p)){if(w.has(x))continue;if(b==="never"){y.push(x);continue}const k=m.run({value:p[x],issues:[]},u);k instanceof Promise?v.push(k.then(N=>Ut(N,h,x))):Ut(k,h,x)}return y.length&&h.issues.push({code:"unrecognized_keys",keys:y,input:p,inst:e}),v.length?Promise.all(v).then(()=>h):h}});function Ss(e,t,n,r){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(a=>rt(a,r,st())))}),t}const xc=I("$ZodUnion",(e,t)=>{je.init(e,t),he(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),he(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),he(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),he(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Yn(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let i=!1;const a=[];for(const o of t.options){const l=o._zod.run({value:n.value,issues:[]},r);if(l instanceof Promise)a.push(l),i=!0;else{if(l.issues.length===0)return l;a.push(l)}}return i?Promise.all(a).then(o=>Ss(o,n,e,r)):Ss(a,n,e,r)}}),jc=I("$ZodIntersection",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,a=t.left._zod.run({value:i,issues:[]},r),o=t.right._zod.run({value:i,issues:[]},r);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([c,d])=>Cs(n,c,d)):Cs(n,a,o)}});function Mn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ln(e)&&Ln(t)){const n=Object.keys(t),r=Object.keys(e).filter(a=>n.indexOf(a)!==-1),i={...e,...t};for(const a of r){const o=Mn(e[a],t[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};i[a]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r],a=t[r],o=Mn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Cs(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Et(e))return e;const r=Mn(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const wc=I("$ZodEnum",(e,t)=>{je.init(e,t);const n=Ir(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>qo.has(typeof r)).map(r=>typeof r=="string"?mn(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const a=r.value;return e._zod.values.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),kc=I("$ZodTransform",(e,t)=>{je.init(e,t),e._zod.parse=(n,r)=>{const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(n.value=o,n));if(i instanceof Promise)throw new Tt;return n.value=i,n}}),Nc=I("$ZodOptional",(e,t)=>{je.init(e,t),e._zod.optin="optional",e._zod.optout="optional",he(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),he(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Yn(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Sc=I("$ZodNullable",(e,t)=>{je.init(e,t),he(e._zod,"optin",()=>t.innerType._zod.optin),he(e._zod,"optout",()=>t.innerType._zod.optout),he(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Yn(n.source)}|null)$`):void 0}),he(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Cc=I("$ZodDefault",(e,t)=>{je.init(e,t),e._zod.optin="optional",he(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(a=>$s(a,t)):$s(i,t)}});function $s(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const $c=I("$ZodPrefault",(e,t)=>{je.init(e,t),e._zod.optin="optional",he(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Ec=I("$ZodNonOptional",(e,t)=>{je.init(e,t),he(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(a=>Es(a,e)):Es(i,e)}});function Es(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const _c=I("$ZodCatch",(e,t)=>{je.init(e,t),e._zod.optin="optional",he(e._zod,"optout",()=>t.innerType._zod.optout),he(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(a=>(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(o=>rt(o,r,st()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(a=>rt(a,r,st()))},input:n.value}),n.issues=[]),n)}}),Ac=I("$ZodPipe",(e,t)=>{je.init(e,t),he(e._zod,"values",()=>t.in._zod.values),he(e._zod,"optin",()=>t.in._zod.optin),he(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(a=>_s(a,t,r)):_s(i,t,r)}});function _s(e,t,n){return Et(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Tc=I("$ZodReadonly",(e,t)=>{je.init(e,t),he(e._zod,"propValues",()=>t.innerType._zod.propValues),he(e._zod,"values",()=>t.innerType._zod.values),he(e._zod,"optin",()=>t.innerType._zod.optin),he(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(As):As(i)}});function As(e){return e.value=Object.freeze(e.value),e}const Rc=I("$ZodCustom",(e,t)=>{Te.init(e,t),je.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(a=>Ts(a,n,r,e));Ts(i,n,r,e)}});function Ts(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Rt(i))}}class Jr{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function Hr(){return new Jr}const Ct=Hr();function Oc(e,t){return new e({type:"string",...H(t)})}function Ic(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...H(t)})}function Rs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...H(t)})}function Pc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...H(t)})}function zc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...H(t)})}function Lc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...H(t)})}function Mc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...H(t)})}function Fc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...H(t)})}function Uc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...H(t)})}function Dc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...H(t)})}function Zc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...H(t)})}function qc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...H(t)})}function Gc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...H(t)})}function Bc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...H(t)})}function Wc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...H(t)})}function Vc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...H(t)})}function Qc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...H(t)})}function Kc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...H(t)})}function Jc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...H(t)})}function Hc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...H(t)})}function Yc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...H(t)})}function Xc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...H(t)})}function eu(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...H(t)})}function tu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...H(t)})}function nu(e,t){return new e({type:"string",format:"date",check:"string_format",...H(t)})}function su(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...H(t)})}function ru(e,t){return new e({type:"string",format:"duration",check:"string_format",...H(t)})}function iu(e,t){return new e({type:"number",checks:[],...H(t)})}function au(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...H(t)})}function ou(e){return new e({type:"unknown"})}function lu(e,t){return new e({type:"never",...H(t)})}function Os(e,t){return new Wr({check:"less_than",...H(t),value:e,inclusive:!1})}function kn(e,t){return new Wr({check:"less_than",...H(t),value:e,inclusive:!0})}function Is(e,t){return new Vr({check:"greater_than",...H(t),value:e,inclusive:!1})}function Nn(e,t){return new Vr({check:"greater_than",...H(t),value:e,inclusive:!0})}function Ps(e,t){return new Al({check:"multiple_of",...H(t),value:e})}function Yr(e,t){return new Rl({check:"max_length",...H(t),maximum:e})}function an(e,t){return new Ol({check:"min_length",...H(t),minimum:e})}function Xr(e,t){return new Il({check:"length_equals",...H(t),length:e})}function cu(e,t){return new Pl({check:"string_format",format:"regex",...H(t),pattern:e})}function uu(e){return new zl({check:"string_format",format:"lowercase",...H(e)})}function du(e){return new Ll({check:"string_format",format:"uppercase",...H(e)})}function pu(e,t){return new Ml({check:"string_format",format:"includes",...H(t),includes:e})}function hu(e,t){return new Fl({check:"string_format",format:"starts_with",...H(t),prefix:e})}function mu(e,t){return new Ul({check:"string_format",format:"ends_with",...H(t),suffix:e})}function Pt(e){return new Dl({check:"overwrite",tx:e})}function fu(e){return Pt(t=>t.normalize(e))}function gu(){return Pt(e=>e.trim())}function vu(){return Pt(e=>e.toLowerCase())}function bu(){return Pt(e=>e.toUpperCase())}function yu(e,t,n){return new e({type:"array",element:t,...H(n)})}function xu(e,t,n){return new e({type:"custom",check:"custom",fn:t,...H(n)})}class zs{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??Ct,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var h,u,p;var r;const i=t._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,n.schemaPath.includes(t)&&(o.cycle=n.path),o.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,l);const c=(u=(h=t._zod).toJSONSchema)==null?void 0:u.call(h);if(c)l.schema=c;else{const v={...n,schemaPath:[...n.schemaPath,t],path:n.path},y=t._zod.parent;if(y)l.ref=y,this.process(y,v),this.seen.get(y).isParent=!0;else{const w=l.schema;switch(i.type){case"string":{const m=w;m.type="string";const{minimum:b,maximum:x,format:k,patterns:N,contentEncoding:j}=t._zod.bag;if(typeof b=="number"&&(m.minLength=b),typeof x=="number"&&(m.maxLength=x),k&&(m.format=a[k]??k,m.format===""&&delete m.format),j&&(m.contentEncoding=j),N&&N.size>0){const _=[...N];_.length===1?m.pattern=_[0].source:_.length>1&&(l.schema.allOf=[..._.map(z=>({...this.target==="draft-7"?{type:"string"}:{},pattern:z.source}))])}break}case"number":{const m=w,{minimum:b,maximum:x,format:k,multipleOf:N,exclusiveMaximum:j,exclusiveMinimum:_}=t._zod.bag;typeof k=="string"&&k.includes("int")?m.type="integer":m.type="number",typeof _=="number"&&(m.exclusiveMinimum=_),typeof b=="number"&&(m.minimum=b,typeof _=="number"&&(_>=b?delete m.minimum:delete m.exclusiveMinimum)),typeof j=="number"&&(m.exclusiveMaximum=j),typeof x=="number"&&(m.maximum=x,typeof j=="number"&&(j<=x?delete m.maximum:delete m.exclusiveMaximum)),typeof N=="number"&&(m.multipleOf=N);break}case"boolean":{const m=w;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{w.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{w.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=w,{minimum:b,maximum:x}=t._zod.bag;typeof b=="number"&&(m.minItems=b),typeof x=="number"&&(m.maxItems=x),m.type="array",m.items=this.process(i.element,{...v,path:[...v.path,"items"]});break}case"object":{const m=w;m.type="object",m.properties={};const b=i.shape;for(const N in b)m.properties[N]=this.process(b[N],{...v,path:[...v.path,"properties",N]});const x=new Set(Object.keys(b)),k=new Set([...x].filter(N=>{const j=i.shape[N]._zod;return this.io==="input"?j.optin===void 0:j.optout===void 0}));k.size>0&&(m.required=Array.from(k)),((p=i.catchall)==null?void 0:p._zod.def.type)==="never"?m.additionalProperties=!1:i.catchall?i.catchall&&(m.additionalProperties=this.process(i.catchall,{...v,path:[...v.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=w;m.anyOf=i.options.map((b,x)=>this.process(b,{...v,path:[...v.path,"anyOf",x]}));break}case"intersection":{const m=w,b=this.process(i.left,{...v,path:[...v.path,"allOf",0]}),x=this.process(i.right,{...v,path:[...v.path,"allOf",1]}),k=j=>"allOf"in j&&Object.keys(j).length===1,N=[...k(b)?b.allOf:[b],...k(x)?x.allOf:[x]];m.allOf=N;break}case"tuple":{const m=w;m.type="array";const b=i.items.map((N,j)=>this.process(N,{...v,path:[...v.path,"prefixItems",j]}));if(this.target==="draft-2020-12"?m.prefixItems=b:m.items=b,i.rest){const N=this.process(i.rest,{...v,path:[...v.path,"items"]});this.target==="draft-2020-12"?m.items=N:m.additionalItems=N}i.rest&&(m.items=this.process(i.rest,{...v,path:[...v.path,"items"]}));const{minimum:x,maximum:k}=t._zod.bag;typeof x=="number"&&(m.minItems=x),typeof k=="number"&&(m.maxItems=k);break}case"record":{const m=w;m.type="object",m.propertyNames=this.process(i.keyType,{...v,path:[...v.path,"propertyNames"]}),m.additionalProperties=this.process(i.valueType,{...v,path:[...v.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const m=w,b=Ir(i.entries);b.every(x=>typeof x=="number")&&(m.type="number"),b.every(x=>typeof x=="string")&&(m.type="string"),m.enum=b;break}case"literal":{const m=w,b=[];for(const x of i.values)if(x===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof x=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(x))}else b.push(x);if(b.length!==0)if(b.length===1){const x=b[0];m.type=x===null?"null":typeof x,m.const=x}else b.every(x=>typeof x=="number")&&(m.type="number"),b.every(x=>typeof x=="string")&&(m.type="string"),b.every(x=>typeof x=="boolean")&&(m.type="string"),b.every(x=>x===null)&&(m.type="null"),m.enum=b;break}case"file":{const m=w,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:x,maximum:k,mime:N}=t._zod.bag;x!==void 0&&(b.minLength=x),k!==void 0&&(b.maxLength=k),N?N.length===1?(b.contentMediaType=N[0],Object.assign(m,b)):m.anyOf=N.map(j=>({...b,contentMediaType:j})):Object.assign(m,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(i.innerType,v);w.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,v),l.ref=i.innerType;break}case"success":{const m=w;m.type="boolean";break}case"default":{this.process(i.innerType,v),l.ref=i.innerType,w.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,v),l.ref=i.innerType,this.io==="input"&&(w._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,v),l.ref=i.innerType;let m;try{m=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}w.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=w,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=b.source;break}case"pipe":{const m=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(m,v),l.ref=m;break}case"readonly":{this.process(i.innerType,v),l.ref=i.innerType,w.readOnly=!0;break}case"promise":{this.process(i.innerType,v),l.ref=i.innerType;break}case"optional":{this.process(i.innerType,v),l.ref=i.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,v),l.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const d=this.metadataRegistry.get(t);return d&&Object.assign(l.schema,d),this.io==="input"&&we(t)&&(delete l.schema.examples,delete l.schema.default),this.io==="input"&&l.schema._prefault&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,this.seen.get(t).schema}emit(t,n){var g,h,u,p,v,y;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},i=this.seen.get(t);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=w=>{var N;const m=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const j=(N=r.external.registry.get(w[0]))==null?void 0:N.id,_=r.external.uri??(E=>E);if(j)return{ref:_(j)};const z=w[1].defId??w[1].schema.id??`schema${this.counter++}`;return w[1].defId=z,{defId:z,ref:`${_("__shared")}#/${m}/${z}`}}if(w[1]===i)return{ref:"#"};const x=`#/${m}/`,k=w[1].schema.id??`__schema${this.counter++}`;return{defId:k,ref:x+k}},o=w=>{if(w[1].schema.$ref)return;const m=w[1],{ref:b,defId:x}=a(w);m.def={...m.schema},x&&(m.defId=x);const k=m.schema;for(const N in k)delete k[N];k.$ref=b};if(r.cycles==="throw")for(const w of this.seen.entries()){const m=w[1];if(m.cycle)throw new Error(`Cycle detected: #/${(g=m.cycle)==null?void 0:g.join("/")}/<root>
85
85
 
86
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const w of this.seen.entries()){const m=w[1];if(t===w[0]){o(w);continue}if(r.external){const x=(h=r.external.registry.get(w[0]))==null?void 0:h.id;if(t!==w[0]&&x){o(w);continue}}if((u=this.metadataRegistry.get(w[0]))==null?void 0:u.id){o(w);continue}if(m.cycle){o(w);continue}if(m.count>1&&r.reused==="ref"){o(w);continue}}const l=(w,m)=>{const b=this.seen.get(w),x=b.def??b.schema,k={...x};if(b.ref===null)return;const S=b.ref;if(b.ref=null,S){l(S,m);const j=this.seen.get(S).schema;j.$ref&&m.target==="draft-7"?(x.allOf=x.allOf??[],x.allOf.push(j)):(Object.assign(x,j),Object.assign(x,k))}b.isParent||this.override({zodSchema:w,jsonSchema:x,path:b.path??[]})};for(const w of[...this.seen.entries()].reverse())l(w[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(p=r.external)!=null&&p.uri){const w=(v=r.external.registry.get(t))==null?void 0:v.id;if(!w)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(w)}Object.assign(c,i.def);const d=((y=r.external)==null?void 0:y.defs)??{};for(const w of this.seen.entries()){const m=w[1];m.def&&m.defId&&(d[m.defId]=m.def)}r.external||Object.keys(d).length>0&&(this.target==="draft-2020-12"?c.$defs=d:c.definitions=d);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function xu(e,t){if(e instanceof Kr){const r=new zs(t),i={};for(const l of e._idmap.entries()){const[c,d]=l;r.process(d)}const a={},o={registry:e,uri:t==null?void 0:t.uri,defs:i};for(const l of e._idmap.entries()){const[c,d]=l;a[c]=r.emit(d,{...t,external:o})}if(Object.keys(i).length>0){const l=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[l]:i}}return{schemas:a}}const n=new zs(t);return n.process(e),n.emit(e,t)}function we(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return we(i.element,n);case"object":{for(const a in i.shape)if(we(i.shape[a],n))return!0;return!1}case"union":{for(const a of i.options)if(we(a,n))return!0;return!1}case"intersection":return we(i.left,n)||we(i.right,n);case"tuple":{for(const a of i.items)if(we(a,n))return!0;return!!(i.rest&&we(i.rest,n))}case"record":return we(i.keyType,n)||we(i.valueType,n);case"map":return we(i.keyType,n)||we(i.valueType,n);case"set":return we(i.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return we(i.innerType,n);case"lazy":return we(i.getter(),n);case"default":return we(i.innerType,n);case"prefault":return we(i.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return we(i.in,n)||we(i.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${i.type}`)}const ju=I("ZodISODateTime",(e,t)=>{ec.init(e,t),ve.init(e,t)});function wu(e){return eu(ju,e)}const ku=I("ZodISODate",(e,t)=>{tc.init(e,t),ve.init(e,t)});function Nu(e){return tu(ku,e)}const Su=I("ZodISOTime",(e,t)=>{nc.init(e,t),ve.init(e,t)});function Cu(e){return nu(Su,e)}const $u=I("ZodISODuration",(e,t)=>{sc.init(e,t),ve.init(e,t)});function Eu(e){return su($u,e)}const _u=(e,t)=>{Lr.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ho(e,n)},flatten:{value:n=>Yo(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},gn=I("ZodError",_u,{Parent:Error}),Au=Xo(gn),Ru=el(gn),Tu=Fr(gn),Ou=Ur(gn),ke=I("ZodType",(e,t)=>(je.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>it(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>Au(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Tu(e,n,r),e.parseAsync=async(n,r)=>Ru(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Ou(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(wd(n,r)),e.superRefine=n=>e.check(kd(n)),e.overwrite=n=>e.check(Pt(n)),e.optional=()=>Us(e),e.nullable=()=>Ds(e),e.nullish=()=>Us(Ds(e)),e.nonoptional=n=>md(e,n),e.array=()=>Je(e),e.or=n=>ss([e,n]),e.and=n=>ad(e,n),e.transform=n=>Zs(e,ld(n)),e.default=n=>dd(e,n),e.prefault=n=>hd(e,n),e.catch=n=>gd(e,n),e.pipe=n=>Zs(e,n),e.readonly=()=>yd(e),e.describe=n=>{const r=e.clone();return Ct.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Ct.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Ct.get(e);const r=e.clone();return Ct.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Xr=I("_ZodString",(e,t)=>{ns.init(e,t),ke.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(lu(...r)),e.includes=(...r)=>e.check(du(...r)),e.startsWith=(...r)=>e.check(pu(...r)),e.endsWith=(...r)=>e.check(hu(...r)),e.min=(...r)=>e.check(an(...r)),e.max=(...r)=>e.check(Yr(...r)),e.length=(...r)=>e.check(Hr(...r)),e.nonempty=(...r)=>e.check(an(1,...r)),e.lowercase=r=>e.check(cu(r)),e.uppercase=r=>e.check(uu(r)),e.trim=()=>e.check(fu()),e.normalize=(...r)=>e.check(mu(...r)),e.toLowerCase=()=>e.check(gu()),e.toUpperCase=()=>e.check(vu())}),Iu=I("ZodString",(e,t)=>{ns.init(e,t),Xr.init(e,t),e.email=n=>e.check(Oc(Pu,n)),e.url=n=>e.check(Mc(zu,n)),e.jwt=n=>e.check(Xc(Yu,n)),e.emoji=n=>e.check(Fc(Lu,n)),e.guid=n=>e.check(Ts(Ls,n)),e.uuid=n=>e.check(Ic(Dt,n)),e.uuidv4=n=>e.check(Pc(Dt,n)),e.uuidv6=n=>e.check(zc(Dt,n)),e.uuidv7=n=>e.check(Lc(Dt,n)),e.nanoid=n=>e.check(Uc(Mu,n)),e.guid=n=>e.check(Ts(Ls,n)),e.cuid=n=>e.check(Dc(Fu,n)),e.cuid2=n=>e.check(Zc(Uu,n)),e.ulid=n=>e.check(qc(Du,n)),e.base64=n=>e.check(Jc(Qu,n)),e.base64url=n=>e.check(Yc(Ku,n)),e.xid=n=>e.check(Gc(Zu,n)),e.ksuid=n=>e.check(Bc(qu,n)),e.ipv4=n=>e.check(Wc(Gu,n)),e.ipv6=n=>e.check(Vc(Bu,n)),e.cidrv4=n=>e.check(Qc(Wu,n)),e.cidrv6=n=>e.check(Kc(Vu,n)),e.e164=n=>e.check(Hc(Ju,n)),e.datetime=n=>e.check(wu(n)),e.date=n=>e.check(Nu(n)),e.time=n=>e.check(Cu(n)),e.duration=n=>e.check(Eu(n))});function K(e){return Tc(Iu,e)}const ve=I("ZodStringFormat",(e,t)=>{me.init(e,t),Xr.init(e,t)}),Pu=I("ZodEmail",(e,t)=>{Bl.init(e,t),ve.init(e,t)}),Ls=I("ZodGUID",(e,t)=>{ql.init(e,t),ve.init(e,t)}),Dt=I("ZodUUID",(e,t)=>{Gl.init(e,t),ve.init(e,t)}),zu=I("ZodURL",(e,t)=>{Wl.init(e,t),ve.init(e,t)}),Lu=I("ZodEmoji",(e,t)=>{Vl.init(e,t),ve.init(e,t)}),Mu=I("ZodNanoID",(e,t)=>{Ql.init(e,t),ve.init(e,t)}),Fu=I("ZodCUID",(e,t)=>{Kl.init(e,t),ve.init(e,t)}),Uu=I("ZodCUID2",(e,t)=>{Jl.init(e,t),ve.init(e,t)}),Du=I("ZodULID",(e,t)=>{Yl.init(e,t),ve.init(e,t)}),Zu=I("ZodXID",(e,t)=>{Hl.init(e,t),ve.init(e,t)}),qu=I("ZodKSUID",(e,t)=>{Xl.init(e,t),ve.init(e,t)}),Gu=I("ZodIPv4",(e,t)=>{rc.init(e,t),ve.init(e,t)}),Bu=I("ZodIPv6",(e,t)=>{ic.init(e,t),ve.init(e,t)}),Wu=I("ZodCIDRv4",(e,t)=>{ac.init(e,t),ve.init(e,t)}),Vu=I("ZodCIDRv6",(e,t)=>{oc.init(e,t),ve.init(e,t)}),Qu=I("ZodBase64",(e,t)=>{lc.init(e,t),ve.init(e,t)}),Ku=I("ZodBase64URL",(e,t)=>{uc.init(e,t),ve.init(e,t)}),Ju=I("ZodE164",(e,t)=>{dc.init(e,t),ve.init(e,t)}),Yu=I("ZodJWT",(e,t)=>{hc.init(e,t),ve.init(e,t)}),ei=I("ZodNumber",(e,t)=>{Qr.init(e,t),ke.init(e,t),e.gt=(r,i)=>e.check(Is(r,i)),e.gte=(r,i)=>e.check(Nn(r,i)),e.min=(r,i)=>e.check(Nn(r,i)),e.lt=(r,i)=>e.check(Os(r,i)),e.lte=(r,i)=>e.check(kn(r,i)),e.max=(r,i)=>e.check(kn(r,i)),e.int=r=>e.check(Ms(r)),e.safe=r=>e.check(Ms(r)),e.positive=r=>e.check(Is(0,r)),e.nonnegative=r=>e.check(Nn(0,r)),e.negative=r=>e.check(Os(0,r)),e.nonpositive=r=>e.check(kn(0,r)),e.multipleOf=(r,i)=>e.check(Ps(r,i)),e.step=(r,i)=>e.check(Ps(r,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Be(e){return ru(ei,e)}const Hu=I("ZodNumberFormat",(e,t)=>{mc.init(e,t),ei.init(e,t)});function Ms(e){return iu(Hu,e)}const Xu=I("ZodUnknown",(e,t)=>{fc.init(e,t),ke.init(e,t)});function Fs(){return au(Xu)}const ed=I("ZodNever",(e,t)=>{gc.init(e,t),ke.init(e,t)});function td(e){return ou(ed,e)}const nd=I("ZodArray",(e,t)=>{vc.init(e,t),ke.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(an(n,r)),e.nonempty=n=>e.check(an(1,n)),e.max=(n,r)=>e.check(Yr(n,r)),e.length=(n,r)=>e.check(Hr(n,r)),e.unwrap=()=>e.element});function Je(e,t){return bu(nd,e,t)}const sd=I("ZodObject",(e,t)=>{bc.init(e,t),ke.init(e,t),he(e,"shape",()=>t.shape),e.keyof=()=>vt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Fs()}),e.loose=()=>e.clone({...e._zod.def,catchall:Fs()}),e.strict=()=>e.clone({...e._zod.def,catchall:td()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Vo(e,n),e.merge=n=>Qo(e,n),e.pick=n=>Bo(e,n),e.omit=n=>Wo(e,n),e.partial=(...n)=>Ko(ti,e,n[0]),e.required=(...n)=>Jo(ni,e,n[0])});function pe(e,t){const n={type:"object",get shape(){return Xn(this,"shape",{...e}),this.shape},...Y(t)};return new sd(n)}const rd=I("ZodUnion",(e,t)=>{yc.init(e,t),ke.init(e,t),e.options=t.options});function ss(e,t){return new rd({type:"union",options:e,...Y(t)})}const id=I("ZodIntersection",(e,t)=>{xc.init(e,t),ke.init(e,t)});function ad(e,t){return new id({type:"intersection",left:e,right:t})}const Fn=I("ZodEnum",(e,t)=>{jc.init(e,t),ke.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const a={};for(const o of r)if(n.has(o))a[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Fn({...t,checks:[],...Y(i),entries:a})},e.exclude=(r,i)=>{const a={...t.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Fn({...t,checks:[],...Y(i),entries:a})}});function vt(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Fn({type:"enum",entries:n,...Y(t)})}const od=I("ZodTransform",(e,t)=>{wc.init(e,t),ke.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(Tt(a,n.value,t));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),n.issues.push(Tt(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(a=>(n.value=a,n)):(n.value=i,n)}});function ld(e){return new od({type:"transform",transform:e})}const ti=I("ZodOptional",(e,t)=>{kc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Us(e){return new ti({type:"optional",innerType:e})}const cd=I("ZodNullable",(e,t)=>{Nc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ds(e){return new cd({type:"nullable",innerType:e})}const ud=I("ZodDefault",(e,t)=>{Sc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function dd(e,t){return new ud({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const pd=I("ZodPrefault",(e,t)=>{Cc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hd(e,t){return new pd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ni=I("ZodNonOptional",(e,t)=>{$c.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function md(e,t){return new ni({type:"nonoptional",innerType:e,...Y(t)})}const fd=I("ZodCatch",(e,t)=>{Ec.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gd(e,t){return new fd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const vd=I("ZodPipe",(e,t)=>{_c.init(e,t),ke.init(e,t),e.in=t.in,e.out=t.out});function Zs(e,t){return new vd({type:"pipe",in:e,out:t})}const bd=I("ZodReadonly",(e,t)=>{Ac.init(e,t),ke.init(e,t)});function yd(e){return new bd({type:"readonly",innerType:e})}const xd=I("ZodCustom",(e,t)=>{Rc.init(e,t),ke.init(e,t)});function jd(e){const t=new Re({check:"custom"});return t._zod.check=e,t}function wd(e,t={}){return yu(xd,e,t)}function kd(e){const t=jd(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Tt(r,n.value,t._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Tt(i))}},e(n.value,n)));return t}function Sn(e,t){if(!t||e==null)return;if(!t.includes("."))return e[t];let n=e;for(const r of t.split(".")){if(n==null)return;n=n[r]}return n}function ee(e){if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);return isNaN(t)?0:t}return typeof e=="boolean"&&e?1:0}const rs={Count:{name:"Count",signature:"Count(array) → number",description:"Returns array length",fn:e=>Array.isArray(e)?e.length:0},First:{name:"First",signature:"First(array) → element",description:"Returns first element of array",fn:e=>Array.isArray(e)?e[0]??null:null},Last:{name:"Last",signature:"Last(array) → element",description:"Returns last element of array",fn:e=>Array.isArray(e)?e[e.length-1]??null:null},Sum:{name:"Sum",signature:"Sum(numbers[]) → number",description:"Sum of numeric array",fn:e=>Array.isArray(e)?e.reduce((t,n)=>t+ee(n),0):0},Avg:{name:"Avg",signature:"Avg(numbers[]) → number",description:"Average of numeric array",fn:e=>Array.isArray(e)&&e.length?e.reduce((t,n)=>t+ee(n),0)/e.length:0},Min:{name:"Min",signature:"Min(numbers[]) → number",description:"Minimum value in array",fn:e=>Array.isArray(e)&&e.length?e.reduce((t,n)=>Math.min(t,ee(n)),ee(e[0])):0},Max:{name:"Max",signature:"Max(numbers[]) → number",description:"Maximum value in array",fn:e=>Array.isArray(e)&&e.length?e.reduce((t,n)=>Math.max(t,ee(n)),ee(e[0])):0},Sort:{name:"Sort",signature:"Sort(array, field, direction?) → sorted array",description:'Sort array by field. Direction: "asc" (default) or "desc"',fn:(e,t,n)=>{if(!Array.isArray(e))return e;const r=String(t??""),i=String(n??"asc")==="desc";return[...e].sort((a,o)=>{const l=r?Sn(a,r):a,c=r?Sn(o,r):o,d=typeof l=="number"||typeof l=="string"&&!isNaN(Number(l))&&l!=="",g=typeof c=="number"||typeof c=="string"&&!isNaN(Number(c))&&c!=="";if(d&&g){const u=ee(l)-ee(c);return i?-u:u}const h=String(l??"").localeCompare(String(c??""));return i?-h:h})}},Filter:{name:"Filter",signature:'Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array',description:"Filter array by field value",fn:(e,t,n,r)=>{if(!Array.isArray(e))return[];const i=String(t??""),a=String(n??"==");return e.filter(o=>{const l=i?Sn(o,i):o;switch(a){case"==":return l==r;case"!=":return l!=r;case">":return ee(l)>ee(r);case"<":return ee(l)<ee(r);case">=":return ee(l)>=ee(r);case"<=":return ee(l)<=ee(r);case"contains":return String(l??"").includes(String(r??""));default:return!1}})}},Round:{name:"Round",signature:"Round(number, decimals?) → number",description:"Round to N decimal places (default 0)",fn:(e,t)=>{const n=ee(e),r=t!=null?ee(t):0,i=Math.pow(10,r);return Math.round(n*i)/i}},Abs:{name:"Abs",signature:"Abs(number) → number",description:"Absolute value",fn:e=>Math.abs(ee(e))},Floor:{name:"Floor",signature:"Floor(number) → number",description:"Round down to nearest integer",fn:e=>Math.floor(ee(e))},Ceil:{name:"Ceil",signature:"Ceil(number) → number",description:"Round up to nearest integer",fn:e=>Math.ceil(ee(e))}},is=new Set(["Each"]),Nd={Each:{signature:"Each(array, varName, template)",description:"Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template."}},Ue={Run:"run",ToAssistant:"continue_conversation",OpenUrl:"open_url",Set:"set",Reset:"reset"},si=new Set(["Action",...Object.keys(Ue)]),Sd=new Set([...Object.keys(rs),...is,...si]);function Ot(e){return Sd.has(e)}const He={Query:"Query",Mutation:"Mutation"};function on(e){return e in He}function ln(e){const t=e.type;if(t==="string"){const n=e.enum;return n?n.map(r=>`"${r}"`).join(" | "):"string"}if(t==="number"||t==="integer")return"number";if(t==="boolean")return"boolean";if(t==="array"){const n=e.items;return n?`${ln(n)}[]`:"any[]"}if(t==="object"){const n=e.properties;if(n&&Object.keys(n).length>0){const r=e.required??[];return`{${Object.entries(n).map(([i,a])=>`${i}${r.includes(i)?"":"?"}: ${ln(a)}`).join(", ")}}`}return"object"}return"any"}function ri(e){const t=e.type;if(t==="string")return"";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(t==="array")return[];if(t==="object"){const n=e.properties;if(n&&Object.keys(n).length>0){const r={};for(const[i,a]of Object.entries(n))r[i]=ri(a);return r}return{}}return null}const Cd="You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.";function $d(e,t){const n=["## Syntax Rules","","1. Each statement is on its own line: `identifier = Expression`",`2. \`root\` is the entry point — every program must define \`root = ${e}(...)\``,'3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)',"4. Use references for readability: define `name = ...` on one line, then use `name` later","5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.",'6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks',"7. Optional arguments can be omitted from the end"];let r=8;return t.bindings&&n.push(`${r++}. Declare mutable state with \`$varName = defaultValue\`. Components marked with \`$binding\` can read/write these. Undeclared $variables are auto-created with null default.`),t.supportsExpressions&&n.push(`${r++}. String concatenation: \`"text" + $var + "more"\``,`${r++}. Dot member access: \`query.field\` reads a field; on arrays it extracts that field from every element`,`${r++}. Index access: \`arr[0]\`, \`data[index]\``,`${r++}. Arithmetic operators: +, -, *, /, % (work on numbers; + is string concat when either side is a string)`,`${r++}. Comparison: ==, !=, >, <, >=, <=`,`${r++}. Logical: &&, ||, ! (prefix)`,`${r++}. Ternary: \`condition ? valueIfTrue : valueIfFalse\``,`${r++}. Parentheses for grouping: \`(a + b) * c\``),n.push("- Strings use double quotes with backslash escaping"),n.join(`
87
- `)}function Ed(){const e=Object.values(rs).map(n=>`@${n.signature} — ${n.description}`),t=Object.values(Nd).map(n=>`@${n.signature} — ${n.description}`);return`## Built-in Functions
86
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const w of this.seen.entries()){const m=w[1];if(t===w[0]){o(w);continue}if(r.external){const x=(h=r.external.registry.get(w[0]))==null?void 0:h.id;if(t!==w[0]&&x){o(w);continue}}if((u=this.metadataRegistry.get(w[0]))==null?void 0:u.id){o(w);continue}if(m.cycle){o(w);continue}if(m.count>1&&r.reused==="ref"){o(w);continue}}const l=(w,m)=>{const b=this.seen.get(w),x=b.def??b.schema,k={...x};if(b.ref===null)return;const N=b.ref;if(b.ref=null,N){l(N,m);const j=this.seen.get(N).schema;j.$ref&&m.target==="draft-7"?(x.allOf=x.allOf??[],x.allOf.push(j)):(Object.assign(x,j),Object.assign(x,k))}b.isParent||this.override({zodSchema:w,jsonSchema:x,path:b.path??[]})};for(const w of[...this.seen.entries()].reverse())l(w[0],{target:this.target});const c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(p=r.external)!=null&&p.uri){const w=(v=r.external.registry.get(t))==null?void 0:v.id;if(!w)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(w)}Object.assign(c,i.def);const d=((y=r.external)==null?void 0:y.defs)??{};for(const w of this.seen.entries()){const m=w[1];m.def&&m.defId&&(d[m.defId]=m.def)}r.external||Object.keys(d).length>0&&(this.target==="draft-2020-12"?c.$defs=d:c.definitions=d);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}function ju(e,t){if(e instanceof Jr){const r=new zs(t),i={};for(const l of e._idmap.entries()){const[c,d]=l;r.process(d)}const a={},o={registry:e,uri:t==null?void 0:t.uri,defs:i};for(const l of e._idmap.entries()){const[c,d]=l;a[c]=r.emit(d,{...t,external:o})}if(Object.keys(i).length>0){const l=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[l]:i}}return{schemas:a}}const n=new zs(t);return n.process(e),n.emit(e,t)}function we(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return we(i.element,n);case"object":{for(const a in i.shape)if(we(i.shape[a],n))return!0;return!1}case"union":{for(const a of i.options)if(we(a,n))return!0;return!1}case"intersection":return we(i.left,n)||we(i.right,n);case"tuple":{for(const a of i.items)if(we(a,n))return!0;return!!(i.rest&&we(i.rest,n))}case"record":return we(i.keyType,n)||we(i.valueType,n);case"map":return we(i.keyType,n)||we(i.valueType,n);case"set":return we(i.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return we(i.innerType,n);case"lazy":return we(i.getter(),n);case"default":return we(i.innerType,n);case"prefault":return we(i.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return we(i.in,n)||we(i.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${i.type}`)}const wu=I("ZodISODateTime",(e,t)=>{tc.init(e,t),ve.init(e,t)});function ku(e){return tu(wu,e)}const Nu=I("ZodISODate",(e,t)=>{nc.init(e,t),ve.init(e,t)});function Su(e){return nu(Nu,e)}const Cu=I("ZodISOTime",(e,t)=>{sc.init(e,t),ve.init(e,t)});function $u(e){return su(Cu,e)}const Eu=I("ZodISODuration",(e,t)=>{rc.init(e,t),ve.init(e,t)});function _u(e){return ru(Eu,e)}const Au=(e,t)=>{Mr.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Xo(e,n)},flatten:{value:n=>Yo(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},gn=I("ZodError",Au,{Parent:Error}),Tu=el(gn),Ru=tl(gn),Ou=Ur(gn),Iu=Dr(gn),ke=I("ZodType",(e,t)=>(je.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>it(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>Tu(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Ou(e,n,r),e.parseAsync=async(n,r)=>Ru(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Iu(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(kd(n,r)),e.superRefine=n=>e.check(Nd(n)),e.overwrite=n=>e.check(Pt(n)),e.optional=()=>Us(e),e.nullable=()=>Ds(e),e.nullish=()=>Us(Ds(e)),e.nonoptional=n=>fd(e,n),e.array=()=>Je(e),e.or=n=>ss([e,n]),e.and=n=>od(e,n),e.transform=n=>Zs(e,cd(n)),e.default=n=>pd(e,n),e.prefault=n=>md(e,n),e.catch=n=>vd(e,n),e.pipe=n=>Zs(e,n),e.readonly=()=>xd(e),e.describe=n=>{const r=e.clone();return Ct.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Ct.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Ct.get(e);const r=e.clone();return Ct.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ei=I("_ZodString",(e,t)=>{ns.init(e,t),ke.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(cu(...r)),e.includes=(...r)=>e.check(pu(...r)),e.startsWith=(...r)=>e.check(hu(...r)),e.endsWith=(...r)=>e.check(mu(...r)),e.min=(...r)=>e.check(an(...r)),e.max=(...r)=>e.check(Yr(...r)),e.length=(...r)=>e.check(Xr(...r)),e.nonempty=(...r)=>e.check(an(1,...r)),e.lowercase=r=>e.check(uu(r)),e.uppercase=r=>e.check(du(r)),e.trim=()=>e.check(gu()),e.normalize=(...r)=>e.check(fu(...r)),e.toLowerCase=()=>e.check(vu()),e.toUpperCase=()=>e.check(bu())}),Pu=I("ZodString",(e,t)=>{ns.init(e,t),ei.init(e,t),e.email=n=>e.check(Ic(zu,n)),e.url=n=>e.check(Fc(Lu,n)),e.jwt=n=>e.check(eu(Yu,n)),e.emoji=n=>e.check(Uc(Mu,n)),e.guid=n=>e.check(Rs(Ls,n)),e.uuid=n=>e.check(Pc(Dt,n)),e.uuidv4=n=>e.check(zc(Dt,n)),e.uuidv6=n=>e.check(Lc(Dt,n)),e.uuidv7=n=>e.check(Mc(Dt,n)),e.nanoid=n=>e.check(Dc(Fu,n)),e.guid=n=>e.check(Rs(Ls,n)),e.cuid=n=>e.check(Zc(Uu,n)),e.cuid2=n=>e.check(qc(Du,n)),e.ulid=n=>e.check(Gc(Zu,n)),e.base64=n=>e.check(Hc(Ku,n)),e.base64url=n=>e.check(Yc(Ju,n)),e.xid=n=>e.check(Bc(qu,n)),e.ksuid=n=>e.check(Wc(Gu,n)),e.ipv4=n=>e.check(Vc(Bu,n)),e.ipv6=n=>e.check(Qc(Wu,n)),e.cidrv4=n=>e.check(Kc(Vu,n)),e.cidrv6=n=>e.check(Jc(Qu,n)),e.e164=n=>e.check(Xc(Hu,n)),e.datetime=n=>e.check(ku(n)),e.date=n=>e.check(Su(n)),e.time=n=>e.check($u(n)),e.duration=n=>e.check(_u(n))});function K(e){return Oc(Pu,e)}const ve=I("ZodStringFormat",(e,t)=>{me.init(e,t),ei.init(e,t)}),zu=I("ZodEmail",(e,t)=>{Wl.init(e,t),ve.init(e,t)}),Ls=I("ZodGUID",(e,t)=>{Gl.init(e,t),ve.init(e,t)}),Dt=I("ZodUUID",(e,t)=>{Bl.init(e,t),ve.init(e,t)}),Lu=I("ZodURL",(e,t)=>{Vl.init(e,t),ve.init(e,t)}),Mu=I("ZodEmoji",(e,t)=>{Ql.init(e,t),ve.init(e,t)}),Fu=I("ZodNanoID",(e,t)=>{Kl.init(e,t),ve.init(e,t)}),Uu=I("ZodCUID",(e,t)=>{Jl.init(e,t),ve.init(e,t)}),Du=I("ZodCUID2",(e,t)=>{Hl.init(e,t),ve.init(e,t)}),Zu=I("ZodULID",(e,t)=>{Yl.init(e,t),ve.init(e,t)}),qu=I("ZodXID",(e,t)=>{Xl.init(e,t),ve.init(e,t)}),Gu=I("ZodKSUID",(e,t)=>{ec.init(e,t),ve.init(e,t)}),Bu=I("ZodIPv4",(e,t)=>{ic.init(e,t),ve.init(e,t)}),Wu=I("ZodIPv6",(e,t)=>{ac.init(e,t),ve.init(e,t)}),Vu=I("ZodCIDRv4",(e,t)=>{oc.init(e,t),ve.init(e,t)}),Qu=I("ZodCIDRv6",(e,t)=>{lc.init(e,t),ve.init(e,t)}),Ku=I("ZodBase64",(e,t)=>{cc.init(e,t),ve.init(e,t)}),Ju=I("ZodBase64URL",(e,t)=>{dc.init(e,t),ve.init(e,t)}),Hu=I("ZodE164",(e,t)=>{pc.init(e,t),ve.init(e,t)}),Yu=I("ZodJWT",(e,t)=>{mc.init(e,t),ve.init(e,t)}),ti=I("ZodNumber",(e,t)=>{Kr.init(e,t),ke.init(e,t),e.gt=(r,i)=>e.check(Is(r,i)),e.gte=(r,i)=>e.check(Nn(r,i)),e.min=(r,i)=>e.check(Nn(r,i)),e.lt=(r,i)=>e.check(Os(r,i)),e.lte=(r,i)=>e.check(kn(r,i)),e.max=(r,i)=>e.check(kn(r,i)),e.int=r=>e.check(Ms(r)),e.safe=r=>e.check(Ms(r)),e.positive=r=>e.check(Is(0,r)),e.nonnegative=r=>e.check(Nn(0,r)),e.negative=r=>e.check(Os(0,r)),e.nonpositive=r=>e.check(kn(0,r)),e.multipleOf=(r,i)=>e.check(Ps(r,i)),e.step=(r,i)=>e.check(Ps(r,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Be(e){return iu(ti,e)}const Xu=I("ZodNumberFormat",(e,t)=>{fc.init(e,t),ti.init(e,t)});function Ms(e){return au(Xu,e)}const ed=I("ZodUnknown",(e,t)=>{gc.init(e,t),ke.init(e,t)});function Fs(){return ou(ed)}const td=I("ZodNever",(e,t)=>{vc.init(e,t),ke.init(e,t)});function nd(e){return lu(td,e)}const sd=I("ZodArray",(e,t)=>{bc.init(e,t),ke.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(an(n,r)),e.nonempty=n=>e.check(an(1,n)),e.max=(n,r)=>e.check(Yr(n,r)),e.length=(n,r)=>e.check(Xr(n,r)),e.unwrap=()=>e.element});function Je(e,t){return yu(sd,e,t)}const rd=I("ZodObject",(e,t)=>{yc.init(e,t),ke.init(e,t),he(e,"shape",()=>t.shape),e.keyof=()=>vt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Fs()}),e.loose=()=>e.clone({...e._zod.def,catchall:Fs()}),e.strict=()=>e.clone({...e._zod.def,catchall:nd()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Qo(e,n),e.merge=n=>Ko(e,n),e.pick=n=>Wo(e,n),e.omit=n=>Vo(e,n),e.partial=(...n)=>Jo(ni,e,n[0]),e.required=(...n)=>Ho(si,e,n[0])});function pe(e,t){const n={type:"object",get shape(){return Xn(this,"shape",{...e}),this.shape},...H(t)};return new rd(n)}const id=I("ZodUnion",(e,t)=>{xc.init(e,t),ke.init(e,t),e.options=t.options});function ss(e,t){return new id({type:"union",options:e,...H(t)})}const ad=I("ZodIntersection",(e,t)=>{jc.init(e,t),ke.init(e,t)});function od(e,t){return new ad({type:"intersection",left:e,right:t})}const Fn=I("ZodEnum",(e,t)=>{wc.init(e,t),ke.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const a={};for(const o of r)if(n.has(o))a[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Fn({...t,checks:[],...H(i),entries:a})},e.exclude=(r,i)=>{const a={...t.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Fn({...t,checks:[],...H(i),entries:a})}});function vt(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Fn({type:"enum",entries:n,...H(t)})}const ld=I("ZodTransform",(e,t)=>{kc.init(e,t),ke.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(Rt(a,n.value,t));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),n.issues.push(Rt(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(a=>(n.value=a,n)):(n.value=i,n)}});function cd(e){return new ld({type:"transform",transform:e})}const ni=I("ZodOptional",(e,t)=>{Nc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Us(e){return new ni({type:"optional",innerType:e})}const ud=I("ZodNullable",(e,t)=>{Sc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ds(e){return new ud({type:"nullable",innerType:e})}const dd=I("ZodDefault",(e,t)=>{Cc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function pd(e,t){return new dd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const hd=I("ZodPrefault",(e,t)=>{$c.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function md(e,t){return new hd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const si=I("ZodNonOptional",(e,t)=>{Ec.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fd(e,t){return new si({type:"nonoptional",innerType:e,...H(t)})}const gd=I("ZodCatch",(e,t)=>{_c.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vd(e,t){return new gd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const bd=I("ZodPipe",(e,t)=>{Ac.init(e,t),ke.init(e,t),e.in=t.in,e.out=t.out});function Zs(e,t){return new bd({type:"pipe",in:e,out:t})}const yd=I("ZodReadonly",(e,t)=>{Tc.init(e,t),ke.init(e,t)});function xd(e){return new yd({type:"readonly",innerType:e})}const jd=I("ZodCustom",(e,t)=>{Rc.init(e,t),ke.init(e,t)});function wd(e){const t=new Te({check:"custom"});return t._zod.check=e,t}function kd(e,t={}){return xu(jd,e,t)}function Nd(e){const t=wd(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Rt(r,n.value,t._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Rt(i))}},e(n.value,n)));return t}function Sn(e,t){if(!t||e==null)return;if(!t.includes("."))return e[t];let n=e;for(const r of t.split(".")){if(n==null)return;n=n[r]}return n}function ee(e){if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);return isNaN(t)?0:t}return typeof e=="boolean"&&e?1:0}const rs={Count:{name:"Count",signature:"Count(array) → number",description:"Returns array length",fn:e=>Array.isArray(e)?e.length:0},First:{name:"First",signature:"First(array) → element",description:"Returns first element of array",fn:e=>Array.isArray(e)?e[0]??null:null},Last:{name:"Last",signature:"Last(array) → element",description:"Returns last element of array",fn:e=>Array.isArray(e)?e[e.length-1]??null:null},Sum:{name:"Sum",signature:"Sum(numbers[]) → number",description:"Sum of numeric array",fn:e=>Array.isArray(e)?e.reduce((t,n)=>t+ee(n),0):0},Avg:{name:"Avg",signature:"Avg(numbers[]) → number",description:"Average of numeric array",fn:e=>Array.isArray(e)&&e.length?e.reduce((t,n)=>t+ee(n),0)/e.length:0},Min:{name:"Min",signature:"Min(numbers[]) → number",description:"Minimum value in array",fn:e=>Array.isArray(e)&&e.length?e.reduce((t,n)=>Math.min(t,ee(n)),ee(e[0])):0},Max:{name:"Max",signature:"Max(numbers[]) → number",description:"Maximum value in array",fn:e=>Array.isArray(e)&&e.length?e.reduce((t,n)=>Math.max(t,ee(n)),ee(e[0])):0},Sort:{name:"Sort",signature:"Sort(array, field, direction?) → sorted array",description:'Sort array by field. Direction: "asc" (default) or "desc"',fn:(e,t,n)=>{if(!Array.isArray(e))return e;const r=String(t??""),i=String(n??"asc")==="desc";return[...e].sort((a,o)=>{const l=r?Sn(a,r):a,c=r?Sn(o,r):o,d=typeof l=="number"||typeof l=="string"&&!isNaN(Number(l))&&l!=="",g=typeof c=="number"||typeof c=="string"&&!isNaN(Number(c))&&c!=="";if(d&&g){const u=ee(l)-ee(c);return i?-u:u}const h=String(l??"").localeCompare(String(c??""));return i?-h:h})}},Filter:{name:"Filter",signature:'Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array',description:"Filter array by field value",fn:(e,t,n,r)=>{if(!Array.isArray(e))return[];const i=String(t??""),a=String(n??"==");return e.filter(o=>{const l=i?Sn(o,i):o;switch(a){case"==":return l==r;case"!=":return l!=r;case">":return ee(l)>ee(r);case"<":return ee(l)<ee(r);case">=":return ee(l)>=ee(r);case"<=":return ee(l)<=ee(r);case"contains":return String(l??"").includes(String(r??""));default:return!1}})}},Round:{name:"Round",signature:"Round(number, decimals?) → number",description:"Round to N decimal places (default 0)",fn:(e,t)=>{const n=ee(e),r=t!=null?ee(t):0,i=Math.pow(10,r);return Math.round(n*i)/i}},Abs:{name:"Abs",signature:"Abs(number) → number",description:"Absolute value",fn:e=>Math.abs(ee(e))},Floor:{name:"Floor",signature:"Floor(number) → number",description:"Round down to nearest integer",fn:e=>Math.floor(ee(e))},Ceil:{name:"Ceil",signature:"Ceil(number) → number",description:"Round up to nearest integer",fn:e=>Math.ceil(ee(e))}},is=new Set(["Each"]),Sd={Each:{signature:"Each(array, varName, template)",description:"Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template."}},Ue={Run:"run",ToAssistant:"continue_conversation",OpenUrl:"open_url",Set:"set",Reset:"reset"},ri=new Set(["Action",...Object.keys(Ue)]),Cd=new Set([...Object.keys(rs),...is,...ri]);function Ot(e){return Cd.has(e)}const Ye={Query:"Query",Mutation:"Mutation"};function on(e){return e in Ye}function ln(e){const t=e.type;if(t==="string"){const n=e.enum;return n?n.map(r=>`"${r}"`).join(" | "):"string"}if(t==="number"||t==="integer")return"number";if(t==="boolean")return"boolean";if(t==="array"){const n=e.items;return n?`${ln(n)}[]`:"any[]"}if(t==="object"){const n=e.properties;if(n&&Object.keys(n).length>0){const r=e.required??[];return`{${Object.entries(n).map(([i,a])=>`${i}${r.includes(i)?"":"?"}: ${ln(a)}`).join(", ")}}`}return"object"}return"any"}function ii(e){const t=e.type;if(t==="string")return"";if(t==="number"||t==="integer")return 0;if(t==="boolean")return!1;if(t==="array")return[];if(t==="object"){const n=e.properties;if(n&&Object.keys(n).length>0){const r={};for(const[i,a]of Object.entries(n))r[i]=ii(a);return r}return{}}return null}const $d="You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.";function Ed(e,t){const n=["## Syntax Rules","","1. Each statement is on its own line: `identifier = Expression`",`2. \`root\` is the entry point — every program must define \`root = ${e}(...)\``,'3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)',"4. Use references for readability: define `name = ...` on one line, then use `name` later","5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.",'6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks',"7. Optional arguments can be omitted from the end"];let r=8;return t.bindings&&n.push(`${r++}. Declare mutable state with \`$varName = defaultValue\`. Components marked with \`$binding\` can read/write these. Undeclared $variables are auto-created with null default.`),t.supportsExpressions&&n.push(`${r++}. String concatenation: \`"text" + $var + "more"\``,`${r++}. Dot member access: \`query.field\` reads a field; on arrays it extracts that field from every element`,`${r++}. Index access: \`arr[0]\`, \`data[index]\``,`${r++}. Arithmetic operators: +, -, *, /, % (work on numbers; + is string concat when either side is a string)`,`${r++}. Comparison: ==, !=, >, <, >=, <=`,`${r++}. Logical: &&, ||, ! (prefix)`,`${r++}. Ternary: \`condition ? valueIfTrue : valueIfFalse\``,`${r++}. Parentheses for grouping: \`(a + b) * c\``),n.push("- Strings use double quotes with backslash escaping"),n.join(`
87
+ `)}function _d(){const e=Object.values(rs).map(n=>`@${n.signature} — ${n.description}`),t=Object.values(Sd).map(n=>`@${n.signature} — ${n.description}`);return`## Built-in Functions
88
88
 
89
89
  Data functions prefixed with \`@\` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.
90
90
  Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.
@@ -98,7 +98,7 @@ Array pluck: \`data.rows.field\` extracts a field from every row → use with @S
98
98
 
99
99
  IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.
100
100
  CORRECT: \`Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))\`
101
- WRONG: \`myBtn = Button("Edit", Action([@Set($id, t.id)]))\` then \`Col("Actions", @Each(rows, "t", myBtn))\` — t is undefined in myBtn.`}function _d(){return`## Query — Live Data Fetching
101
+ WRONG: \`myBtn = Button("Edit", Action([@Set($id, t.id)]))\` then \`Col("Actions", @Each(rows, "t", myBtn))\` — t is undefined in myBtn.`}function Ad(){return`## Query — Live Data Fetching
102
102
 
103
103
  Fetch data from available tools. Returns defaults instantly, swaps in real data when it arrives.
104
104
 
@@ -113,7 +113,7 @@ metrics = Query("tool_name", {arg1: value, arg2: $binding}, {defaultField: 0, de
113
113
  - Use dot access on results: metrics.totalEvents, metrics.data.day (array pluck)
114
114
  - Query results must use regular identifiers: \`metrics = Query(...)\`, NOT \`$metrics = Query(...)\`
115
115
  - Manual refresh: \`Button("Refresh", Action([@Run(query1), @Run(query2)]), "secondary")\` — re-fetches the listed queries
116
- - Refresh all queries: create Action with @Run for each query`}function Ad(){return`## Mutation — Write Operations
116
+ - Refresh all queries: create Action with @Run for each query`}function Td(){return`## Mutation — Write Operations
117
117
 
118
118
  Execute state-changing tool calls (create, update, delete). Unlike Query (auto-fetches on render), Mutation fires only on button click via Action.
119
119
 
@@ -141,7 +141,7 @@ ${n.join(`
141
141
  `)}
142
142
 
143
143
  ${r.join(`
144
- `)}`}function Td(){return`## Interactive Filters
144
+ `)}`}function Od(){return`## Interactive Filters
145
145
 
146
146
  To let the user filter data with a dropdown:
147
147
  1. Declare a $variable with a default: \`$dateRange = "14"\`
@@ -180,7 +180,7 @@ submitBtn = Button("Submit")
180
180
 
181
181
  For form + mutation patterns (create, refresh, reset), see the Action section example above.
182
182
 
183
- IMPORTANT: Always add validation rules to form fields used with Mutations. Use OBJECT syntax: {required: true, email: true, minLength: 8}. The renderer shows error messages automatically and blocks submit when validation fails.`}function Od(){return`## Edit Mode
183
+ IMPORTANT: Always add validation rules to form fields used with Mutations. Use OBJECT syntax: {required: true, email: true, minLength: 8}. The renderer shows error messages automatically and blocks submit when validation fails.`}function Id(){return`## Edit Mode
184
184
 
185
185
  The runtime merges by statement name: same name = replace, new name = append.
186
186
  Output ONLY statements that changed or are new. Everything else is kept automatically.
@@ -202,7 +202,7 @@ Example — remove chart: \`root = Stack([header, kpiRow, table])\` — chart is
202
202
  - A typical edit patch is 1-10 statements, not 20+
203
203
  - If the existing code already satisfies the request, output only the root statement
204
204
  - NEVER output the entire program as a patch. Only output what actually changes
205
- - If you are about to output more than 10 statements, reconsider — most edits need fewer`}function Id(e,t){const n=[`1. \`root = ${e}(...)\` — UI shell appears immediately`];return t.supportsExpressions?(n.push("2. $variable declarations — state ready for bindings"),n.push("3. Query statements — defaults resolve immediately so components render with data"),n.push("4. Component definitions — fill in with data already available"),n.push("5. Data values — leaf content last")):(n.push("2. Component definitions — fill in as they stream"),n.push("3. Data values — leaf content last")),`## Hoisting & Streaming (CRITICAL)
205
+ - If you are about to output more than 10 statements, reconsider — most edits need fewer`}function Pd(e,t){const n=[`1. \`root = ${e}(...)\` — UI shell appears immediately`];return t.supportsExpressions?(n.push("2. $variable declarations — state ready for bindings"),n.push("3. Query statements — defaults resolve immediately so components render with data"),n.push("4. Component definitions — fill in with data already available"),n.push("5. Data values — leaf content last")):(n.push("2. Component definitions — fill in as they stream"),n.push("3. Data values — leaf content last")),`## Hoisting & Streaming (CRITICAL)
206
206
 
207
207
  openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.
208
208
 
@@ -212,7 +212,7 @@ During streaming, the output is re-parsed on every chunk. Undefined references a
212
212
  ${n.join(`
213
213
  `)}
214
214
 
215
- Always write the root = ${e}(...) statement first so the UI shell appears immediately, even before child data has streamed in.`}function Pd(){return`## Inline Mode
215
+ Always write the root = ${e}(...) statement first so the UI shell appears immediately, even before child data has streamed in.`}function zd(){return`## Inline Mode
216
216
 
217
217
  You are in inline mode. You can respond in two ways:
218
218
 
@@ -235,7 +235,7 @@ If the user asks "what is this?", "explain the chart", "how does this work", etc
235
235
  ### Rules
236
236
  - When the user asks for changes, output ONLY the changed/new statements in a fenced block
237
237
  - When the user asks a question, respond with text only — NO code. The dashboard stays unchanged.
238
- - The parser extracts code from fences automatically. Text outside fences is shown as chat.`}function zd(){return`## Data Workflow
238
+ - The parser extracts code from fences automatically. Text outside fences is shown as chat.`}function Ld(){return`## Data Workflow
239
239
 
240
240
  When tools are available, follow this workflow:
241
241
  1. FIRST: Call the most relevant tool to inspect the real data shape before generating code
@@ -263,28 +263,28 @@ list = @Each(data.rows, "item", SomeComp(item.title, item.field))
263
263
  createResult = Mutation("create_tool", {title: $title})
264
264
  submitBtn = Button("Create", Action([@Run(createResult), @Run(data), @Reset($title)]))
265
265
  \`\`\`
266
- Everything derives from the Query — when data refreshes, the entire dashboard updates automatically.`}function Ld(e,t){const n=[`1. root = ${e}(...) is the FIRST line (for optimal streaming).`,"2. Every referenced name is defined. Every defined name (other than root) is reachable from root."];return t.toolCalls&&n.push("3. Every Query result is referenced by at least one component."),t.bindings&&n.push(`${t.toolCalls?"4":"3"}. Every $binding appears in at least one component or expression.`),`## Important Rules
266
+ Everything derives from the Query — when data refreshes, the entire dashboard updates automatically.`}function Md(e,t){const n=[`1. root = ${e}(...) is the FIRST line (for optimal streaming).`,"2. Every referenced name is defined. Every defined name (other than root) is reachable from root."];return t.toolCalls&&n.push("3. Every Query result is referenced by at least one component."),t.bindings&&n.push(`${t.toolCalls?"4":"3"}. Every $binding appears in at least one component or expression.`),`## Important Rules
267
267
  - When asked about data, generate realistic/plausible data
268
268
  - Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)
269
269
 
270
270
  ## Final Verification
271
271
  Before finishing, walk your output and verify:
272
272
  ${n.join(`
273
- `)}`}function Md(e){let t="";if(e.inputSchema){const i=e.inputSchema.properties,a=e.inputSchema.required??[];i&&Object.keys(i).length>0&&(t=Object.entries(i).map(([o,l])=>`${o}${a.includes(o)?"":"?"}: ${ln(l)}`).join(", "))}let n="";e.outputSchema&&(n=` → ${ln(e.outputSchema)}`);let r=`- ${e.name}(${t})${n}`;return e.description&&(r+=`
274
- ${e.description}`),r}function Fd(e){const t=[],n=[],r=[];for(const a of e)typeof a=="string"?n.push(a):r.push(a);t.push("## Available Tools"),t.push(""),t.push("Use these with Query() for read operations or Mutation() for write operations. The LLM decides which is appropriate based on the tool's purpose."),t.push("");for(const a of n)t.push(`- ${a}`);for(const a of r)t.push(Md(a));const i=r.filter(a=>a.outputSchema);if(i.length>0){t.push(""),t.push("### Default values for Query results"),t.push(""),t.push("Use these shapes as minimal Query defaults:");for(const a of i){const o=ri(a.outputSchema);t.push(`- ${a.name}: \`${JSON.stringify(o)}\``)}}return t.push(""),t.push("CRITICAL: Use ONLY the tools listed above in Query() and Mutation() calls. Do NOT invent or guess tool names. If the user asks for functionality that doesn't match any available tool, use realistic mock data instead of fabricating a tool call."),t.join(`
275
- `)}function Ud(e,t){var i,a;const n=["## Component Signatures","","Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming."];if(t.usesActionExpression){const o=[t.toolCalls?"@Run":"","@ToAssistant","@OpenUrl",t.bindings?"@Set":"",t.bindings?"@Reset":""].filter(Boolean);n.push(`Props typed \`ActionExpression\` accept an Action([@steps...]) expression. See the Action section for available steps (${o.join(", ")}).`)}(t.bindings||Object.values(e.components).some(o=>{var l;return(l=o.signature)==null?void 0:l.includes("$binding")}))&&n.push("Props marked `$binding<type>` accept a `$variable` reference for two-way binding.");const r=o=>o.description?`${o.signature} — ${o.description}`:o.signature;if((i=e.componentGroups)!=null&&i.length){const o=new Set;for(const c of e.componentGroups){n.push("",`### ${c.name}`);for(const d of c.components){if(o.has(d))continue;const g=e.components[d];g&&(o.add(d),n.push(r(g)))}if((a=c.notes)!=null&&a.length)for(const d of c.notes)n.push(d)}const l=Object.keys(e.components).filter(c=>!o.has(c));if(l.length){n.push("","### Other");for(const c of l){const d=e.components[c];n.push(r(d))}}}else{n.push("");for(const[,o]of Object.entries(e.components))n.push(r(o))}return n.join(`
276
- `)}function Dd(e){var d,g,h;const t=e.root??"Root",n=!!((d=e.tools)!=null&&d.length),r=e.toolCalls??n,i=e.bindings??r,a=r||i,o=Object.values(e.components).some(u=>{var p;return(p=u.signature)==null?void 0:p.includes("ActionExpression")}),l=[];l.push(e.preamble??Cd),l.push(""),l.push($d(t,{supportsExpressions:a,bindings:i})),l.push(""),l.push(Ud(e,{toolCalls:r,bindings:i,usesActionExpression:o})),a&&(l.push(""),l.push(Ed())),r&&(l.push(""),l.push(_d()),l.push(""),l.push(Ad())),o&&(l.push(""),l.push(Rd({toolCalls:r,bindings:i}))),r&&i&&(l.push(""),l.push(Td())),r&&(l.push(""),l.push(zd())),(g=e.tools)!=null&&g.length&&(l.push(""),l.push(Fd(e.tools))),l.push(""),l.push(Id(t,{supportsExpressions:a}));const c=[...e.examples??[],...e.toolExamples??[]];if(c.length){l.push(""),l.push("## Examples"),l.push("");for(const u of c)l.push(u),l.push("")}if(e.editMode&&(l.push(""),l.push(Od())),e.inlineMode&&(l.push(""),l.push(Pd())),l.push(Ld(t,{toolCalls:r,bindings:i})),(h=e.additionalRules)!=null&&h.length){l.push("");for(const u of e.additionalRules)l.push(`- ${u}`)}return l.join(`
277
- `)}const Zd=new WeakSet;function _t(e){return typeof e=="object"&&e!==null&&Zd.has(e)}const ii=new WeakMap;function qd(e,t){if(e!=null&&typeof e=="object"&&"_def"in e&&!("_zod"in e))throw new Error(`[OpenUI] Component "${t}" was defined with a Zod 3 schema. OpenUI requires Zod 4 schemas. If you're on zod@3.25+, import from "zod/v4" instead of "zod". See: https://zod.dev/v4/versioning`)}function Gd(e){return qd(e.props,e.name),ii.set(e.props,e.name),{...e,ref:e.props}}function Ye(e){var t;return(t=e==null?void 0:e._zod)==null?void 0:t.def}function as(e){var t;return(t=Ye(e))==null?void 0:t.type}function ai(e){const t=as(e);return t==="optional"||t==="default"||t==="nullable"}function zt(e){let t=e,n=Ye(t);for(;(n==null?void 0:n.type)==="optional"||(n==null?void 0:n.type)==="default"||(n==null?void 0:n.type)==="nullable";)t=n.innerType,n=Ye(t);return t}function oi(e){return as(zt(e))==="array"}function Bd(e){const t=Ye(zt(e));if((t==null?void 0:t.type)==="array")return t.element??t.innerType}function Wd(e){const t=Ye(zt(e));if((t==null?void 0:t.type)==="enum"){if(Array.isArray(t.values))return t.values;if(t.entries&&typeof t.entries=="object")return Object.keys(t.entries)}}function Vd(e,t){try{const n=t.get(e);if(n!=null&&n.id)return n.id}catch{}if(typeof e=="object"&&e!==null)return ii.get(e)}function qs(e){const t=Ye(e);if((t==null?void 0:t.type)==="union"&&Array.isArray(t.options))return t.options}function Qd(e){const t=Ye(e);if((t==null?void 0:t.type)==="object"&&t.shape&&typeof t.shape=="object")return t.shape}function pt(e,t){const n=_t(e),r=Kd(zt(e),t);if(r)return n?`$binding<${r}>`:r}function Kd(e,t){var l;const n=Vd(e,t);if(n)return n;const r=qs(e);if(r){const c=r.map(d=>pt(d,t)).filter(Boolean);if(c.length>0)return c.join(" | ")}if(oi(e)){const c=Bd(e);if(!c)return;const d=pt(c,t);return d?qs(zt(c))!==void 0?`(${d})[]`:`${d}[]`:void 0}const i=as(e);if(i==="string")return"string";if(i==="number")return"number";if(i==="boolean")return"boolean";if(i==="any")return"any";if(i==="record"){const c=Ye(e);return`Record<${pt(c==null?void 0:c.keyType,t)??"string"}, ${pt(c==null?void 0:c.valueType,t)??"any"}>`}const a=Wd(e);if(a)return a.map(c=>`"${c}"`).join(" | ");if(i==="literal"){const c=(l=Ye(e))==null?void 0:l.values;if(Array.isArray(c)&&c.length===1){const d=c[0];return typeof d=="string"?`"${d}"`:String(d)}}const o=Qd(e);return o?`{${Object.entries(o).map(([c,d])=>{const g=ai(d)?"?":"",h=pt(d,t);return h?`${c}${g}: ${h}`:`${c}${g}`}).join(", ")}}`:"any"}function Jd(e,t){return Object.entries(e).map(([n,r])=>({name:n,isOptional:ai(r),isArray:oi(r),typeAnnotation:pt(r,t)}))}function Yd(e,t){return`${e}(${t.map(n=>n.typeAnnotation?n.isOptional?`${n.name}?: ${n.typeAnnotation}`:`${n.name}: ${n.typeAnnotation}`:n.isArray?n.isOptional?`[${n.name}]?`:`[${n.name}]`:n.isOptional?`${n.name}?`:n.name).join(", ")})`}function Gs(e,t){const n={};for(const[r,i]of Object.entries(e))n[r]={signature:Yd(r,Jd(i.props.shape,t)),description:i.description};return n}function Hd(e){const t={},n=Jr();for(const r of e.components)n.add(r.props,{id:r.name}),t[r.name]=r;if(e.root&&!t[e.root]){const r=Object.keys(t).join(", ");throw new Error(`[createLibrary] Root component "${e.root}" was not found in components. Available components: ${r}`)}return{components:t,componentGroups:e.componentGroups,root:e.root,prompt(r){return Dd({root:e.root,components:Gs(t,n),componentGroups:e.componentGroups,...r})},toSpec(){return{root:e.root,components:Gs(t,n),componentGroups:e.componentGroups}},toJSONSchema(){const r=pe(Object.fromEntries(Object.entries(t).map(([i,a])=>[i,a.props])));return xu(r,{metadata:n})}}}function Ke(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.type==="element"&&typeof t.typeName=="string"&&typeof t.props=="object"&&t.props!==null&&typeof t.partial=="boolean"}let Zt=(function(e){return e.ContinueConversation="continue_conversation",e.OpenUrl="open_url",e})({});function Xd(e){switch(e.k){case"StateRef":case"RuntimeRef":case"BinOp":case"UnaryOp":case"Ternary":case"Member":case"Index":case"Assign":return!0;default:return!1}}const ep=new Set(["Comp","Ref","StateRef","RuntimeRef","BinOp","UnaryOp","Ternary","Member","Index","Assign","Str","Num","Bool","Null","Arr","Obj","Ph"]);function ht(e){return!e||typeof e!="object"||Array.isArray(e)?!1:ep.has(e.k)}function tp(e,t){const n=r=>{switch(t(r),r.k){case"Comp":r.args.forEach(n),Object.values(r.mappedProps??{}).forEach(n);break;case"Arr":r.els.forEach(n);break;case"Obj":r.entries.forEach(([,i])=>n(i));break;case"BinOp":n(r.left),n(r.right);break;case"UnaryOp":n(r.operand);break;case"Ternary":n(r.cond),n(r.then),n(r.else);break;case"Member":n(r.obj);break;case"Index":n(r.obj),n(r.index);break;case"Assign":n(r.value);break}};n(e)}let N=(function(e){return e[e.Newline=0]="Newline",e[e.LParen=1]="LParen",e[e.RParen=2]="RParen",e[e.LBrack=3]="LBrack",e[e.RBrack=4]="RBrack",e[e.LBrace=5]="LBrace",e[e.RBrace=6]="RBrace",e[e.Comma=7]="Comma",e[e.Colon=8]="Colon",e[e.Equals=9]="Equals",e[e.True=10]="True",e[e.False=11]="False",e[e.Null=12]="Null",e[e.EOF=13]="EOF",e[e.Str=14]="Str",e[e.Num=15]="Num",e[e.Ident=16]="Ident",e[e.Type=17]="Type",e[e.StateVar=18]="StateVar",e[e.Dot=19]="Dot",e[e.Plus=20]="Plus",e[e.Minus=21]="Minus",e[e.Star=22]="Star",e[e.Slash=23]="Slash",e[e.Percent=24]="Percent",e[e.EqEq=25]="EqEq",e[e.NotEq=26]="NotEq",e[e.Greater=27]="Greater",e[e.Less=28]="Less",e[e.GreaterEq=29]="GreaterEq",e[e.LessEq=30]="LessEq",e[e.And=31]="And",e[e.Or=32]="Or",e[e.Not=33]="Not",e[e.Question=34]="Question",e[e.BuiltinCall=35]="BuiltinCall",e})({});const np=1,Bs=2,Ws=3,Cn=4,kt=5,$n=6,qt=7,Vs=8,sp=9;function Qs(e){let t=0;const n=()=>e[t]??{t:N.EOF},r=()=>{const u=n();return t++,u},i=u=>{n().t===u&&t++};function a(u){switch(u.t){case N.Question:return np;case N.Or:return Bs;case N.And:return Ws;case N.EqEq:case N.NotEq:return Cn;case N.Greater:case N.Less:case N.GreaterEq:case N.LessEq:return kt;case N.Plus:case N.Minus:return $n;case N.Star:case N.Slash:case N.Percent:return qt;case N.Dot:case N.LBrack:return sp;default:return 0}}function o(u=0){let p=l();for(;a(n())>u;)p=c(p);return p}function l(){var p,v;const u=n();if(u.t===N.Str)return r(),{k:"Str",v:u.v};if(u.t===N.Num)return r(),{k:"Num",v:u.v};if(u.t===N.True)return r(),{k:"Bool",v:!0};if(u.t===N.False)return r(),{k:"Bool",v:!1};if(u.t===N.Null)return r(),{k:"Null"};if(u.t===N.LBrack)return g();if(u.t===N.LBrace)return h();if(u.t===N.StateVar){const y=u.v;return r(),n().t===N.Equals?(r(),{k:"Assign",target:y,value:o(0)}):{k:"StateRef",n:y}}if(u.t===N.Type){const y=u.v;return((p=e[t+1])==null?void 0:p.t)===N.LParen&&(!Ot(y)||y==="Action")?d():(r(),{k:"Ref",n:y})}if(u.t===N.BuiltinCall)return((v=e[t+1])==null?void 0:v.t)===N.LParen?d():(r(),{k:"Ref",n:u.v});if(u.t===N.Ident)return r(),{k:"Ref",n:u.v};if(u.t===N.Not)return r(),{k:"UnaryOp",op:"!",operand:o(Vs)};if(u.t===N.Minus)return r(),{k:"UnaryOp",op:"-",operand:o(Vs)};if(u.t===N.LParen){r();const y=o(0);return i(N.RParen),y}return r(),{k:"Null"}}function c(u){const p=n();if(p.t===N.Plus)return r(),{k:"BinOp",op:"+",left:u,right:o($n)};if(p.t===N.Minus)return r(),{k:"BinOp",op:"-",left:u,right:o($n)};if(p.t===N.Star)return r(),{k:"BinOp",op:"*",left:u,right:o(qt)};if(p.t===N.Slash)return r(),{k:"BinOp",op:"/",left:u,right:o(qt)};if(p.t===N.Percent)return r(),{k:"BinOp",op:"%",left:u,right:o(qt)};if(p.t===N.EqEq)return r(),{k:"BinOp",op:"==",left:u,right:o(Cn)};if(p.t===N.NotEq)return r(),{k:"BinOp",op:"!=",left:u,right:o(Cn)};if(p.t===N.Greater)return r(),{k:"BinOp",op:">",left:u,right:o(kt)};if(p.t===N.Less)return r(),{k:"BinOp",op:"<",left:u,right:o(kt)};if(p.t===N.GreaterEq)return r(),{k:"BinOp",op:">=",left:u,right:o(kt)};if(p.t===N.LessEq)return r(),{k:"BinOp",op:"<=",left:u,right:o(kt)};if(p.t===N.And)return r(),{k:"BinOp",op:"&&",left:u,right:o(Ws)};if(p.t===N.Or)return r(),{k:"BinOp",op:"||",left:u,right:o(Bs)};if(p.t===N.Question){r();const v=o(0);return i(N.Colon),{k:"Ternary",cond:u,then:v,else:o(0)}}if(p.t===N.Dot){r();const v=n();return{k:"Member",obj:u,field:v.t===N.Ident||v.t===N.Type||v.t===N.Str||v.t===N.Num?(r(),String(v.v)):v.t===N.StateVar?(r(),v.v.replace(/^\$/,"")):(r(),"?")}}if(p.t===N.LBrack){r();const v=o(0);return i(N.RBrack),{k:"Index",obj:u,index:v}}return u}function d(){const u=n().v;r(),i(N.LParen);const p=[];for(;n().t!==N.RParen&&n().t!==N.EOF;)p.push(o(0)),n().t===N.Comma&&r();return i(N.RParen),{k:"Comp",name:u,args:p}}function g(){r();const u=[];for(;n().t!==N.RBrack&&n().t!==N.EOF;)u.push(o(0)),n().t===N.Comma&&r();return i(N.RBrack),{k:"Arr",els:u}}function h(){r();const u=[];for(;n().t!==N.RBrace&&n().t!==N.EOF;){const p=n(),v=p.t===N.Ident||p.t===N.Str||p.t===N.Type||p.t===N.Num?(r(),String(p.v)):p.t===N.StateVar?(r(),p.v.replace(/^\$/,"")):(r(),"?");i(N.Colon),u.push([v,o(0)]),n().t===N.Comma&&r()}return i(N.RBrace),{k:"Obj",entries:u}}return o(0)}function Ks(e){const t=[];let n=0;const r=e.length;for(;n<r;){for(;n<r&&(e[n]===" "||e[n]===" "||e[n]==="\r");)n++;if(n>=r)break;const i=e[n];if(i===`
278
- `){t.push({t:N.Newline}),n++;continue}if(i==="("){t.push({t:N.LParen}),n++;continue}if(i===")"){t.push({t:N.RParen}),n++;continue}if(i==="["){t.push({t:N.LBrack}),n++;continue}if(i==="]"){t.push({t:N.RBrack}),n++;continue}if(i==="{"){t.push({t:N.LBrace}),n++;continue}if(i==="}"){t.push({t:N.RBrace}),n++;continue}if(i===","){t.push({t:N.Comma}),n++;continue}if(i===":"){t.push({t:N.Colon}),n++;continue}if(i==="="){n+1<r&&e[n+1]==="="?(t.push({t:N.EqEq}),n+=2):(t.push({t:N.Equals}),n++);continue}if(i==="!"){n+1<r&&e[n+1]==="="?(t.push({t:N.NotEq}),n+=2):(t.push({t:N.Not}),n++);continue}if(i===">"){n+1<r&&e[n+1]==="="?(t.push({t:N.GreaterEq}),n+=2):(t.push({t:N.Greater}),n++);continue}if(i==="<"){n+1<r&&e[n+1]==="="?(t.push({t:N.LessEq}),n+=2):(t.push({t:N.Less}),n++);continue}if(i==="&"){n+1<r&&e[n+1]==="&"?(t.push({t:N.And}),n+=2):(t.push({t:N.And}),n++);continue}if(i==="|"){n+1<r&&e[n+1]==="|"?(t.push({t:N.Or}),n+=2):(t.push({t:N.Or}),n++);continue}if(i==="."){t.push({t:N.Dot}),n++;continue}if(i==="?"){t.push({t:N.Question}),n++;continue}if(i==="+"){t.push({t:N.Plus}),n++;continue}if(i==="*"){t.push({t:N.Star}),n++;continue}if(i==="/"){t.push({t:N.Slash}),n++;continue}if(i==="%"){t.push({t:N.Percent}),n++;continue}if(i==='"'){const l=n;n++;let c=!1;for(;n<r;)if(e[n]==="\\")n+=2;else if(e[n]==='"'){n++,c=!0;break}else n++;const d=e.slice(l,n);try{const g=c?d:d+'"';t.push({t:N.Str,v:JSON.parse(g)})}catch{const g=d.replace(/^"|"$/g,"");t.push({t:N.Str,v:g})}continue}if(i==="'"){n++;let l="";for(;n<r;)if(e[n]==="\\"){if(n++,n<r){const c=e[n];c==="'"?l+="'":c==="\\"?l+="\\":c==="n"?l+=`
279
- `:c==="t"?l+=" ":l+=c,n++}}else if(e[n]==="'"){n++;break}else l+=e[n],n++;t.push({t:N.Str,v:l});continue}if(i==="-"){const l=t.length>0?t[t.length-1]:null;if(!(!(l!=null&&(l.t===N.Num||l.t===N.Str||l.t===N.Ident||l.t===N.Type||l.t===N.RParen||l.t===N.RBrack||l.t===N.True||l.t===N.False||l.t===N.Null||l.t===N.StateVar||l.t===N.BuiltinCall))&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9")){t.push({t:N.Minus}),n++;continue}}const a=i>="0"&&i<="9",o=i==="-"&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9";if(a||o){const l=n;for(e[n]==="-"&&n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;if(n<r&&e[n]==="."&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9")for(n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;if(n<r&&(e[n]==="e"||e[n]==="E"))for(n++,n<r&&(e[n]==="+"||e[n]==="-")&&n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;t.push({t:N.Num,v:+e.slice(l,n)});continue}if(i==="$"&&n+1<r&&(e[n+1]>="a"&&e[n+1]<="z"||e[n+1]>="A"&&e[n+1]<="Z"||e[n+1]==="_")){const l=n;for(n++;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;t.push({t:N.StateVar,v:e.slice(l,n)});continue}if(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="_"){const l=n;for(;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;const c=e.slice(l,n);if(c==="true"){t.push({t:N.True});continue}if(c==="false"){t.push({t:N.False});continue}if(c==="null"){t.push({t:N.Null});continue}const d=i>="A"&&i<="Z"?N.Type:N.Ident;t.push({t:d,v:c});continue}if(i==="@"&&n+1<r&&(e[n+1]>="a"&&e[n+1]<="z"||e[n+1]>="A"&&e[n+1]<="Z"||e[n+1]==="_")){n++;const l=n;for(;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;t.push({t:N.BuiltinCall,v:e.slice(l,n)});continue}n++}return t.push({t:N.EOF}),t}function Kt(e){return e==null||typeof e!="object"?!1:ht(e)?!0:Array.isArray(e)?e.some(Kt):Ke(e)?Object.values(e.props).some(Kt):Object.values(e).some(Kt)}function li(e,t,n){var a;if(t.visited.has(e))return t.unres.push(e),n==="expr"?{k:"Ph",n:e}:null;if(!t.syms.has(e))return t.unres.push(e),n==="expr"?{k:"Ph",n:e}:null;const r=t.syms.get(e);if((a=t.unreached)==null||a.delete(e),r.k==="Comp"&&on(r.name))return{k:"RuntimeRef",n:e,refType:r.name===He.Mutation?"mutation":"query"};t.visited.add(e);const i=t.currentStatementId;t.currentStatementId=e;try{const o=n==="value"?mt(r,t):Un(r,t);return n==="value"&&Ke(o)&&(o.statementId=e),o}finally{t.currentStatementId=i,t.visited.delete(e)}}function ci(e,t,n){if(!is.has(e.name)||e.args.length<3)return null;const r=e.args[1],i=r.k==="Ref"?r.n:r.k==="Str"?r.v:null;if(!i)return null;const a=new Set(n);a.add(i);const o=e.args.map((l,c)=>c===1?l:Ae(l,t,a));return{...e,args:o}}function Ae(e,t,n){var r;switch(e.k){case"Ref":return n.has(e.n)?e:li(e.n,t,"expr");case"Ph":return e;case"Comp":{const i=ci(e,t,n);if(i)return i;const a=e.args.map(l=>Ae(l,t,n));if(Ot(e.name)||on(e.name))return{...e,args:a};const o=(r=t.cat)==null?void 0:r.get(e.name);if(o){const l={};for(let c=0;c<o.params.length&&c<a.length;c++)l[o.params[c].name]=a[c];return{...e,args:a,mappedProps:l}}return t.errors.push({code:"unknown-component",component:e.name,path:"",message:`Unknown component "${e.name}" — not found in catalog or builtins`,statementId:t.currentStatementId}),{...e,args:a}}case"Arr":return{...e,els:e.els.map(i=>Ae(i,t,n))};case"Obj":return{...e,entries:e.entries.map(([i,a])=>[i,Ae(a,t,n)])};case"BinOp":return{...e,left:Ae(e.left,t,n),right:Ae(e.right,t,n)};case"UnaryOp":return{...e,operand:Ae(e.operand,t,n)};case"Ternary":return{...e,cond:Ae(e.cond,t,n),then:Ae(e.then,t,n),else:Ae(e.else,t,n)};case"Member":return{...e,obj:Ae(e.obj,t,n)};case"Index":return{...e,obj:Ae(e.obj,t,n),index:Ae(e.index,t,n)};case"Assign":return{...e,value:Ae(e.value,t,n)};default:return e}}function Un(e,t){return Ae(e,t,new Set)}function mt(e,t){var n;switch(e.k){case"Ref":return li(e.n,t,"value");case"Str":return e.v;case"Num":return e.v;case"Bool":return e.v;case"Null":return null;case"Ph":return null;case"Arr":{const r=[];for(const i of e.els){if(i.k==="Ph")continue;const a=mt(i,t);a===null&&(i.k==="Comp"||i.k==="Ref")||r.push(a)}return r}case"Obj":{const r={};for(const[i,a]of e.entries)r[i]=mt(a,t);return r}case"Comp":{const{name:r,args:i}=e;if(Ot(r)){const c=ci(e,t,new Set);return c||{...e,args:i.map(d=>Un(d,t))}}if(on(r))return t.errors.push({code:"inline-reserved",component:r,path:"",message:`${r}() must be declared as a top-level statement, not used inline as a value`,statementId:t.currentStatementId}),null;const a=(n=t.cat)==null?void 0:n.get(r),o={};if(a){for(let d=0;d<a.params.length&&d<i.length;d++)o[a.params[d].name]=mt(i[d],t);if(i.length>a.params.length){const d=i.length-a.params.length;t.errors.push({code:"excess-args",component:r,path:"",message:`${r} takes ${a.params.length} arg(s), got ${i.length} (${d} excess dropped)`,statementId:t.currentStatementId})}const c=a.params.filter(d=>d.required&&(!(d.name in o)||o[d.name]===null));if(c.length){const d=c.filter(g=>g.defaultValue!==void 0?(o[g.name]=g.defaultValue,!1):!0);if(d.length){for(const g of d){const h=g.name in o;t.errors.push({code:h?"null-required":"missing-required",component:r,path:`/${g.name}`,message:h?`required field "${g.name}" cannot be null`:`missing required field "${g.name}"`,statementId:t.currentStatementId})}return null}}}else if(!Ot(r)&&!on(r))return t.errors.push({code:"unknown-component",component:r,path:"",message:`Unknown component "${r}" — not found in catalog or builtins`,statementId:t.currentStatementId}),null;const l=Object.values(o).some(c=>Kt(c));return{type:"element",typeName:r,props:o,partial:t.partial,hasDynamicProps:l}}default:return Xd(e)?Un(e,t):e}}function rp(e){const t=[];let n=!1,r=!1;for(let a=0;a<e.length;a++){const o=e[a];if(r){r=!1;continue}if(o==="\\"&&n){r=!0;continue}if(n){o===n&&(n=!1);continue}if(o==='"'||o==="'"){n=o;continue}o==="("||o==="["||o==="{"?t.push(o):(o===")"&&t[t.length-1]==="("||o==="]"&&t[t.length-1]==="["||o==="}"&&t[t.length-1]==="{")&&t.pop()}if(!(n||t.length>0))return{text:e,wasIncomplete:!1};let i=e;n&&(r&&(i+="\\"),i+=n);for(let a=t.length-1;a>=0;a--)i+=t[a]==="("?")":t[a]==="["?"]":"}";return{text:i,wasIncomplete:!0}}function Js(e){const t=[];let n=0;for(;n<e.length;){for(;n<e.length&&e[n].t===N.Newline;)n++;if(n>=e.length||e[n].t===N.EOF)break;const r=e[n];if(r.t!==N.Ident&&r.t!==N.Type&&r.t!==N.StateVar){for(;n<e.length&&e[n].t!==N.Newline&&e[n].t!==N.EOF;)n++;continue}const i=r.v,a=r.t;if(n++,n>=e.length||e[n].t!==N.Equals){for(;n<e.length&&e[n].t!==N.Newline&&e[n].t!==N.EOF;)n++;continue}n++;const o=[];let l=0,c=0;for(;n<e.length&&e[n].t!==N.EOF;){const d=e[n].t;if(d===N.Newline&&l<=0&&c<=0){let g=n+1;for(;g<e.length&&e[g].t===N.Newline;)g++;const h=g<e.length?e[g].t:N.EOF;if(h===N.Question||h===N.Colon&&c>0){n++;continue}break}if(d===N.Newline){n++;continue}d===N.LParen||d===N.LBrack||d===N.LBrace?l++:(d===N.RParen||d===N.RBrack||d===N.RBrace)&&l>0?l--:d===N.Question&&l===0?c++:d===N.Colon&&l===0&&c>0&&c--,o.push(e[n++])}o.length&&t.push({id:i,idTokenType:a,tokens:o})}return t}function Jt(e=!0){return{root:null,meta:{incomplete:e,unresolved:[],orphaned:[],statementCount:0,errors:[]},stateDeclarations:{},queryStatements:[],mutationStatements:[]}}function ui(e){if(!ht(e))return[];const t=new Set;return tp(e,n=>{n.k==="StateRef"&&t.add(n.n)}),[...t]}function Ys(e,t){if(t.k==="Comp"&&t.name===He.Query){const n=ui(t.args[1]);return{kind:"query",id:e.id,call:{callee:He.Query,args:t.args},expr:t,deps:n.length>0?n:void 0}}return t.k==="Comp"&&t.name===He.Mutation?{kind:"mutation",id:e.id,call:{callee:He.Mutation,args:t.args},expr:t}:e.idTokenType===N.StateVar?{kind:"state",id:e.id,init:t}:{kind:"value",id:e.id,expr:t}}function ip(e,t){const n={},r=[],i=[];for(const a of e)switch(a.kind){case"state":n[a.id]=mt(a.init,t);break;case"query":r.push({statementId:a.id,toolAST:a.call.args[0]??null,argsAST:a.call.args[1]??null,defaultsAST:a.call.args[2]??null,refreshAST:a.call.args[3]??null,deps:a.deps,complete:!0});break;case"mutation":i.push({statementId:a.id,toolAST:a.call.args[0]??null,argsAST:a.call.args[1]??null});break}for(const a of e){const o=a.kind==="state"?[a.init]:a.kind==="value"?[a.expr]:a.kind==="query"||a.kind==="mutation"?a.call.args:[];for(const l of o)for(const c of ui(l))c in n||(n[c]=null)}return{stateDeclarations:n,queryStatements:r,mutationStatements:i}}const Hs="root";function Xs(e){return e.kind==="value"&&e.expr.k==="Comp"&&!Ot(e.expr.name)&&e.expr.name!==He.Query&&e.expr.name!==He.Mutation}function ap(e,t,n,r){var a;if(e.has(Hs))return Hs;if(r&&e.has(r))return r;const i=r?t.find(o=>Xs(o)&&o.expr.name===r):void 0;return i?i.id:((a=t.find(Xs))==null?void 0:a.id)??n}function Gt(e,t,n,r,i,a,o){const l=ap(e,t,n,o);if(!e.has(l))return Jt(r);const c=new Map;for(const[b,x]of e)c.set(b,x.kind==="state"?x.init:x.expr);const d=[],g=[],h=new Set;for(const[b,x]of e)b!==l&&(x.kind==="state"||x.kind==="query"||x.kind==="mutation"||h.add(b));const u={syms:c,cat:a,errors:g,unres:d,visited:new Set,partial:r,currentStatementId:l,unreached:h},p=mt(c.get(l),u),v=Ke(p)?p:null;v&&(v.statementId=l);const{stateDeclarations:y,queryStatements:w,mutationStatements:m}=ip(t,u);return{root:v,meta:{incomplete:r,unresolved:d,orphaned:[...h],statementCount:i,errors:g},stateDeclarations:y,queryStatements:w,mutationStatements:m}}function op(e){const t=[];let n=0;for(;n<e.length;){const r=e.indexOf("```",n);if(r===-1)break;let i=r+3;for(;i<e.length&&e[i]!==`
273
+ `)}`}function Fd(e){let t="";if(e.inputSchema){const i=e.inputSchema.properties,a=e.inputSchema.required??[];i&&Object.keys(i).length>0&&(t=Object.entries(i).map(([o,l])=>`${o}${a.includes(o)?"":"?"}: ${ln(l)}`).join(", "))}let n="";e.outputSchema&&(n=` → ${ln(e.outputSchema)}`);let r=`- ${e.name}(${t})${n}`;return e.description&&(r+=`
274
+ ${e.description}`),r}function Ud(e){const t=[],n=[],r=[];for(const a of e)typeof a=="string"?n.push(a):r.push(a);t.push("## Available Tools"),t.push(""),t.push("Use these with Query() for read operations or Mutation() for write operations. The LLM decides which is appropriate based on the tool's purpose."),t.push("");for(const a of n)t.push(`- ${a}`);for(const a of r)t.push(Fd(a));const i=r.filter(a=>a.outputSchema);if(i.length>0){t.push(""),t.push("### Default values for Query results"),t.push(""),t.push("Use these shapes as minimal Query defaults:");for(const a of i){const o=ii(a.outputSchema);t.push(`- ${a.name}: \`${JSON.stringify(o)}\``)}}return t.push(""),t.push("CRITICAL: Use ONLY the tools listed above in Query() and Mutation() calls. Do NOT invent or guess tool names. If the user asks for functionality that doesn't match any available tool, use realistic mock data instead of fabricating a tool call."),t.join(`
275
+ `)}function Dd(e,t){var i,a;const n=["## Component Signatures","","Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming."];if(t.usesActionExpression){const o=[t.toolCalls?"@Run":"","@ToAssistant","@OpenUrl",t.bindings?"@Set":"",t.bindings?"@Reset":""].filter(Boolean);n.push(`Props typed \`ActionExpression\` accept an Action([@steps...]) expression. See the Action section for available steps (${o.join(", ")}).`)}(t.bindings||Object.values(e.components).some(o=>{var l;return(l=o.signature)==null?void 0:l.includes("$binding")}))&&n.push("Props marked `$binding<type>` accept a `$variable` reference for two-way binding.");const r=o=>o.description?`${o.signature} — ${o.description}`:o.signature;if((i=e.componentGroups)!=null&&i.length){const o=new Set;for(const c of e.componentGroups){n.push("",`### ${c.name}`);for(const d of c.components){if(o.has(d))continue;const g=e.components[d];g&&(o.add(d),n.push(r(g)))}if((a=c.notes)!=null&&a.length)for(const d of c.notes)n.push(d)}const l=Object.keys(e.components).filter(c=>!o.has(c));if(l.length){n.push("","### Other");for(const c of l){const d=e.components[c];n.push(r(d))}}}else{n.push("");for(const[,o]of Object.entries(e.components))n.push(r(o))}return n.join(`
276
+ `)}function Zd(e){var d,g,h;const t=e.root??"Root",n=!!((d=e.tools)!=null&&d.length),r=e.toolCalls??n,i=e.bindings??r,a=r||i,o=Object.values(e.components).some(u=>{var p;return(p=u.signature)==null?void 0:p.includes("ActionExpression")}),l=[];l.push(e.preamble??$d),l.push(""),l.push(Ed(t,{supportsExpressions:a,bindings:i})),l.push(""),l.push(Dd(e,{toolCalls:r,bindings:i,usesActionExpression:o})),a&&(l.push(""),l.push(_d())),r&&(l.push(""),l.push(Ad()),l.push(""),l.push(Td())),o&&(l.push(""),l.push(Rd({toolCalls:r,bindings:i}))),r&&i&&(l.push(""),l.push(Od())),r&&(l.push(""),l.push(Ld())),(g=e.tools)!=null&&g.length&&(l.push(""),l.push(Ud(e.tools))),l.push(""),l.push(Pd(t,{supportsExpressions:a}));const c=[...e.examples??[],...e.toolExamples??[]];if(c.length){l.push(""),l.push("## Examples"),l.push("");for(const u of c)l.push(u),l.push("")}if(e.editMode&&(l.push(""),l.push(Id())),e.inlineMode&&(l.push(""),l.push(zd())),l.push(Md(t,{toolCalls:r,bindings:i})),(h=e.additionalRules)!=null&&h.length){l.push("");for(const u of e.additionalRules)l.push(`- ${u}`)}return l.join(`
277
+ `)}const qd=new WeakSet;function _t(e){return typeof e=="object"&&e!==null&&qd.has(e)}const ai=new WeakMap;function Gd(e,t){if(e!=null&&typeof e=="object"&&"_def"in e&&!("_zod"in e))throw new Error(`[OpenUI] Component "${t}" was defined with a Zod 3 schema. OpenUI requires Zod 4 schemas. If you're on zod@3.25+, import from "zod/v4" instead of "zod". See: https://zod.dev/v4/versioning`)}function Bd(e){return Gd(e.props,e.name),ai.set(e.props,e.name),{...e,ref:e.props}}function He(e){var t;return(t=e==null?void 0:e._zod)==null?void 0:t.def}function as(e){var t;return(t=He(e))==null?void 0:t.type}function oi(e){const t=as(e);return t==="optional"||t==="default"||t==="nullable"}function zt(e){let t=e,n=He(t);for(;(n==null?void 0:n.type)==="optional"||(n==null?void 0:n.type)==="default"||(n==null?void 0:n.type)==="nullable";)t=n.innerType,n=He(t);return t}function li(e){return as(zt(e))==="array"}function Wd(e){const t=He(zt(e));if((t==null?void 0:t.type)==="array")return t.element??t.innerType}function Vd(e){const t=He(zt(e));if((t==null?void 0:t.type)==="enum"){if(Array.isArray(t.values))return t.values;if(t.entries&&typeof t.entries=="object")return Object.keys(t.entries)}}function Qd(e,t){try{const n=t.get(e);if(n!=null&&n.id)return n.id}catch{}if(typeof e=="object"&&e!==null)return ai.get(e)}function qs(e){const t=He(e);if((t==null?void 0:t.type)==="union"&&Array.isArray(t.options))return t.options}function Kd(e){const t=He(e);if((t==null?void 0:t.type)==="object"&&t.shape&&typeof t.shape=="object")return t.shape}function pt(e,t){const n=_t(e),r=Jd(zt(e),t);if(r)return n?`$binding<${r}>`:r}function Jd(e,t){var l;const n=Qd(e,t);if(n)return n;const r=qs(e);if(r){const c=r.map(d=>pt(d,t)).filter(Boolean);if(c.length>0)return c.join(" | ")}if(li(e)){const c=Wd(e);if(!c)return;const d=pt(c,t);return d?qs(zt(c))!==void 0?`(${d})[]`:`${d}[]`:void 0}const i=as(e);if(i==="string")return"string";if(i==="number")return"number";if(i==="boolean")return"boolean";if(i==="any")return"any";if(i==="record"){const c=He(e);return`Record<${pt(c==null?void 0:c.keyType,t)??"string"}, ${pt(c==null?void 0:c.valueType,t)??"any"}>`}const a=Vd(e);if(a)return a.map(c=>`"${c}"`).join(" | ");if(i==="literal"){const c=(l=He(e))==null?void 0:l.values;if(Array.isArray(c)&&c.length===1){const d=c[0];return typeof d=="string"?`"${d}"`:String(d)}}const o=Kd(e);return o?`{${Object.entries(o).map(([c,d])=>{const g=oi(d)?"?":"",h=pt(d,t);return h?`${c}${g}: ${h}`:`${c}${g}`}).join(", ")}}`:"any"}function Hd(e,t){return Object.entries(e).map(([n,r])=>({name:n,isOptional:oi(r),isArray:li(r),typeAnnotation:pt(r,t)}))}function Yd(e,t){return`${e}(${t.map(n=>n.typeAnnotation?n.isOptional?`${n.name}?: ${n.typeAnnotation}`:`${n.name}: ${n.typeAnnotation}`:n.isArray?n.isOptional?`[${n.name}]?`:`[${n.name}]`:n.isOptional?`${n.name}?`:n.name).join(", ")})`}function Gs(e,t){const n={};for(const[r,i]of Object.entries(e))n[r]={signature:Yd(r,Hd(i.props.shape,t)),description:i.description};return n}function Xd(e){const t={},n=Hr();for(const r of e.components)n.add(r.props,{id:r.name}),t[r.name]=r;if(e.root&&!t[e.root]){const r=Object.keys(t).join(", ");throw new Error(`[createLibrary] Root component "${e.root}" was not found in components. Available components: ${r}`)}return{components:t,componentGroups:e.componentGroups,root:e.root,prompt(r){return Zd({root:e.root,components:Gs(t,n),componentGroups:e.componentGroups,...r})},toSpec(){return{root:e.root,components:Gs(t,n),componentGroups:e.componentGroups}},toJSONSchema(){const r=pe(Object.fromEntries(Object.entries(t).map(([i,a])=>[i,a.props])));return ju(r,{metadata:n})}}}function Ke(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.type==="element"&&typeof t.typeName=="string"&&typeof t.props=="object"&&t.props!==null&&typeof t.partial=="boolean"}let Zt=(function(e){return e.ContinueConversation="continue_conversation",e.OpenUrl="open_url",e})({});function ep(e){switch(e.k){case"StateRef":case"RuntimeRef":case"BinOp":case"UnaryOp":case"Ternary":case"Member":case"Index":case"Assign":return!0;default:return!1}}const tp=new Set(["Comp","Ref","StateRef","RuntimeRef","BinOp","UnaryOp","Ternary","Member","Index","Assign","Str","Num","Bool","Null","Arr","Obj","Ph"]);function ht(e){return!e||typeof e!="object"||Array.isArray(e)?!1:tp.has(e.k)}function np(e,t){const n=r=>{switch(t(r),r.k){case"Comp":r.args.forEach(n),Object.values(r.mappedProps??{}).forEach(n);break;case"Arr":r.els.forEach(n);break;case"Obj":r.entries.forEach(([,i])=>n(i));break;case"BinOp":n(r.left),n(r.right);break;case"UnaryOp":n(r.operand);break;case"Ternary":n(r.cond),n(r.then),n(r.else);break;case"Member":n(r.obj);break;case"Index":n(r.obj),n(r.index);break;case"Assign":n(r.value);break}};n(e)}let S=(function(e){return e[e.Newline=0]="Newline",e[e.LParen=1]="LParen",e[e.RParen=2]="RParen",e[e.LBrack=3]="LBrack",e[e.RBrack=4]="RBrack",e[e.LBrace=5]="LBrace",e[e.RBrace=6]="RBrace",e[e.Comma=7]="Comma",e[e.Colon=8]="Colon",e[e.Equals=9]="Equals",e[e.True=10]="True",e[e.False=11]="False",e[e.Null=12]="Null",e[e.EOF=13]="EOF",e[e.Str=14]="Str",e[e.Num=15]="Num",e[e.Ident=16]="Ident",e[e.Type=17]="Type",e[e.StateVar=18]="StateVar",e[e.Dot=19]="Dot",e[e.Plus=20]="Plus",e[e.Minus=21]="Minus",e[e.Star=22]="Star",e[e.Slash=23]="Slash",e[e.Percent=24]="Percent",e[e.EqEq=25]="EqEq",e[e.NotEq=26]="NotEq",e[e.Greater=27]="Greater",e[e.Less=28]="Less",e[e.GreaterEq=29]="GreaterEq",e[e.LessEq=30]="LessEq",e[e.And=31]="And",e[e.Or=32]="Or",e[e.Not=33]="Not",e[e.Question=34]="Question",e[e.BuiltinCall=35]="BuiltinCall",e})({});const sp=1,Bs=2,Ws=3,Cn=4,kt=5,$n=6,qt=7,Vs=8,rp=9;function Qs(e){let t=0;const n=()=>e[t]??{t:S.EOF},r=()=>{const u=n();return t++,u},i=u=>{n().t===u&&t++};function a(u){switch(u.t){case S.Question:return sp;case S.Or:return Bs;case S.And:return Ws;case S.EqEq:case S.NotEq:return Cn;case S.Greater:case S.Less:case S.GreaterEq:case S.LessEq:return kt;case S.Plus:case S.Minus:return $n;case S.Star:case S.Slash:case S.Percent:return qt;case S.Dot:case S.LBrack:return rp;default:return 0}}function o(u=0){let p=l();for(;a(n())>u;)p=c(p);return p}function l(){var p,v;const u=n();if(u.t===S.Str)return r(),{k:"Str",v:u.v};if(u.t===S.Num)return r(),{k:"Num",v:u.v};if(u.t===S.True)return r(),{k:"Bool",v:!0};if(u.t===S.False)return r(),{k:"Bool",v:!1};if(u.t===S.Null)return r(),{k:"Null"};if(u.t===S.LBrack)return g();if(u.t===S.LBrace)return h();if(u.t===S.StateVar){const y=u.v;return r(),n().t===S.Equals?(r(),{k:"Assign",target:y,value:o(0)}):{k:"StateRef",n:y}}if(u.t===S.Type){const y=u.v;return((p=e[t+1])==null?void 0:p.t)===S.LParen&&(!Ot(y)||y==="Action")?d():(r(),{k:"Ref",n:y})}if(u.t===S.BuiltinCall)return((v=e[t+1])==null?void 0:v.t)===S.LParen?d():(r(),{k:"Ref",n:u.v});if(u.t===S.Ident)return r(),{k:"Ref",n:u.v};if(u.t===S.Not)return r(),{k:"UnaryOp",op:"!",operand:o(Vs)};if(u.t===S.Minus)return r(),{k:"UnaryOp",op:"-",operand:o(Vs)};if(u.t===S.LParen){r();const y=o(0);return i(S.RParen),y}return r(),{k:"Null"}}function c(u){const p=n();if(p.t===S.Plus)return r(),{k:"BinOp",op:"+",left:u,right:o($n)};if(p.t===S.Minus)return r(),{k:"BinOp",op:"-",left:u,right:o($n)};if(p.t===S.Star)return r(),{k:"BinOp",op:"*",left:u,right:o(qt)};if(p.t===S.Slash)return r(),{k:"BinOp",op:"/",left:u,right:o(qt)};if(p.t===S.Percent)return r(),{k:"BinOp",op:"%",left:u,right:o(qt)};if(p.t===S.EqEq)return r(),{k:"BinOp",op:"==",left:u,right:o(Cn)};if(p.t===S.NotEq)return r(),{k:"BinOp",op:"!=",left:u,right:o(Cn)};if(p.t===S.Greater)return r(),{k:"BinOp",op:">",left:u,right:o(kt)};if(p.t===S.Less)return r(),{k:"BinOp",op:"<",left:u,right:o(kt)};if(p.t===S.GreaterEq)return r(),{k:"BinOp",op:">=",left:u,right:o(kt)};if(p.t===S.LessEq)return r(),{k:"BinOp",op:"<=",left:u,right:o(kt)};if(p.t===S.And)return r(),{k:"BinOp",op:"&&",left:u,right:o(Ws)};if(p.t===S.Or)return r(),{k:"BinOp",op:"||",left:u,right:o(Bs)};if(p.t===S.Question){r();const v=o(0);return i(S.Colon),{k:"Ternary",cond:u,then:v,else:o(0)}}if(p.t===S.Dot){r();const v=n();return{k:"Member",obj:u,field:v.t===S.Ident||v.t===S.Type||v.t===S.Str||v.t===S.Num?(r(),String(v.v)):v.t===S.StateVar?(r(),v.v.replace(/^\$/,"")):(r(),"?")}}if(p.t===S.LBrack){r();const v=o(0);return i(S.RBrack),{k:"Index",obj:u,index:v}}return u}function d(){const u=n().v;r(),i(S.LParen);const p=[];for(;n().t!==S.RParen&&n().t!==S.EOF;)p.push(o(0)),n().t===S.Comma&&r();return i(S.RParen),{k:"Comp",name:u,args:p}}function g(){r();const u=[];for(;n().t!==S.RBrack&&n().t!==S.EOF;)u.push(o(0)),n().t===S.Comma&&r();return i(S.RBrack),{k:"Arr",els:u}}function h(){r();const u=[];for(;n().t!==S.RBrace&&n().t!==S.EOF;){const p=n(),v=p.t===S.Ident||p.t===S.Str||p.t===S.Type||p.t===S.Num?(r(),String(p.v)):p.t===S.StateVar?(r(),p.v.replace(/^\$/,"")):(r(),"?");i(S.Colon),u.push([v,o(0)]),n().t===S.Comma&&r()}return i(S.RBrace),{k:"Obj",entries:u}}return o(0)}function Ks(e){const t=[];let n=0;const r=e.length;for(;n<r;){for(;n<r&&(e[n]===" "||e[n]===" "||e[n]==="\r");)n++;if(n>=r)break;const i=e[n];if(i===`
278
+ `){t.push({t:S.Newline}),n++;continue}if(i==="("){t.push({t:S.LParen}),n++;continue}if(i===")"){t.push({t:S.RParen}),n++;continue}if(i==="["){t.push({t:S.LBrack}),n++;continue}if(i==="]"){t.push({t:S.RBrack}),n++;continue}if(i==="{"){t.push({t:S.LBrace}),n++;continue}if(i==="}"){t.push({t:S.RBrace}),n++;continue}if(i===","){t.push({t:S.Comma}),n++;continue}if(i===":"){t.push({t:S.Colon}),n++;continue}if(i==="="){n+1<r&&e[n+1]==="="?(t.push({t:S.EqEq}),n+=2):(t.push({t:S.Equals}),n++);continue}if(i==="!"){n+1<r&&e[n+1]==="="?(t.push({t:S.NotEq}),n+=2):(t.push({t:S.Not}),n++);continue}if(i===">"){n+1<r&&e[n+1]==="="?(t.push({t:S.GreaterEq}),n+=2):(t.push({t:S.Greater}),n++);continue}if(i==="<"){n+1<r&&e[n+1]==="="?(t.push({t:S.LessEq}),n+=2):(t.push({t:S.Less}),n++);continue}if(i==="&"){n+1<r&&e[n+1]==="&"?(t.push({t:S.And}),n+=2):(t.push({t:S.And}),n++);continue}if(i==="|"){n+1<r&&e[n+1]==="|"?(t.push({t:S.Or}),n+=2):(t.push({t:S.Or}),n++);continue}if(i==="."){t.push({t:S.Dot}),n++;continue}if(i==="?"){t.push({t:S.Question}),n++;continue}if(i==="+"){t.push({t:S.Plus}),n++;continue}if(i==="*"){t.push({t:S.Star}),n++;continue}if(i==="/"){t.push({t:S.Slash}),n++;continue}if(i==="%"){t.push({t:S.Percent}),n++;continue}if(i==='"'){const l=n;n++;let c=!1;for(;n<r;)if(e[n]==="\\")n+=2;else if(e[n]==='"'){n++,c=!0;break}else n++;const d=e.slice(l,n);try{const g=c?d:d+'"';t.push({t:S.Str,v:JSON.parse(g)})}catch{const g=d.replace(/^"|"$/g,"");t.push({t:S.Str,v:g})}continue}if(i==="'"){n++;let l="";for(;n<r;)if(e[n]==="\\"){if(n++,n<r){const c=e[n];c==="'"?l+="'":c==="\\"?l+="\\":c==="n"?l+=`
279
+ `:c==="t"?l+=" ":l+=c,n++}}else if(e[n]==="'"){n++;break}else l+=e[n],n++;t.push({t:S.Str,v:l});continue}if(i==="-"){const l=t.length>0?t[t.length-1]:null;if(!(!(l!=null&&(l.t===S.Num||l.t===S.Str||l.t===S.Ident||l.t===S.Type||l.t===S.RParen||l.t===S.RBrack||l.t===S.True||l.t===S.False||l.t===S.Null||l.t===S.StateVar||l.t===S.BuiltinCall))&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9")){t.push({t:S.Minus}),n++;continue}}const a=i>="0"&&i<="9",o=i==="-"&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9";if(a||o){const l=n;for(e[n]==="-"&&n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;if(n<r&&e[n]==="."&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9")for(n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;if(n<r&&(e[n]==="e"||e[n]==="E"))for(n++,n<r&&(e[n]==="+"||e[n]==="-")&&n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;t.push({t:S.Num,v:+e.slice(l,n)});continue}if(i==="$"&&n+1<r&&(e[n+1]>="a"&&e[n+1]<="z"||e[n+1]>="A"&&e[n+1]<="Z"||e[n+1]==="_")){const l=n;for(n++;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;t.push({t:S.StateVar,v:e.slice(l,n)});continue}if(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="_"){const l=n;for(;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;const c=e.slice(l,n);if(c==="true"){t.push({t:S.True});continue}if(c==="false"){t.push({t:S.False});continue}if(c==="null"){t.push({t:S.Null});continue}const d=i>="A"&&i<="Z"?S.Type:S.Ident;t.push({t:d,v:c});continue}if(i==="@"&&n+1<r&&(e[n+1]>="a"&&e[n+1]<="z"||e[n+1]>="A"&&e[n+1]<="Z"||e[n+1]==="_")){n++;const l=n;for(;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;t.push({t:S.BuiltinCall,v:e.slice(l,n)});continue}n++}return t.push({t:S.EOF}),t}function Kt(e){return e==null||typeof e!="object"?!1:ht(e)?!0:Array.isArray(e)?e.some(Kt):Ke(e)?Object.values(e.props).some(Kt):Object.values(e).some(Kt)}function ci(e,t,n){var a;if(t.visited.has(e))return t.unres.push(e),n==="expr"?{k:"Ph",n:e}:null;if(!t.syms.has(e))return t.unres.push(e),n==="expr"?{k:"Ph",n:e}:null;const r=t.syms.get(e);if((a=t.unreached)==null||a.delete(e),r.k==="Comp"&&on(r.name))return{k:"RuntimeRef",n:e,refType:r.name===Ye.Mutation?"mutation":"query"};t.visited.add(e);const i=t.currentStatementId;t.currentStatementId=e;try{const o=n==="value"?mt(r,t):Un(r,t);return n==="value"&&Ke(o)&&(o.statementId=e),o}finally{t.currentStatementId=i,t.visited.delete(e)}}function ui(e,t,n){if(!is.has(e.name)||e.args.length<3)return null;const r=e.args[1],i=r.k==="Ref"?r.n:r.k==="Str"?r.v:null;if(!i)return null;const a=new Set(n);a.add(i);const o=e.args.map((l,c)=>c===1?l:Ae(l,t,a));return{...e,args:o}}function Ae(e,t,n){var r;switch(e.k){case"Ref":return n.has(e.n)?e:ci(e.n,t,"expr");case"Ph":return e;case"Comp":{const i=ui(e,t,n);if(i)return i;const a=e.args.map(l=>Ae(l,t,n));if(Ot(e.name)||on(e.name))return{...e,args:a};const o=(r=t.cat)==null?void 0:r.get(e.name);if(o){const l={};for(let c=0;c<o.params.length&&c<a.length;c++)l[o.params[c].name]=a[c];return{...e,args:a,mappedProps:l}}return t.errors.push({code:"unknown-component",component:e.name,path:"",message:`Unknown component "${e.name}" — not found in catalog or builtins`,statementId:t.currentStatementId}),{...e,args:a}}case"Arr":return{...e,els:e.els.map(i=>Ae(i,t,n))};case"Obj":return{...e,entries:e.entries.map(([i,a])=>[i,Ae(a,t,n)])};case"BinOp":return{...e,left:Ae(e.left,t,n),right:Ae(e.right,t,n)};case"UnaryOp":return{...e,operand:Ae(e.operand,t,n)};case"Ternary":return{...e,cond:Ae(e.cond,t,n),then:Ae(e.then,t,n),else:Ae(e.else,t,n)};case"Member":return{...e,obj:Ae(e.obj,t,n)};case"Index":return{...e,obj:Ae(e.obj,t,n),index:Ae(e.index,t,n)};case"Assign":return{...e,value:Ae(e.value,t,n)};default:return e}}function Un(e,t){return Ae(e,t,new Set)}function mt(e,t){var n;switch(e.k){case"Ref":return ci(e.n,t,"value");case"Str":return e.v;case"Num":return e.v;case"Bool":return e.v;case"Null":return null;case"Ph":return null;case"Arr":{const r=[];for(const i of e.els){if(i.k==="Ph")continue;const a=mt(i,t);a===null&&(i.k==="Comp"||i.k==="Ref")||r.push(a)}return r}case"Obj":{const r={};for(const[i,a]of e.entries)r[i]=mt(a,t);return r}case"Comp":{const{name:r,args:i}=e;if(Ot(r)){const c=ui(e,t,new Set);return c||{...e,args:i.map(d=>Un(d,t))}}if(on(r))return t.errors.push({code:"inline-reserved",component:r,path:"",message:`${r}() must be declared as a top-level statement, not used inline as a value`,statementId:t.currentStatementId}),null;const a=(n=t.cat)==null?void 0:n.get(r),o={};if(a){for(let d=0;d<a.params.length&&d<i.length;d++)o[a.params[d].name]=mt(i[d],t);if(i.length>a.params.length){const d=i.length-a.params.length;t.errors.push({code:"excess-args",component:r,path:"",message:`${r} takes ${a.params.length} arg(s), got ${i.length} (${d} excess dropped)`,statementId:t.currentStatementId})}const c=a.params.filter(d=>d.required&&(!(d.name in o)||o[d.name]===null));if(c.length){const d=c.filter(g=>g.defaultValue!==void 0?(o[g.name]=g.defaultValue,!1):!0);if(d.length){for(const g of d){const h=g.name in o;t.errors.push({code:h?"null-required":"missing-required",component:r,path:`/${g.name}`,message:h?`required field "${g.name}" cannot be null`:`missing required field "${g.name}"`,statementId:t.currentStatementId})}return null}}}else if(!Ot(r)&&!on(r))return t.errors.push({code:"unknown-component",component:r,path:"",message:`Unknown component "${r}" — not found in catalog or builtins`,statementId:t.currentStatementId}),null;const l=Object.values(o).some(c=>Kt(c));return{type:"element",typeName:r,props:o,partial:t.partial,hasDynamicProps:l}}default:return ep(e)?Un(e,t):e}}function ip(e){const t=[];let n=!1,r=!1;for(let a=0;a<e.length;a++){const o=e[a];if(r){r=!1;continue}if(o==="\\"&&n){r=!0;continue}if(n){o===n&&(n=!1);continue}if(o==='"'||o==="'"){n=o;continue}o==="("||o==="["||o==="{"?t.push(o):(o===")"&&t[t.length-1]==="("||o==="]"&&t[t.length-1]==="["||o==="}"&&t[t.length-1]==="{")&&t.pop()}if(!(n||t.length>0))return{text:e,wasIncomplete:!1};let i=e;n&&(r&&(i+="\\"),i+=n);for(let a=t.length-1;a>=0;a--)i+=t[a]==="("?")":t[a]==="["?"]":"}";return{text:i,wasIncomplete:!0}}function Js(e){const t=[];let n=0;for(;n<e.length;){for(;n<e.length&&e[n].t===S.Newline;)n++;if(n>=e.length||e[n].t===S.EOF)break;const r=e[n];if(r.t!==S.Ident&&r.t!==S.Type&&r.t!==S.StateVar){for(;n<e.length&&e[n].t!==S.Newline&&e[n].t!==S.EOF;)n++;continue}const i=r.v,a=r.t;if(n++,n>=e.length||e[n].t!==S.Equals){for(;n<e.length&&e[n].t!==S.Newline&&e[n].t!==S.EOF;)n++;continue}n++;const o=[];let l=0,c=0;for(;n<e.length&&e[n].t!==S.EOF;){const d=e[n].t;if(d===S.Newline&&l<=0&&c<=0){let g=n+1;for(;g<e.length&&e[g].t===S.Newline;)g++;const h=g<e.length?e[g].t:S.EOF;if(h===S.Question||h===S.Colon&&c>0){n++;continue}break}if(d===S.Newline){n++;continue}d===S.LParen||d===S.LBrack||d===S.LBrace?l++:(d===S.RParen||d===S.RBrack||d===S.RBrace)&&l>0?l--:d===S.Question&&l===0?c++:d===S.Colon&&l===0&&c>0&&c--,o.push(e[n++])}o.length&&t.push({id:i,idTokenType:a,tokens:o})}return t}function Jt(e=!0){return{root:null,meta:{incomplete:e,unresolved:[],orphaned:[],statementCount:0,errors:[]},stateDeclarations:{},queryStatements:[],mutationStatements:[]}}function di(e){if(!ht(e))return[];const t=new Set;return np(e,n=>{n.k==="StateRef"&&t.add(n.n)}),[...t]}function Hs(e,t){if(t.k==="Comp"&&t.name===Ye.Query){const n=di(t.args[1]);return{kind:"query",id:e.id,call:{callee:Ye.Query,args:t.args},expr:t,deps:n.length>0?n:void 0}}return t.k==="Comp"&&t.name===Ye.Mutation?{kind:"mutation",id:e.id,call:{callee:Ye.Mutation,args:t.args},expr:t}:e.idTokenType===S.StateVar?{kind:"state",id:e.id,init:t}:{kind:"value",id:e.id,expr:t}}function ap(e,t){const n={},r=[],i=[];for(const a of e)switch(a.kind){case"state":n[a.id]=mt(a.init,t);break;case"query":r.push({statementId:a.id,toolAST:a.call.args[0]??null,argsAST:a.call.args[1]??null,defaultsAST:a.call.args[2]??null,refreshAST:a.call.args[3]??null,deps:a.deps,complete:!0});break;case"mutation":i.push({statementId:a.id,toolAST:a.call.args[0]??null,argsAST:a.call.args[1]??null});break}for(const a of e){const o=a.kind==="state"?[a.init]:a.kind==="value"?[a.expr]:a.kind==="query"||a.kind==="mutation"?a.call.args:[];for(const l of o)for(const c of di(l))c in n||(n[c]=null)}return{stateDeclarations:n,queryStatements:r,mutationStatements:i}}const Ys="root";function Xs(e){return e.kind==="value"&&e.expr.k==="Comp"&&!Ot(e.expr.name)&&e.expr.name!==Ye.Query&&e.expr.name!==Ye.Mutation}function op(e,t,n,r){var a;if(e.has(Ys))return Ys;if(r&&e.has(r))return r;const i=r?t.find(o=>Xs(o)&&o.expr.name===r):void 0;return i?i.id:((a=t.find(Xs))==null?void 0:a.id)??n}function Gt(e,t,n,r,i,a,o){const l=op(e,t,n,o);if(!e.has(l))return Jt(r);const c=new Map;for(const[b,x]of e)c.set(b,x.kind==="state"?x.init:x.expr);const d=[],g=[],h=new Set;for(const[b,x]of e)b!==l&&(x.kind==="state"||x.kind==="query"||x.kind==="mutation"||h.add(b));const u={syms:c,cat:a,errors:g,unres:d,visited:new Set,partial:r,currentStatementId:l,unreached:h},p=mt(c.get(l),u),v=Ke(p)?p:null;v&&(v.statementId=l);const{stateDeclarations:y,queryStatements:w,mutationStatements:m}=ap(t,u);return{root:v,meta:{incomplete:r,unresolved:d,orphaned:[...h],statementCount:i,errors:g},stateDeclarations:y,queryStatements:w,mutationStatements:m}}function lp(e){const t=[];let n=0;for(;n<e.length;){const r=e.indexOf("```",n);if(r===-1)break;let i=r+3;for(;i<e.length&&e[i]!==`
280
280
  `;)i++;if(i>=e.length){t.push(e.slice(r+3).replace(/^[^\n]*\n?/,"")),n=e.length;break}i++;let a=!1,o=-1,l=i;for(;l<e.length;){const c=e[l];if(a){if(c==="\\"&&l+1<e.length){l+=2;continue}c==='"'&&(a=!1),l++;continue}if(c==='"'){a=!0,l++;continue}if(c==="`"&&l+1<e.length&&e[l+1]==="`"&&l+2<e.length&&e[l+2]==="`"){o=l;break}l++}o!==-1?(t.push(e.slice(i,o)),n=o+3):(t.push(e.slice(i)),n=e.length)}if(t.length>0)return t.join(`
281
281
  `);if(e.startsWith("```")){let r=3;for(;r<e.length&&e[r]!==`
282
282
  `;)r++;const i=r<e.length?r+1:3,a=e.slice(i),o=a.lastIndexOf("```");return o!==-1?a.slice(0,o):a}return e}function er(e){return e.split(`
283
283
  `).map(t=>{let n=!1;for(let r=0;r<t.length;r++){const i=t[r];if(n){if(i==="\\"&&r+1<t.length){r++;continue}i===n&&(n=!1);continue}if(i==='"'||i==="'"){n=i;continue}if(i==="/"&&t[r+1]==="/"||i==="#")return t.substring(0,r).trimEnd()}return t}).join(`
284
- `)}function lp(e,t){let n="",r=0;const i=new Map;let a=0,o="";function l(h){const u=er(h).trim();if(!(!u||/^```/.test(u)))for(const p of Js(Ks(u))){const v=Ys(p,Qs(p.tokens));i.set(p.id,v),a++,o||(o=p.id)}}function c(){let h=0,u=0,p=!1,v=!1,y=r;for(let w=r;w<n.length;w++){const m=n[w];if(v){v=!1;continue}if(m==="\\"&&p){v=!0;continue}if(p){m===p&&(p=!1);continue}if(m==='"'||m==="'"){p=m;continue}if(m==="("||m==="["||m==="{")h++;else if(m===")"||m==="]"||m==="}")h=Math.max(0,h-1);else if(m==="?"&&h===0)u++;else if(m===":"&&h===0&&u>0)u--;else if(m===`
284
+ `)}function cp(e,t){let n="",r=0;const i=new Map;let a=0,o="";function l(h){const u=er(h).trim();if(!(!u||/^```/.test(u)))for(const p of Js(Ks(u))){const v=Hs(p,Qs(p.tokens));i.set(p.id,v),a++,o||(o=p.id)}}function c(){let h=0,u=0,p=!1,v=!1,y=r;for(let w=r;w<n.length;w++){const m=n[w];if(v){v=!1;continue}if(m==="\\"&&p){v=!0;continue}if(p){m===p&&(p=!1);continue}if(m==='"'||m==="'"){p=m;continue}if(m==="("||m==="["||m==="{")h++;else if(m===")"||m==="]"||m==="}")h=Math.max(0,h-1);else if(m==="?"&&h===0)u++;else if(m===":"&&h===0&&u>0)u--;else if(m===`
285
285
  `&&h<=0&&u<=0){let b=w+1;for(;b<n.length&&(n[b]===" "||n[b]===" "||n[b]==="\r"||n[b]===`
286
- `);)b++;if(b<n.length&&(n[b]==="?"||n[b]===":"&&u>0))continue;const x=n.slice(y,w).trim();x&&l(x),y=w+1,r=w+1}}return y}function d(){const h=c(),u=n.slice(h).trim();if(!u)return a===0?Jt():Gt(i,[...i.values()],o,!1,a,e,t);const p=er(op(u)).trim();if(!p)return a===0?Jt():Gt(i,[...i.values()],o,!1,a,e,t);const{text:v,wasIncomplete:y}=rp(p),w=Js(Ks(v));if(!w.length)return a===0?Jt(y):Gt(i,[...i.values()],o,y,a,e,t);const m=new Map(i);for(const b of w){if(i.has(b.id))continue;const x=Ys(b,Qs(b.tokens));m.set(b.id,x)}return Gt(m,[...m.values()],o||w[0].id,y,a+w.length,e,t)}function g(){n="",r=0,i.clear(),a=0,o=""}return{push(h){return n+=h,d()},set(h){(h.length<n.length||!h.startsWith(n))&&g();const u=h.slice(n.length);return u&&(n+=u),d()},getResult:d}}function cp(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e.default}function up(e){const t=new Map,n=e.$defs??{};for(const[r,i]of Object.entries(n)){const a=i.properties??{},o=i.required??[],l=Object.keys(a).map(c=>({name:c,required:o.includes(c),defaultValue:cp(a[c])}));t.set(r,{params:l})}return t}function dp(e,t){return lp(up(e),t)}function pp(e,t){if(!(t!=null&&t.properties))return;const n=new Set(t.required??[]);return`Signature: ${e}(${Object.keys(t.properties).map(r=>n.has(r)?`${r}*`:r).join(", ")}) — * marks required`}function hp(e,t,n){return e.map(r=>{var a;const i={source:"parser",code:r.code,message:r.message,component:r.component,path:r.path||void 0,statementId:r.statementId};return r.code==="unknown-component"&&n.length?i.hint=`Available components: ${n.join(", ")}`:r.code==="missing-required"||r.code==="null-required"?i.hint=pp(r.component,(a=t.$defs)==null?void 0:a[r.component]):r.code==="inline-reserved"&&(i.hint=`Declare as a top-level statement: myVar = ${r.component}(...)`),i})}function mp(e){return typeof e=="object"&&e!==null&&e.__reactive==="assign"}function oe(e,t,n){var r,i,a;switch(e.k){case"Str":return e.v;case"Num":return e.v;case"Bool":return e.v;case"Null":return null;case"Ph":return null;case"StateRef":return((r=t.extraScope)==null?void 0:r[e.n])??t.getState(e.n);case"Ref":case"RuntimeRef":return t.resolveRef(e.n);case"Arr":return e.els.map(o=>oe(o,t));case"Obj":return Object.fromEntries(e.entries.map(([o,l])=>[o,oe(l,t)]));case"Comp":{if(is.has(e.name))return gp(e.name,e.args,t,n);const o=rs[e.name];if(o){const l=e.args.map(c=>oe(c,t));return o.fn(...l)}if(si.has(e.name))return fp(e.name,e.args,t);if(e.mappedProps){const l=n==null?void 0:n.library.components[e.name],c={};for(const[g,h]of Object.entries(e.mappedProps)){const u=(a=(i=l==null?void 0:l.props)==null?void 0:i.shape)==null?void 0:a[g];h.k==="StateRef"&&u&&_t(u)?c[g]={__reactive:"assign",target:h.n,expr:{k:"StateRef",n:"$value"}}:h.k==="StateRef"?c[g]=n?t.getState(h.n):h:c[g]=oe(h,t,n)}const d={type:"element",typeName:e.name,props:c,partial:!1,hasDynamicProps:!0};if(n)for(const[g,h]of Object.entries(c))Ke(h)?c[g]=cn(h,t,n):Array.isArray(h)&&(c[g]=h.map(u=>Ke(u)?cn(u,t,n):u));return d}return console.warn(`[openui] Unexpected unmapped Comp node: ${e.name}`),null}case"BinOp":{if(e.op==="&&"){const c=oe(e.left,t);return c&&oe(e.right,t)}if(e.op==="||"){const c=oe(e.left,t);return c||oe(e.right,t)}const o=oe(e.left,t),l=oe(e.right,t);switch(e.op){case"+":return typeof o=="string"||typeof l=="string"?String(o??"")+String(l??""):ee(o)+ee(l);case"-":return ee(o)-ee(l);case"*":return ee(o)*ee(l);case"/":return ee(l)===0?0:ee(o)/ee(l);case"%":return ee(l)===0?0:ee(o)%ee(l);case"==":return o==l;case"!=":return o!=l;case">":return ee(o)>ee(l);case"<":return ee(o)<ee(l);case">=":return ee(o)>=ee(l);case"<=":return ee(o)<=ee(l);default:return null}}case"UnaryOp":return e.op==="!"?!oe(e.operand,t):e.op==="-"?-ee(oe(e.operand,t)):null;case"Ternary":return oe(e.cond,t)?oe(e.then,t):oe(e.else,t);case"Member":{const o=oe(e.obj,t);return o==null?null:Array.isArray(o)?e.field==="length"?o.length:o.map(l=>(l==null?void 0:l[e.field])??null):o[e.field]}case"Index":{const o=oe(e.obj,t),l=oe(e.index,t);return o==null||l==null?null:Array.isArray(o)?o[ee(l)]:o[String(l)]}case"Assign":return{__reactive:"assign",target:e.target,expr:e.value}}}function cn(e,t,n){var a,o;if(e.hasDynamicProps===!1)return e;const r=n.library.components[e.typeName],i={};for(const[l,c]of Object.entries(e.props)){const d=(o=(a=r==null?void 0:r.props)==null?void 0:a.shape)==null?void 0:o[l];i[l]=di(c,t,n,d)}return{...e,props:i}}function di(e,t,n,r){return pi(e,t,n,r,{recurseElement:i=>cn(i,t,n),recurse:(i,a)=>di(i,t,n,a)})}function Dn(e){return e==null?{k:"Null"}:typeof e=="string"?{k:"Str",v:e}:typeof e=="number"?{k:"Num",v:e}:typeof e=="boolean"?{k:"Bool",v:e}:Array.isArray(e)?{k:"Arr",els:e.map(Dn)}:typeof e=="object"?{k:"Obj",entries:Object.entries(e).map(([t,n])=>[t,Dn(n)])}:{k:"Null"}}function fp(e,t,n){switch(e){case"Action":{const r=t.length>0?oe(t[0],n):[];return{steps:(Array.isArray(r)?r:[]).filter(i=>i!=null&&typeof i=="object"&&"type"in i)}}case"Run":{if(t.length===0)return null;const r=t[0];return r.k==="RuntimeRef"?{type:Ue.Run,statementId:r.n,refType:r.refType}:null}case"ToAssistant":{const r=t.length>0?String(oe(t[0],n)??""):"",i=t.length>1?String(oe(t[1],n)??""):void 0;return{type:Ue.ToAssistant,message:r,context:i}}case"OpenUrl":{const r=t.length>0?String(oe(t[0],n)??""):"";return{type:Ue.OpenUrl,url:r}}case"Set":{if(t.length<2)return null;const r=t[0];return r.k!=="StateRef"?null:{type:Ue.Set,target:r.n,valueAST:t[1]}}case"Reset":{const r=t.filter(i=>i.k==="StateRef").map(i=>i.n);return r.length===0?null:{type:Ue.Reset,targets:r}}default:return null}}function _e(e,t,n){switch(e.k){case"Ref":return e.n===t?Dn(n):e;case"Member":if(ht(e.obj)){const r=_e(e.obj,t,n);if(r.k==="Obj"){const i=r.entries.find(([a])=>a===e.field);if(i)return i[1]}return{...e,obj:r}}return e;case"Index":return{...e,obj:ht(e.obj)?_e(e.obj,t,n):e.obj,index:ht(e.index)?_e(e.index,t,n):e.index};case"BinOp":return{...e,left:_e(e.left,t,n),right:_e(e.right,t,n)};case"UnaryOp":return{...e,operand:_e(e.operand,t,n)};case"Ternary":return{...e,cond:_e(e.cond,t,n),then:_e(e.then,t,n),else:_e(e.else,t,n)};case"Arr":return{...e,els:e.els.map(r=>_e(r,t,n))};case"Obj":return{...e,entries:e.entries.map(([r,i])=>[r,_e(i,t,n)])};case"Comp":{const r={...e,args:e.args.map(i=>_e(i,t,n))};if(e.mappedProps){const i={};for(const[a,o]of Object.entries(e.mappedProps))i[a]=_e(o,t,n);r.mappedProps=i}return r}case"Assign":return{...e,value:_e(e.value,t,n)};default:return e}}function gp(e,t,n,r){if(e==="Each"){if(t.length<3)return[];const i=oe(t[0],n);if(!Array.isArray(i))return[];const a=t[1].k==="Ref"?t[1].n:t[1].k==="Str"?t[1].v:null;if(!a)return[];const o=t[2];return i.map((l,c)=>{const d=_e(o,a,l),g={...n,resolveRef:u=>u===a?l:n.resolveRef(u)},h=oe(d,g,r);return r&&Ke(h)?cn(h,g,r):h})}return null}function pi(e,t,n,r,i){if(e==null||typeof e!="object")return e;if(ht(e)){if(e.k==="StateRef"&&r&&_t(r))return{__reactive:"assign",target:e.n,expr:{k:"StateRef",n:"$value"}};const l=oe(e,t,n);return Ke(l)?i.recurseElement(l):Array.isArray(l)?l.map(c=>Ke(c)?i.recurseElement(c):c):mp(l)&&!(r&&_t(r))?t.getState(l.target)??null:l}if(typeof e=="string"&&r&&_t(r))return e;if(Array.isArray(e))return e.map(l=>i.recurse(l,r));if(Ke(e))return i.recurseElement(e);const a=e;if("steps"in a&&Array.isArray(a.steps)||"type"in a&&"valueAST"in a)return e;let o=!1;for(const l of Object.values(a))if(typeof l=="object"&&l!==null){o=!0;break}if(o){const l={};for(const[c,d]of Object.entries(a))l[c]=i.recurse(d,r);return l}return e}function hi(e,t){var a,o,l;if(e.hasDynamicProps===!1)return e;const n={library:t.library},r=t.library.components[e.typeName],i={};for(const[c,d]of Object.entries(e.props)){const g=(o=(a=r==null?void 0:r.props)==null?void 0:a.shape)==null?void 0:o[c];try{i[c]=mi(d,t,n,g)}catch(h){i[c]=d;const u=h instanceof Error?h.message:String(h);(l=t.errors)==null||l.push({source:"runtime",code:"runtime-error",component:e.typeName,statementId:e.statementId,message:`Evaluating prop "${c}" on ${e.typeName} failed: ${u}`,hint:`Check the expression used for prop "${c}"`})}}return{...e,props:i}}function mi(e,t,n,r){return pi(e,t.ctx,n,r,{recurseElement:i=>hi(i,t),recurse:(i,a)=>mi(i,t,n,a)})}var Zn=class extends Error{constructor(t){super(`MCP tool error: ${t||"Unknown error"}`);xt(this,"toolErrorText");this.name="McpToolError",this.toolErrorText=t}};function vp(e){var n,r;if(e.isError){const i=(n=e.content)==null?void 0:n.filter(a=>a.type==="text").map(a=>a.text).join(`
287
- `);throw new Zn(i||"Unknown error")}if(e.structuredContent!=null)return e.structuredContent;const t=(r=e.content)==null?void 0:r.filter(i=>i.type==="text").map(i=>i.text??"");if(t!=null&&t.length){const i=t.join("");try{return JSON.parse(i)}catch{return i}}return null}var qn=class extends Error{constructor(t,n=[]){super(`[openui] No handler for tool "${t}". Available: ${n.join(", ")||"(none)"}`);xt(this,"toolName");xt(this,"availableTools");this.name="ToolNotFoundError",this.toolName=t,this.availableTools=n}};function tr(e){return JSON.stringify(e,(t,n)=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const r={};for(const i of Object.keys(n).sort())r[i]=n[i];return r}if(n===void 0)return"__undefined__";if(typeof n=="number"){if(Number.isNaN(n))return"__NaN__";if(n===1/0)return"__Inf__";if(n===-1/0)return"__-Inf__"}return n})}function bp(e,t,n){const r=n!=null?"::"+tr(n):"";return e+"::"+tr(t)+r}function yp(e){const t=new Map,n=new Map,r=new Map,i=new Set;let a={__openui_loading:[],__openui_refetching:[],__openui_errors:[]},o=JSON.stringify(a),l=!1,c=0;function d(){const E={__openui_loading:[],__openui_refetching:[],__openui_errors:[]};for(const[T,$]of t){const O=r.get($.cacheKey);if(O&&O.data!==void 0)E[T]=O.data;else if($.prevCacheKey){const Z=r.get($.prevCacheKey);Z&&Z.data!==void 0?E[T]=Z.data:E[T]=$.defaults}else E[T]=$.defaults;$.loading&&(E.__openui_loading.push(T),$.everFetched&&E.__openui_refetching.push(T)),$.error&&E.__openui_errors.push($.error)}for(const[T,$]of n)E[T]=$.result,$.error&&E.__openui_errors.push($.error);try{const T=JSON.stringify(E);if(T===o)return!1;a=E,o=T}catch{a=E,o=""}return!0}function g(){for(const E of[...i])E()}async function h(E,T){if(!e)return;const $=t.get(T);if(!$)return;const O=E,Z=$.toolName,C=$.args;let R=r.get(O);R?R.inFlight=!0:(R={data:void 0,inFlight:!0},r.set(O,R)),$.loading=!0,d(),g();try{const G=await e.callTool(Z,C??{});if(l)return;const P=t.get(T);if(!P||P.cacheKey!==O){R.inFlight=!1;return}if(R.data=G??null,P.everFetched=!0,P.error=void 0,P.prevCacheKey&&P.prevCacheKey!==O){const L=P.prevCacheKey;P.prevCacheKey=void 0,u(L)}}catch(G){const P=t.get(T);P&&P.cacheKey===O&&(G instanceof qn?P.error={source:"query",code:"tool-not-found",message:`Query tool "${Z}" not found`,statementId:T,component:"Query",toolName:Z,hint:G.availableTools.length?`Available tools: ${G.availableTools.join(", ")}`:void 0}:G instanceof Zn?P.error={source:"query",code:"mcp-error",message:`Query "${Z}" returned an error: ${G.toolErrorText}`,statementId:T,component:"Query",toolName:Z}:P.error={source:"query",code:"tool-error",message:`Query "${Z}" failed: ${G instanceof Error?G.message:String(G)}`,statementId:T,component:"Query",toolName:Z}),console.error(`Query "${Z}" failed:`,G)}finally{R.inFlight=!1;const G=t.get(T);G&&G.cacheKey===O?(G.loading=!1,d()&&g(),G.needsRefetch&&(G.needsRefetch=!1,h(G.cacheKey,T))):d()&&g()}}function u(E){for(const T of t.values())if(T.cacheKey===E||T.prevCacheKey===E)return;r.delete(E)}function p(E){if(l)return;const T=new Set(E.map($=>$.statementId));for(const[$,O]of t)T.has($)||(O.timer&&clearInterval(O.timer),t.delete($),u(O.cacheKey),O.prevCacheKey&&u(O.prevCacheKey));for(const $ of E){if(!$.complete)continue;const O=bp($.toolName,$.args,$.deps),Z=t.get($.statementId);Z?(Z.cacheKey!==O&&(Z.prevCacheKey=Z.cacheKey),Z.toolName=$.toolName,Z.args=$.args,Z.defaults=$.defaults,Z.cacheKey=O):t.set($.statementId,{toolName:$.toolName,args:$.args,defaults:$.defaults,cacheKey:O,loading:!1,everFetched:!1,refreshInterval:0,needsRefetch:!1});const C=t.get($.statementId),R=r.get(O),G=R&&R.data!==void 0&&!R.inFlight;e&&!G&&!(R!=null&&R.inFlight)&&h(O,$.statementId);const P=$.refreshInterval??0;P!==C.refreshInterval&&(C.timer&&(clearInterval(C.timer),C.timer=void 0),P>0&&(C.timer=setInterval(()=>{var L;l||!e||(L=r.get(C.cacheKey))!=null&&L.inFlight||h(C.cacheKey,$.statementId)},P*1e3)),C.refreshInterval=P)}d()&&g()}function v(E){const T=t.get(E);if(!T)return null;const $=r.get(T.cacheKey);if($&&$.data!==void 0)return $.data;if(T.prevCacheKey){const O=r.get(T.prevCacheKey);if(O&&O.data!==void 0)return O.data}return T.defaults}function y(E){var T;return((T=t.get(E))==null?void 0:T.loading)??!1}function w(){for(const E of t.values())if(E.loading)return!0;return!1}function m(E){var $;if(l||!e)return;const T=E!=null&&E.length?E.filter(O=>t.has(O)):[...t.keys()];for(const O of T){const Z=t.get(O);Z&&(($=r.get(Z.cacheKey))!=null&&$.inFlight?Z.needsRefetch=!0:h(Z.cacheKey,O))}}function b(E){const T=new Set(E.map($=>$.statementId));for(const $ of n.keys())T.has($)||n.delete($);for(const $ of E){const O=n.get($.statementId);O?O.toolName!==$.toolName&&(O.toolName=$.toolName,O.result={status:"idle",data:null,error:null},O.error=void 0):n.set($.statementId,{toolName:$.toolName,result:{status:"idle"}})}d()&&g()}async function x(E,T,$){if(l||!e)return!1;const O=n.get(E);if(!O||O.result.status==="loading")return!1;const Z=c;O.result={status:"loading"},d(),g();let C=!1;try{const R=await e.callTool(O.toolName,T);if(l||Z!==c)return!1;O.result={status:"success",data:R},O.error=void 0,C=!0}catch(R){if(l||Z!==c)return!1;const G=R instanceof Error?R.message:String(R);O.result={status:"error",error:G},R instanceof qn?O.error={source:"mutation",code:"tool-not-found",message:`Mutation tool "${O.toolName}" not found`,statementId:E,component:"Mutation",toolName:O.toolName,hint:R.availableTools.length?`Available tools: ${R.availableTools.join(", ")}`:void 0}:R instanceof Zn?O.error={source:"mutation",code:"mcp-error",message:`Mutation "${O.toolName}" returned an error: ${R.toolErrorText}`,statementId:E,component:"Mutation",toolName:O.toolName}:O.error={source:"mutation",code:"tool-error",message:`Mutation "${O.toolName}" failed: ${G}`,statementId:E,component:"Mutation",toolName:O.toolName}}return d(),g(),C&&($!=null&&$.length)&&m($),C}function k(E){var T;return((T=n.get(E))==null?void 0:T.result)??null}function S(E){return i.add(E),()=>i.delete(E)}function j(){return a}function _(){l=!1}function z(){l=!0,c++,i.clear();for(const E of t.values())E.timer&&(clearInterval(E.timer),E.timer=void 0),E.loading=!1,E.needsRefetch=!1;n.clear()}return{evaluateQueries:p,getResult:v,isLoading:y,isAnyLoading:w,invalidate:m,registerMutations:b,fireMutation:x,getMutationResult:k,subscribe:S,getSnapshot:j,activate:_,dispose:z}}function xp(){const e=new Map,t=new Set;let n={};function r(){const h=[...t];for(const u of h)u()}function i(){n=Object.fromEntries(e)}function a(h){return e.get(h)}function o(h,u){const p=e.get(h);if(!Object.is(p,u)){if(u&&p&&typeof u=="object"&&typeof p=="object"&&!Array.isArray(u)&&!Array.isArray(p)){const v=Object.keys(u),y=Object.keys(p);if(v.length===y.length&&v.every(w=>Object.is(u[w],p[w])))return}e.set(h,u),i(),r()}}function l(h){return t.add(h),()=>{t.delete(h)}}function c(){return n}function d(h,u){for(const p of Object.keys(u))e.set(p,u[p]);for(const p of Object.keys(h))e.has(p)||e.set(p,h[p]);i(),r()}function g(){e.clear(),t.clear(),n={}}return{get:a,set:o,subscribe:l,getSnapshot:c,initialize:d,dispose:g}}function Le(e){return Gd(e)}function jp(e){return Hd(e)}const fi=f.createContext(null);function gi(){const e=f.useContext(fi);if(!e)throw new Error("useOpenUI must be used within a <Renderer /> component.");return e}function wp(){return gi().renderNode}f.createContext(void 0);function En(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e?e.value:e}function kp({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:o,onError:l},c){const d=f.useMemo(()=>dp(t.toJSONSchema(),t.root),[t]),g=f.useRef(null),h=f.useMemo(()=>{if(g.current=null,!e)return null;try{return d.set(e)}catch(P){return g.current={source:"parser",code:"parse-exception",message:`Parser crashed: ${P instanceof Error?P.message:String(P)}`,hint:"The response may contain syntax the parser cannot handle"},null}},[d,e]),u=f.useMemo(()=>xp(),[]),p=f.useMemo(()=>yp(o??null),[o]);f.useEffect(()=>(p.activate(),()=>p.dispose()),[p]);const v=f.useRef(Symbol());f.useEffect(()=>{if(!(h!=null&&h.stateDeclarations)&&!a)return;const P=`${JSON.stringify(h==null?void 0:h.stateDeclarations)}::${JSON.stringify(a)}`;if(v.current===P)return;v.current=P;const L={};if(a)for(const[A,M]of Object.entries(a))A.startsWith("$")?L[A]=M:u.set(A,M);u.initialize((h==null?void 0:h.stateDeclarations)??{},L)},[h==null?void 0:h.stateDeclarations,u,a]);const y=f.useSyncExternalStore(u.subscribe,u.getSnapshot,u.getSnapshot),w=f.useSyncExternalStore(p.subscribe,p.getSnapshot,p.getSnapshot),m=f.useMemo(()=>({getState:P=>En(u.get(P)),resolveRef:P=>{const L=p.getMutationResult(P);return L||p.getResult(P)}}),[u,p]);f.useEffect(()=>{if(n)return;const P=((h==null?void 0:h.queryStatements)??[]).map(L=>{const A={};if(L.deps)for(const M of L.deps)A[M]=y[M];return{statementId:L.statementId,toolName:L.toolAST?oe(L.toolAST,m):"",args:L.argsAST?oe(L.argsAST,m):null,defaults:L.defaultsAST?oe(L.defaultsAST,m):null,refreshInterval:L.refreshAST?oe(L.refreshAST,m):void 0,deps:Object.keys(A).length>0?A:void 0,complete:L.complete}});p.evaluateQueries(P)},[n,h==null?void 0:h.queryStatements,m,p,y]),f.useEffect(()=>{if(n)return;const P=((h==null?void 0:h.mutationStatements)??[]).map(L=>({statementId:L.statementId,toolName:L.toolAST?oe(L.toolAST,m):""}));p.registerMutations(P)},[n,h==null?void 0:h.mutationStatements,m,p]);const b=f.useRef({onAction:r,onStateUpdate:i,onError:l});b.current={onAction:r,onStateUpdate:i,onError:l};const x=f.useRef(h);x.current=h;const k=f.useRef(null);f.useEffect(()=>(k.current=u.getSnapshot(),u.subscribe(()=>{var L,A;const P=u.getSnapshot();P!==k.current&&(k.current=null,(A=(L=b.current).onStateUpdate)==null||A.call(L,P))})),[u]);const S=f.useCallback((P,L)=>{if(!P)return En(u.get(L));const A=u.get(P);if(!(!A||typeof A!="object"||Array.isArray(A)))return En(A[L])},[u]),j=f.useCallback((P,L,A,M,F=!0)=>{var J,X;const B={value:M,componentType:L};if(!P)u.set(A,B);else{const H=u.get(P),V=H&&typeof H=="object"&&!Array.isArray(H)?H:{};u.set(P,{...V,[A]:B})}F&&((X=(J=b.current).onStateUpdate)==null||X.call(J,u.getSnapshot()))},[u]),_=f.useCallback(P=>{if(P){const L=u.get(P);if(L&&typeof L=="object"&&!Array.isArray(L))return{[P]:L}}return u.getSnapshot()},[u]),z=f.useCallback(async(P,L,A)=>{var J,X,H;const M=_(L),{onAction:F}=b.current;if(A&&!("steps"in A)){const V=A.type||Zt.ContinueConversation,re={...A.params||{}};A.url&&(re.url=A.url),A.context&&(re.context=A.context),F==null||F({type:V,params:re,humanFriendlyMessage:P,formState:M,formName:L});return}const B=A;if(B!=null&&B.steps){for(const V of B.steps)switch(V.type){case Ue.Run:if(V.refType==="mutation"){const re=(X=(J=x.current)==null?void 0:J.mutationStatements)==null?void 0:X.find(Ne=>Ne.statementId===V.statementId),ye=re!=null&&re.argsAST?oe(re.argsAST,m):{};if(!await p.fireMutation(V.statementId,ye))return}else p.invalidate([V.statementId]);break;case Ue.ToAssistant:F==null||F({type:Zt.ContinueConversation,params:V.context?{context:V.context}:{},humanFriendlyMessage:V.message,formState:M,formName:L});break;case Ue.OpenUrl:F==null||F({type:Zt.OpenUrl,params:{url:V.url},humanFriendlyMessage:"",formState:M,formName:L});break;case Ue.Set:{if(!V.valueAST){console.warn(`[openui] Set action for ${V.target} has no valueAST — skipping`);break}const re=oe(V.valueAST,m);u.set(V.target,re);break}case Ue.Reset:{const re=((H=x.current)==null?void 0:H.stateDeclarations)??{};for(const ye of V.targets)u.set(ye,re[ye]??null);break}}return}F==null||F({type:Zt.ContinueConversation,params:{},humanFriendlyMessage:P,formState:M,formName:L})},[p,m,_,u]),E=f.useRef([]),T=f.useRef(n);T.current=n;const $=f.useCallback(P=>{T.current||E.current.push(P)},[]),O=f.useMemo(()=>({library:t,renderNode:c,triggerAction:z,isStreaming:n,getFieldValue:S,setFieldValue:j,store:u,evaluationContext:m,reportError:$}),[t,c,n,z,S,j,u,m,$]),Z=f.useRef([]),C=f.useMemo(()=>{if(!(h!=null&&h.root))return h;const P=[],L={ctx:m,library:t,store:u,errors:P};try{const A=hi(h.root,L);return Z.current=P,{...h,root:A}}catch(A){const M=A instanceof Error?A.message:String(A);return P.push({source:"runtime",code:"runtime-error",message:`Prop evaluation failed: ${M}`}),Z.current=P,h}},[h,m,t,u,y,w]),R=w.__openui_loading.length>0,G=f.useRef("");return f.useEffect(()=>{var A,M,F,B;if(n){G.current!==""&&(G.current="",(M=(A=b.current).onError)==null||M.call(A,[]));return}const P=[];g.current&&P.push(g.current),e&&!(h!=null&&h.root)&&!g.current&&P.push({source:"parser",code:"parse-failed",message:h?"Code parsed but produced no renderable root component":"Response could not be parsed as valid openui-lang",hint:`The entire response must be valid openui-lang code starting with root = ${t.root??"Root"}(...)`}),(B=(F=h==null?void 0:h.meta)==null?void 0:F.errors)!=null&&B.length&&P.push(...hp(h.meta.errors,t.toJSONSchema(),Object.keys(t.components))),P.push(...Z.current),P.push(...E.current),E.current=[],P.push(...w.__openui_errors??[]);const L=JSON.stringify(P);if(L!==G.current){if(G.current=L,b.current.onError)b.current.onError(P);else if(P.length>0)for(const J of P)console.warn(`[openui] ${J.source}/${J.code}: ${J.message}`)}},[n,e,h,C,w,t]),{result:C,parseResult:h,contextValue:O,isQueryLoading:R}}var Np=class extends f.Component{constructor(t){super(t);xt(this,"lastValidChildren",null);this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidMount(){this.state.hasError||(this.lastValidChildren=this.props.children)}componentDidUpdate(t){this.state.hasError||(this.lastValidChildren=this.props.children),this.state.hasError&&t.children!==this.props.children&&this.setState({hasError:!1})}componentDidCatch(t){var r,i;const n=this.props.componentName??"Unknown";(i=(r=this.props).onError)==null||i.call(r,{source:"runtime",code:"render-error",component:n,message:`Component ${n} render failed: ${t.message}`})}render(){return this.state.hasError?this.lastValidChildren:this.props.children}};function vi(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map((t,n)=>s.jsx(f.Fragment,{children:vi(t)},n));if(typeof e=="object"&&e!==null){const t=e;if(t.type==="element")return s.jsx(bi,{node:t})}return null}function bi({node:e}){var i;const{library:t,reportError:n}=gi(),r=(i=t.components[e.typeName])==null?void 0:i.component;return r?s.jsx(Np,{componentName:e.typeName,onError:n,children:s.jsx(Sp,{el:e,Comp:r})}):null}function Sp({el:e,Comp:t}){const n=wp();return s.jsx(t,{props:e.props,renderNode:n})}let nr=!1;function Cp(){if(nr||typeof document>"u")return;nr=!0;const e=document.createElement("style");e.textContent="@keyframes openui-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }",document.head.appendChild(e)}const $p=()=>s.jsx("div",{style:{position:"absolute",top:8,right:8,width:16,height:16,border:"2px solid #e5e7eb",borderTopColor:"#3b82f6",borderRadius:"50%",animation:"openui-spin 0.6s linear infinite",zIndex:10}});function Ep({response:e,library:t,isStreaming:n=!1,onAction:r,onStateUpdate:i,initialState:a,onParseResult:o,toolProvider:l,queryLoader:c,onError:d}){f.useInsertionEffect(()=>{Cp()},[]);const g=f.useRef(o);g.current=o;const h=f.useRef(l);h.current=l;const u=f.useRef({async callTool(m,b){const x=h.current??null;if(x==null)throw new Error("[openui] toolProvider is null");if(typeof x.callTool=="function")return vp(await x.callTool({name:m,arguments:b}));const k=x,S=k[m];if(!S)throw new qn(m,Object.keys(k));return S(b)}}),{result:p,parseResult:v,contextValue:y,isQueryLoading:w}=kp({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:l!=null?u.current:null,onError:d},vi);return f.useEffect(()=>{var m;(m=g.current)==null||m.call(g,v)},[v]),p!=null&&p.root?s.jsx(fi.Provider,{value:y,children:s.jsxs("div",{style:{position:"relative"},children:[w&&(c??s.jsx($p,{})),s.jsx("div",{style:{opacity:w?.7:1,transition:"opacity 0.2s ease"},children:s.jsx(bi,{node:p.root})})]})}):null}f.createContext(null);function _p(e){if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t,"https://placeholder.invalid");return n.origin==="https://placeholder.invalid"||n.protocol==="http:"||n.protocol==="https:"||n.protocol==="mailto:"?t:null}catch{return null}}const Ap=({props:e,renderNode:t})=>{const n=e.children;return s.jsxs("div",{className:"v10-genui-root",children:[e.title?s.jsx("div",{className:"v10-genui-root-title",children:e.title}):null,Array.isArray(n)?n.map((r,i)=>s.jsx(Ce.Fragment,{children:t(r)},i)):t(n)]})},Rp=({props:e})=>{var t;return s.jsxs("div",{className:"v10-genui-card v10-genui-entity-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("div",{className:"v10-genui-card-title",children:e.name}),e.typeLabel?s.jsx("div",{className:"v10-genui-card-type",children:e.typeLabel}):null]}),e.subtitle?s.jsx("div",{className:"v10-genui-card-subtitle",children:e.subtitle}):null,(t=e.chips)!=null&&t.length?s.jsx("div",{className:"v10-genui-chips",children:e.chips.map((n,r)=>s.jsxs("span",{className:`v10-genui-chip tone-${n.tone??"default"}`,children:[s.jsx("span",{className:"v10-genui-chip-label",children:n.label}),s.jsx("span",{className:"v10-genui-chip-value",children:n.value})]},r))}):null]})},Tp=({props:e})=>s.jsx("div",{className:"v10-genui-stats-grid",children:e.stats.map((t,n)=>s.jsxs("div",{className:"v10-genui-stat",title:t.hint,children:[s.jsx("div",{className:"v10-genui-stat-value",children:t.value}),s.jsx("div",{className:"v10-genui-stat-label",children:t.label})]},n))}),Op=({props:e})=>s.jsxs("div",{className:"v10-genui-section",children:[e.heading?s.jsx("div",{className:"v10-genui-section-heading",children:e.heading}):null,s.jsx("div",{className:"v10-genui-triple-table",children:e.rows.map((t,n)=>s.jsxs("div",{className:"v10-genui-triple-row",children:[s.jsx("div",{className:"v10-genui-triple-predicate",children:os(t.predicate)}),s.jsx("div",{className:"v10-genui-triple-object",children:Zp(t.object)})]},n))})]}),Ip=({props:e})=>s.jsxs("div",{className:"v10-genui-section",children:[e.heading?s.jsx("div",{className:"v10-genui-section-heading",children:e.heading}):null,s.jsx("div",{className:"v10-genui-type-groups",children:e.groups.map((t,n)=>s.jsxs("div",{className:"v10-genui-type-group",children:[s.jsxs("div",{className:"v10-genui-type-group-head",children:[t.icon?s.jsx("span",{className:"v10-genui-type-icon",children:t.icon}):null,s.jsx("span",{className:"v10-genui-type-label",children:t.typeLabel}),s.jsx("span",{className:"v10-genui-type-count",children:t.items.length})]}),s.jsx("div",{className:"v10-genui-type-items",children:t.items.map((r,i)=>s.jsxs("div",{className:"v10-genui-type-item",title:r.uri,children:[s.jsx("div",{className:"v10-genui-type-item-label",children:r.label}),r.sub?s.jsx("div",{className:"v10-genui-type-item-sub",children:r.sub}):null]},i))})]},n))})]}),Pp=({props:e})=>s.jsxs("div",{className:"v10-genui-section",children:[s.jsxs("div",{className:"v10-genui-section-heading",children:[s.jsx("span",{children:e.heading}),e.predicate?s.jsxs("span",{className:"v10-genui-section-sub",children:["· ",os(e.predicate)]}):null]}),s.jsx("div",{className:"v10-genui-crossref",children:e.items.map((t,n)=>s.jsxs("div",{className:"v10-genui-crossref-item",title:t.uri,children:[s.jsx("span",{className:"v10-genui-crossref-label",children:t.label}),t.sub?s.jsx("span",{className:"v10-genui-crossref-sub",children:t.sub}):null]},n))})]}),zp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-package-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#a855f7"},children:"📦"}),s.jsx("div",{className:"v10-genui-card-title",children:e.name}),e.folder?s.jsxs("div",{className:"v10-genui-card-type",children:["packages/",e.folder]}):null]}),e.description?s.jsx("div",{className:"v10-genui-card-subtitle",children:e.description}):null,s.jsxs("div",{className:"v10-genui-stats-grid",children:[typeof e.fileCount=="number"&&s.jsx(Bt,{label:"Files",value:e.fileCount}),typeof e.classCount=="number"&&s.jsx(Bt,{label:"Classes",value:e.classCount}),typeof e.functionCount=="number"&&s.jsx(Bt,{label:"Functions",value:e.functionCount}),typeof e.interfaceCount=="number"&&s.jsx(Bt,{label:"Interfaces",value:e.interfaceCount})]})]}),Lp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-file-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#3b82f6"},children:"📄"}),s.jsx("div",{className:"v10-genui-card-title",children:Gp(e.path)}),e.language?s.jsxs("div",{className:"v10-genui-card-type",children:[".",e.language]}):null]}),s.jsx("div",{className:"v10-genui-card-subtitle",children:e.path}),s.jsxs("div",{className:"v10-genui-chips",children:[e.packageName?s.jsxs("span",{className:"v10-genui-chip tone-info",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"pkg"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.packageName})]}):null,typeof e.lineCount=="number"?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"lines"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.lineCount})]}):null]})]}),Mp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-decision-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#ef4444"},children:"◆"}),s.jsx("div",{className:"v10-genui-card-title",children:e.title}),e.status?s.jsx("div",{className:`v10-genui-status-chip status-${e.status}`,children:e.status}):null]}),e.date?s.jsxs("div",{className:"v10-genui-card-subtitle",children:["Decided ",e.date]}):null,e.context?s.jsx(Wt,{heading:"Context",body:e.context}):null,e.outcome?s.jsx(Wt,{heading:"Outcome",body:e.outcome}):null,e.consequences?s.jsx(Wt,{heading:"Consequences",body:e.consequences}):null,e.alternatives?s.jsx(Wt,{heading:"Alternatives considered",body:e.alternatives}):null]}),Fp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-pr-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#f59e0b"},children:"⇄"}),s.jsxs("div",{className:"v10-genui-card-title",children:[typeof e.number=="number"?s.jsxs("span",{className:"v10-genui-pr-num",children:["#",e.number]}):null,e.title]}),e.state?s.jsx("div",{className:`v10-genui-status-chip pr-state-${e.state}`,children:e.state}):null]}),s.jsxs("div",{className:"v10-genui-chips",children:[e.author?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"by"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.author})]}):null,e.mergedAt?s.jsxs("span",{className:"v10-genui-chip tone-success",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"merged"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.mergedAt.split("T")[0]})]}):null,(()=>{const t=_p(e.url);return t?s.jsxs("a",{className:"v10-genui-chip tone-info",href:t,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"view"}),s.jsx("span",{className:"v10-genui-chip-value",children:"github"})]}):null})()]}),e.body?s.jsx("div",{className:"v10-genui-pr-body",children:e.body}):null]}),Up=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-task-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#06b6d4"},children:"✓"}),s.jsx("div",{className:"v10-genui-card-title",children:e.title}),e.status?s.jsx("div",{className:`v10-genui-status-chip task-status-${e.status}`,children:e.status.replace("_"," ")}):null,e.priority?s.jsx("div",{className:`v10-genui-priority-chip priority-${e.priority}`,children:e.priority.toUpperCase()}):null]}),s.jsxs("div",{className:"v10-genui-chips",children:[e.assignee?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"assignee"}),s.jsxs("span",{className:"v10-genui-chip-value",children:["@",e.assignee]})]}):null,typeof e.estimate=="number"?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"est"}),s.jsxs("span",{className:"v10-genui-chip-value",children:[e.estimate,"h"]})]}):null]})]}),Dp=({props:e})=>{var t;return s.jsxs("div",{className:"v10-genui-vm-panel",children:[s.jsxs("div",{className:"v10-genui-vm-panel-head",children:[s.jsxs("div",{className:"v10-genui-vm-badge",children:[s.jsx("span",{className:"v10-genui-vm-badge-dot"}),"Verifiable Memory"]}),s.jsx("div",{className:"v10-genui-vm-title",children:"On-chain provenance"})]}),s.jsxs("div",{className:"v10-genui-vm-grid",children:[e.onChain?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsx("div",{className:"v10-genui-vm-block-heading",children:"Anchoring"}),e.onChain.txHash?s.jsx(tt,{label:"tx",value:sr(e.onChain.txHash),mono:!0}):null,e.onChain.blockNumber?s.jsx(tt,{label:"block",value:String(e.onChain.blockNumber),mono:!0}):null,e.onChain.chain?s.jsx(tt,{label:"chain",value:e.onChain.chain}):null]}):null,e.consensus?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsxs("div",{className:"v10-genui-vm-block-heading",children:["Consensus ",e.consensus.quorum?s.jsx("span",{className:"v10-genui-vm-quorum",children:e.consensus.quorum}):null]}),(e.consensus.signers??[]).map((n,r)=>s.jsxs("div",{className:"v10-genui-vm-signer",children:[s.jsx("div",{className:"v10-genui-vm-signer-dot"}),s.jsxs("div",{className:"v10-genui-vm-signer-body",children:[s.jsx("div",{className:"v10-genui-vm-signer-label",children:n.label??qp(n.did)}),s.jsx("div",{className:"v10-genui-vm-signer-did",children:n.did})]}),typeof n.reputation=="number"?s.jsxs("div",{className:"v10-genui-vm-rep",children:["rep ",n.reputation]}):null]},r))]}):null,e.knowledgeAsset?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsx("div",{className:"v10-genui-vm-block-heading",children:"Knowledge asset"}),e.knowledgeAsset.ual?s.jsx(tt,{label:"ual",value:e.knowledgeAsset.ual,mono:!0}):null,e.knowledgeAsset.contentHash?s.jsx(tt,{label:"hash",value:sr(e.knowledgeAsset.contentHash),mono:!0}):null,e.knowledgeAsset.tracLocked?s.jsx(tt,{label:"trac",value:e.knowledgeAsset.tracLocked}):null,e.knowledgeAsset.tokenId?s.jsx(tt,{label:"nft",value:`#${e.knowledgeAsset.tokenId}`}):null]}):null,(t=e.timeline)!=null&&t.length?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsx("div",{className:"v10-genui-vm-block-heading",children:"Timeline"}),e.timeline.map((n,r)=>s.jsxs("div",{className:"v10-genui-vm-timeline-row",children:[s.jsx("div",{className:"v10-genui-vm-timeline-dot"}),s.jsx("div",{className:"v10-genui-vm-timeline-label",children:n.label}),s.jsx("div",{className:"v10-genui-vm-timeline-at",children:n.at})]},r))]}):null]})]})},Bt=({label:e,value:t})=>s.jsxs("div",{className:"v10-genui-stat",children:[s.jsx("div",{className:"v10-genui-stat-value",children:t}),s.jsx("div",{className:"v10-genui-stat-label",children:e})]}),Wt=({heading:e,body:t})=>s.jsxs("div",{className:"v10-genui-decision-section",children:[s.jsx("div",{className:"v10-genui-decision-section-heading",children:e}),s.jsx("div",{className:"v10-genui-decision-section-body",children:t})]}),tt=({label:e,value:t,mono:n})=>s.jsxs("div",{className:"v10-genui-prov-row",children:[s.jsx("span",{className:"v10-genui-prov-label",children:e}),s.jsx("span",{className:`v10-genui-prov-value${n?" mono":""}`,children:t})]});function os(e){return e.replace(/^"|"$/g,"").replace(/^<|>$/g,"").replace("http://www.w3.org/1999/02/22-rdf-syntax-ns#","rdf:").replace("http://www.w3.org/2000/01/rdf-schema#","rdfs:").replace("http://www.w3.org/2001/XMLSchema#","xsd:").replace("http://schema.org/","schema:").replace("http://dkg.io/ontology/code/","code:").replace("http://dkg.io/ontology/github/","gh:").replace("http://dkg.io/ontology/decisions/","dec:").replace("http://dkg.io/ontology/tasks/","task:").replace("http://dkg.io/ontology/profile/","prof:")}function Zp(e){return os(e).replace(/\^\^<?.*$/,"").replace(/^"(.+)"$/,"$1")}function sr(e){return e?e.length<=16?e:`${e.slice(0,8)}…${e.slice(-6)}`:""}function qp(e){return e?e.length>22?`${e.slice(0,12)}…${e.slice(-6)}`:e:""}function Gp(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}const Bp=Le({name:"EntityDetail",description:"Root container for a single-entity detail view. Accepts any number of child blocks (EntityCard, PackageCard, VerifiedProvenancePanel, etc.). Always use this as the outermost element.",props:pe({title:K().optional().describe("Optional top-of-panel title override (defaults to the entity rdfs:label)")}),component:Ap}),Wp=Le({name:"EntityCard",description:"Compact header card for any entity: name, rdf:type label, optional subtitle, and up to 6 small stat chips.",props:pe({name:K().describe("Display name / label of the entity"),typeLabel:K().optional().describe('Human-readable rdf:type label (e.g. "Package", "Pull Request")'),subtitle:K().optional().describe("Short supporting text (e.g. path, author, date)"),chips:Je(pe({label:K(),value:K(),tone:vt(["default","success","warn","danger","info"]).optional()})).max(6).optional()}),component:Rp}),Vp=Le({name:"EntityStatsGrid",description:"Grid of numeric stats with labels. Use for summarising counts (files, classes, additions, deletions).",props:pe({stats:Je(pe({label:K(),value:ss([K(),Be()]),hint:K().optional()})).min(1).max(8)}),component:Tp}),Qp=Le({name:"TripleTable",description:"Fallback raw-triples table. Use sparingly — only when the entity has no better structured components in this library.",props:pe({heading:K().optional(),rows:Je(pe({predicate:K(),object:K()})).max(60)}),component:Op}),Kp=Le({name:"EntityTypeList",description:"Grouped list of child entities by rdf:type. Great for showing a File's contained classes/functions/interfaces as separate sections.",props:pe({heading:K().optional(),groups:Je(pe({typeLabel:K(),icon:K().optional(),items:Je(pe({label:K(),uri:K().optional(),sub:K().optional()})).max(30)})).max(8)}),component:Ip}),Jp=Le({name:"CrossRefList",description:"List of cross-references following a single predicate (e.g. code:imports, github:affects, decisions:affects). Each item can show a short subtitle.",props:pe({heading:K().describe('Human-readable heading (e.g. "Imports", "Affected files")'),predicate:K().optional(),items:Je(pe({label:K(),uri:K().optional(),sub:K().optional()})).max(40)}),component:Pp}),Yp=Le({name:"PackageCard",description:"Specialised card for a code:Package entity: name, folder, description, and a mini-stats strip.",props:pe({name:K(),folder:K().optional(),description:K().optional(),fileCount:Be().optional(),classCount:Be().optional(),functionCount:Be().optional(),interfaceCount:Be().optional()}),component:zp}),Hp=Le({name:"FileCard",description:"Specialised card for a code:File entity: path, language, line count, owning package.",props:pe({path:K(),language:K().optional(),lineCount:Be().optional(),packageName:K().optional()}),component:Lp}),Xp=Le({name:"DecisionCard",description:"Specialised card for a decisions:Decision entity: title, status badge, date, context/outcome quoted sections.",props:pe({title:K(),status:vt(["proposed","accepted","rejected","superseded"]).optional(),date:K().optional(),context:K().optional(),outcome:K().optional(),consequences:K().optional(),alternatives:K().optional()}),component:Mp}),eh=Le({name:"PRCard",description:"Specialised card for a github:PullRequest entity: title + #number, state, author, merged badge, body preview.",props:pe({title:K(),number:Be().optional(),state:vt(["open","closed","merged"]).optional(),author:K().optional(),mergedAt:K().optional(),body:K().optional(),url:K().optional()}),component:Fp}),th=Le({name:"TaskCard",description:"Specialised card for a tasks:Task entity: title, status chip, priority, assignee, estimate.",props:pe({title:K(),status:vt(["todo","in_progress","blocked","done","cancelled"]).optional(),priority:vt(["p0","p1","p2","p3"]).optional(),assignee:K().optional(),estimate:Be().optional()}),component:Up}),nh=Le({name:"VerifiedProvenancePanel",description:"The Verifiable Memory hero block. Use at the top of any entity in the VM layer. Surfaces on-chain anchor (tx hash, block), consensus (signing agents with reputation), knowledge-asset identity (UAL, content hash, TRAC locked, NFT token id), and finalisation timeline.",props:pe({onChain:pe({txHash:K().optional(),blockNumber:ss([K(),Be()]).optional(),chain:K().optional()}).optional(),consensus:pe({signers:Je(pe({did:K(),label:K().optional(),reputation:Be().optional(),signature:K().optional()})).max(10).optional(),quorum:K().optional().describe('e.g. "3 of 5"')}).optional(),knowledgeAsset:pe({ual:K().optional(),contentHash:K().optional(),tracLocked:K().optional(),tokenId:K().optional()}).optional(),timeline:Je(pe({label:K(),at:K()})).max(6).optional()}),component:Dp}),yi=jp({components:[Bp,Wp,Vp,Qp,Kp,Jp,Yp,Hp,Xp,eh,th,nh],root:"EntityDetail",componentGroups:[{name:"Generic",components:["EntityDetail","EntityCard","EntityStatsGrid","EntityTypeList","CrossRefList","TripleTable"]},{name:"Code domain",components:["PackageCard","FileCard"]},{name:"GitHub domain",components:["PRCard"]},{name:"Decisions & tasks",components:["DecisionCard","TaskCard"]},{name:"Verifiable memory",components:["VerifiedProvenancePanel"]}]});let _n=null;function sh(){return _n===null&&(_n=yi.prompt({preamble:"You are composing a single-entity detail panel for the DKG Node UI. Use only the components below to build a rich, structured view. Always wrap the response in the EntityDetail root element.",additionalRules:["Prefer specialised cards (PackageCard, PRCard, DecisionCard, TaskCard, FileCard) when the rdf:type matches.","Include VerifiedProvenancePanel at the very top if the entity appears in verifiable memory or has on-chain / signature triples.","Keep the tree compact: aim for 3–8 top-level blocks.","Do not invent triple data — only use values present in the provided triples."]})),_n}async function*rh(e){const t=await fetch("/api/genui/render",{method:"POST",headers:{"Content-Type":"application/json",...un()},body:JSON.stringify({contextGraphId:e.contextGraphId,entityUri:e.entityUri,libraryPrompt:e.libraryPrompt}),signal:e.signal});if(!t.ok||!t.body){let a=`HTTP ${t.status}`;try{const o=await t.json();o!=null&&o.error&&(a=o.error)}catch{}yield{type:"error",error:a};return}const n=t.body.getReader(),r=new TextDecoder;let i="";try{for(;;){const{value:a,done:o}=await n.read();if(o)break;i+=r.decode(a,{stream:!0});let l;for(;(l=i.indexOf(`
286
+ `);)b++;if(b<n.length&&(n[b]==="?"||n[b]===":"&&u>0))continue;const x=n.slice(y,w).trim();x&&l(x),y=w+1,r=w+1}}return y}function d(){const h=c(),u=n.slice(h).trim();if(!u)return a===0?Jt():Gt(i,[...i.values()],o,!1,a,e,t);const p=er(lp(u)).trim();if(!p)return a===0?Jt():Gt(i,[...i.values()],o,!1,a,e,t);const{text:v,wasIncomplete:y}=ip(p),w=Js(Ks(v));if(!w.length)return a===0?Jt(y):Gt(i,[...i.values()],o,y,a,e,t);const m=new Map(i);for(const b of w){if(i.has(b.id))continue;const x=Hs(b,Qs(b.tokens));m.set(b.id,x)}return Gt(m,[...m.values()],o||w[0].id,y,a+w.length,e,t)}function g(){n="",r=0,i.clear(),a=0,o=""}return{push(h){return n+=h,d()},set(h){(h.length<n.length||!h.startsWith(n))&&g();const u=h.slice(n.length);return u&&(n+=u),d()},getResult:d}}function up(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e.default}function dp(e){const t=new Map,n=e.$defs??{};for(const[r,i]of Object.entries(n)){const a=i.properties??{},o=i.required??[],l=Object.keys(a).map(c=>({name:c,required:o.includes(c),defaultValue:up(a[c])}));t.set(r,{params:l})}return t}function pp(e,t){return cp(dp(e),t)}function hp(e,t){if(!(t!=null&&t.properties))return;const n=new Set(t.required??[]);return`Signature: ${e}(${Object.keys(t.properties).map(r=>n.has(r)?`${r}*`:r).join(", ")}) — * marks required`}function mp(e,t,n){return e.map(r=>{var a;const i={source:"parser",code:r.code,message:r.message,component:r.component,path:r.path||void 0,statementId:r.statementId};return r.code==="unknown-component"&&n.length?i.hint=`Available components: ${n.join(", ")}`:r.code==="missing-required"||r.code==="null-required"?i.hint=hp(r.component,(a=t.$defs)==null?void 0:a[r.component]):r.code==="inline-reserved"&&(i.hint=`Declare as a top-level statement: myVar = ${r.component}(...)`),i})}function fp(e){return typeof e=="object"&&e!==null&&e.__reactive==="assign"}function oe(e,t,n){var r,i,a;switch(e.k){case"Str":return e.v;case"Num":return e.v;case"Bool":return e.v;case"Null":return null;case"Ph":return null;case"StateRef":return((r=t.extraScope)==null?void 0:r[e.n])??t.getState(e.n);case"Ref":case"RuntimeRef":return t.resolveRef(e.n);case"Arr":return e.els.map(o=>oe(o,t));case"Obj":return Object.fromEntries(e.entries.map(([o,l])=>[o,oe(l,t)]));case"Comp":{if(is.has(e.name))return vp(e.name,e.args,t,n);const o=rs[e.name];if(o){const l=e.args.map(c=>oe(c,t));return o.fn(...l)}if(ri.has(e.name))return gp(e.name,e.args,t);if(e.mappedProps){const l=n==null?void 0:n.library.components[e.name],c={};for(const[g,h]of Object.entries(e.mappedProps)){const u=(a=(i=l==null?void 0:l.props)==null?void 0:i.shape)==null?void 0:a[g];h.k==="StateRef"&&u&&_t(u)?c[g]={__reactive:"assign",target:h.n,expr:{k:"StateRef",n:"$value"}}:h.k==="StateRef"?c[g]=n?t.getState(h.n):h:c[g]=oe(h,t,n)}const d={type:"element",typeName:e.name,props:c,partial:!1,hasDynamicProps:!0};if(n)for(const[g,h]of Object.entries(c))Ke(h)?c[g]=cn(h,t,n):Array.isArray(h)&&(c[g]=h.map(u=>Ke(u)?cn(u,t,n):u));return d}return console.warn(`[openui] Unexpected unmapped Comp node: ${e.name}`),null}case"BinOp":{if(e.op==="&&"){const c=oe(e.left,t);return c&&oe(e.right,t)}if(e.op==="||"){const c=oe(e.left,t);return c||oe(e.right,t)}const o=oe(e.left,t),l=oe(e.right,t);switch(e.op){case"+":return typeof o=="string"||typeof l=="string"?String(o??"")+String(l??""):ee(o)+ee(l);case"-":return ee(o)-ee(l);case"*":return ee(o)*ee(l);case"/":return ee(l)===0?0:ee(o)/ee(l);case"%":return ee(l)===0?0:ee(o)%ee(l);case"==":return o==l;case"!=":return o!=l;case">":return ee(o)>ee(l);case"<":return ee(o)<ee(l);case">=":return ee(o)>=ee(l);case"<=":return ee(o)<=ee(l);default:return null}}case"UnaryOp":return e.op==="!"?!oe(e.operand,t):e.op==="-"?-ee(oe(e.operand,t)):null;case"Ternary":return oe(e.cond,t)?oe(e.then,t):oe(e.else,t);case"Member":{const o=oe(e.obj,t);return o==null?null:Array.isArray(o)?e.field==="length"?o.length:o.map(l=>(l==null?void 0:l[e.field])??null):o[e.field]}case"Index":{const o=oe(e.obj,t),l=oe(e.index,t);return o==null||l==null?null:Array.isArray(o)?o[ee(l)]:o[String(l)]}case"Assign":return{__reactive:"assign",target:e.target,expr:e.value}}}function cn(e,t,n){var a,o;if(e.hasDynamicProps===!1)return e;const r=n.library.components[e.typeName],i={};for(const[l,c]of Object.entries(e.props)){const d=(o=(a=r==null?void 0:r.props)==null?void 0:a.shape)==null?void 0:o[l];i[l]=pi(c,t,n,d)}return{...e,props:i}}function pi(e,t,n,r){return hi(e,t,n,r,{recurseElement:i=>cn(i,t,n),recurse:(i,a)=>pi(i,t,n,a)})}function Dn(e){return e==null?{k:"Null"}:typeof e=="string"?{k:"Str",v:e}:typeof e=="number"?{k:"Num",v:e}:typeof e=="boolean"?{k:"Bool",v:e}:Array.isArray(e)?{k:"Arr",els:e.map(Dn)}:typeof e=="object"?{k:"Obj",entries:Object.entries(e).map(([t,n])=>[t,Dn(n)])}:{k:"Null"}}function gp(e,t,n){switch(e){case"Action":{const r=t.length>0?oe(t[0],n):[];return{steps:(Array.isArray(r)?r:[]).filter(i=>i!=null&&typeof i=="object"&&"type"in i)}}case"Run":{if(t.length===0)return null;const r=t[0];return r.k==="RuntimeRef"?{type:Ue.Run,statementId:r.n,refType:r.refType}:null}case"ToAssistant":{const r=t.length>0?String(oe(t[0],n)??""):"",i=t.length>1?String(oe(t[1],n)??""):void 0;return{type:Ue.ToAssistant,message:r,context:i}}case"OpenUrl":{const r=t.length>0?String(oe(t[0],n)??""):"";return{type:Ue.OpenUrl,url:r}}case"Set":{if(t.length<2)return null;const r=t[0];return r.k!=="StateRef"?null:{type:Ue.Set,target:r.n,valueAST:t[1]}}case"Reset":{const r=t.filter(i=>i.k==="StateRef").map(i=>i.n);return r.length===0?null:{type:Ue.Reset,targets:r}}default:return null}}function _e(e,t,n){switch(e.k){case"Ref":return e.n===t?Dn(n):e;case"Member":if(ht(e.obj)){const r=_e(e.obj,t,n);if(r.k==="Obj"){const i=r.entries.find(([a])=>a===e.field);if(i)return i[1]}return{...e,obj:r}}return e;case"Index":return{...e,obj:ht(e.obj)?_e(e.obj,t,n):e.obj,index:ht(e.index)?_e(e.index,t,n):e.index};case"BinOp":return{...e,left:_e(e.left,t,n),right:_e(e.right,t,n)};case"UnaryOp":return{...e,operand:_e(e.operand,t,n)};case"Ternary":return{...e,cond:_e(e.cond,t,n),then:_e(e.then,t,n),else:_e(e.else,t,n)};case"Arr":return{...e,els:e.els.map(r=>_e(r,t,n))};case"Obj":return{...e,entries:e.entries.map(([r,i])=>[r,_e(i,t,n)])};case"Comp":{const r={...e,args:e.args.map(i=>_e(i,t,n))};if(e.mappedProps){const i={};for(const[a,o]of Object.entries(e.mappedProps))i[a]=_e(o,t,n);r.mappedProps=i}return r}case"Assign":return{...e,value:_e(e.value,t,n)};default:return e}}function vp(e,t,n,r){if(e==="Each"){if(t.length<3)return[];const i=oe(t[0],n);if(!Array.isArray(i))return[];const a=t[1].k==="Ref"?t[1].n:t[1].k==="Str"?t[1].v:null;if(!a)return[];const o=t[2];return i.map((l,c)=>{const d=_e(o,a,l),g={...n,resolveRef:u=>u===a?l:n.resolveRef(u)},h=oe(d,g,r);return r&&Ke(h)?cn(h,g,r):h})}return null}function hi(e,t,n,r,i){if(e==null||typeof e!="object")return e;if(ht(e)){if(e.k==="StateRef"&&r&&_t(r))return{__reactive:"assign",target:e.n,expr:{k:"StateRef",n:"$value"}};const l=oe(e,t,n);return Ke(l)?i.recurseElement(l):Array.isArray(l)?l.map(c=>Ke(c)?i.recurseElement(c):c):fp(l)&&!(r&&_t(r))?t.getState(l.target)??null:l}if(typeof e=="string"&&r&&_t(r))return e;if(Array.isArray(e))return e.map(l=>i.recurse(l,r));if(Ke(e))return i.recurseElement(e);const a=e;if("steps"in a&&Array.isArray(a.steps)||"type"in a&&"valueAST"in a)return e;let o=!1;for(const l of Object.values(a))if(typeof l=="object"&&l!==null){o=!0;break}if(o){const l={};for(const[c,d]of Object.entries(a))l[c]=i.recurse(d,r);return l}return e}function mi(e,t){var a,o,l;if(e.hasDynamicProps===!1)return e;const n={library:t.library},r=t.library.components[e.typeName],i={};for(const[c,d]of Object.entries(e.props)){const g=(o=(a=r==null?void 0:r.props)==null?void 0:a.shape)==null?void 0:o[c];try{i[c]=fi(d,t,n,g)}catch(h){i[c]=d;const u=h instanceof Error?h.message:String(h);(l=t.errors)==null||l.push({source:"runtime",code:"runtime-error",component:e.typeName,statementId:e.statementId,message:`Evaluating prop "${c}" on ${e.typeName} failed: ${u}`,hint:`Check the expression used for prop "${c}"`})}}return{...e,props:i}}function fi(e,t,n,r){return hi(e,t.ctx,n,r,{recurseElement:i=>mi(i,t),recurse:(i,a)=>fi(i,t,n,a)})}var Zn=class extends Error{constructor(t){super(`MCP tool error: ${t||"Unknown error"}`);xt(this,"toolErrorText");this.name="McpToolError",this.toolErrorText=t}};function bp(e){var n,r;if(e.isError){const i=(n=e.content)==null?void 0:n.filter(a=>a.type==="text").map(a=>a.text).join(`
287
+ `);throw new Zn(i||"Unknown error")}if(e.structuredContent!=null)return e.structuredContent;const t=(r=e.content)==null?void 0:r.filter(i=>i.type==="text").map(i=>i.text??"");if(t!=null&&t.length){const i=t.join("");try{return JSON.parse(i)}catch{return i}}return null}var qn=class extends Error{constructor(t,n=[]){super(`[openui] No handler for tool "${t}". Available: ${n.join(", ")||"(none)"}`);xt(this,"toolName");xt(this,"availableTools");this.name="ToolNotFoundError",this.toolName=t,this.availableTools=n}};function tr(e){return JSON.stringify(e,(t,n)=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const r={};for(const i of Object.keys(n).sort())r[i]=n[i];return r}if(n===void 0)return"__undefined__";if(typeof n=="number"){if(Number.isNaN(n))return"__NaN__";if(n===1/0)return"__Inf__";if(n===-1/0)return"__-Inf__"}return n})}function yp(e,t,n){const r=n!=null?"::"+tr(n):"";return e+"::"+tr(t)+r}function xp(e){const t=new Map,n=new Map,r=new Map,i=new Set;let a={__openui_loading:[],__openui_refetching:[],__openui_errors:[]},o=JSON.stringify(a),l=!1,c=0;function d(){const E={__openui_loading:[],__openui_refetching:[],__openui_errors:[]};for(const[T,C]of t){const O=r.get(C.cacheKey);if(O&&O.data!==void 0)E[T]=O.data;else if(C.prevCacheKey){const Z=r.get(C.prevCacheKey);Z&&Z.data!==void 0?E[T]=Z.data:E[T]=C.defaults}else E[T]=C.defaults;C.loading&&(E.__openui_loading.push(T),C.everFetched&&E.__openui_refetching.push(T)),C.error&&E.__openui_errors.push(C.error)}for(const[T,C]of n)E[T]=C.result,C.error&&E.__openui_errors.push(C.error);try{const T=JSON.stringify(E);if(T===o)return!1;a=E,o=T}catch{a=E,o=""}return!0}function g(){for(const E of[...i])E()}async function h(E,T){if(!e)return;const C=t.get(T);if(!C)return;const O=E,Z=C.toolName,$=C.args;let R=r.get(O);R?R.inFlight=!0:(R={data:void 0,inFlight:!0},r.set(O,R)),C.loading=!0,d(),g();try{const G=await e.callTool(Z,$??{});if(l)return;const P=t.get(T);if(!P||P.cacheKey!==O){R.inFlight=!1;return}if(R.data=G??null,P.everFetched=!0,P.error=void 0,P.prevCacheKey&&P.prevCacheKey!==O){const L=P.prevCacheKey;P.prevCacheKey=void 0,u(L)}}catch(G){const P=t.get(T);P&&P.cacheKey===O&&(G instanceof qn?P.error={source:"query",code:"tool-not-found",message:`Query tool "${Z}" not found`,statementId:T,component:"Query",toolName:Z,hint:G.availableTools.length?`Available tools: ${G.availableTools.join(", ")}`:void 0}:G instanceof Zn?P.error={source:"query",code:"mcp-error",message:`Query "${Z}" returned an error: ${G.toolErrorText}`,statementId:T,component:"Query",toolName:Z}:P.error={source:"query",code:"tool-error",message:`Query "${Z}" failed: ${G instanceof Error?G.message:String(G)}`,statementId:T,component:"Query",toolName:Z}),console.error(`Query "${Z}" failed:`,G)}finally{R.inFlight=!1;const G=t.get(T);G&&G.cacheKey===O?(G.loading=!1,d()&&g(),G.needsRefetch&&(G.needsRefetch=!1,h(G.cacheKey,T))):d()&&g()}}function u(E){for(const T of t.values())if(T.cacheKey===E||T.prevCacheKey===E)return;r.delete(E)}function p(E){if(l)return;const T=new Set(E.map(C=>C.statementId));for(const[C,O]of t)T.has(C)||(O.timer&&clearInterval(O.timer),t.delete(C),u(O.cacheKey),O.prevCacheKey&&u(O.prevCacheKey));for(const C of E){if(!C.complete)continue;const O=yp(C.toolName,C.args,C.deps),Z=t.get(C.statementId);Z?(Z.cacheKey!==O&&(Z.prevCacheKey=Z.cacheKey),Z.toolName=C.toolName,Z.args=C.args,Z.defaults=C.defaults,Z.cacheKey=O):t.set(C.statementId,{toolName:C.toolName,args:C.args,defaults:C.defaults,cacheKey:O,loading:!1,everFetched:!1,refreshInterval:0,needsRefetch:!1});const $=t.get(C.statementId),R=r.get(O),G=R&&R.data!==void 0&&!R.inFlight;e&&!G&&!(R!=null&&R.inFlight)&&h(O,C.statementId);const P=C.refreshInterval??0;P!==$.refreshInterval&&($.timer&&(clearInterval($.timer),$.timer=void 0),P>0&&($.timer=setInterval(()=>{var L;l||!e||(L=r.get($.cacheKey))!=null&&L.inFlight||h($.cacheKey,C.statementId)},P*1e3)),$.refreshInterval=P)}d()&&g()}function v(E){const T=t.get(E);if(!T)return null;const C=r.get(T.cacheKey);if(C&&C.data!==void 0)return C.data;if(T.prevCacheKey){const O=r.get(T.prevCacheKey);if(O&&O.data!==void 0)return O.data}return T.defaults}function y(E){var T;return((T=t.get(E))==null?void 0:T.loading)??!1}function w(){for(const E of t.values())if(E.loading)return!0;return!1}function m(E){var C;if(l||!e)return;const T=E!=null&&E.length?E.filter(O=>t.has(O)):[...t.keys()];for(const O of T){const Z=t.get(O);Z&&((C=r.get(Z.cacheKey))!=null&&C.inFlight?Z.needsRefetch=!0:h(Z.cacheKey,O))}}function b(E){const T=new Set(E.map(C=>C.statementId));for(const C of n.keys())T.has(C)||n.delete(C);for(const C of E){const O=n.get(C.statementId);O?O.toolName!==C.toolName&&(O.toolName=C.toolName,O.result={status:"idle",data:null,error:null},O.error=void 0):n.set(C.statementId,{toolName:C.toolName,result:{status:"idle"}})}d()&&g()}async function x(E,T,C){if(l||!e)return!1;const O=n.get(E);if(!O||O.result.status==="loading")return!1;const Z=c;O.result={status:"loading"},d(),g();let $=!1;try{const R=await e.callTool(O.toolName,T);if(l||Z!==c)return!1;O.result={status:"success",data:R},O.error=void 0,$=!0}catch(R){if(l||Z!==c)return!1;const G=R instanceof Error?R.message:String(R);O.result={status:"error",error:G},R instanceof qn?O.error={source:"mutation",code:"tool-not-found",message:`Mutation tool "${O.toolName}" not found`,statementId:E,component:"Mutation",toolName:O.toolName,hint:R.availableTools.length?`Available tools: ${R.availableTools.join(", ")}`:void 0}:R instanceof Zn?O.error={source:"mutation",code:"mcp-error",message:`Mutation "${O.toolName}" returned an error: ${R.toolErrorText}`,statementId:E,component:"Mutation",toolName:O.toolName}:O.error={source:"mutation",code:"tool-error",message:`Mutation "${O.toolName}" failed: ${G}`,statementId:E,component:"Mutation",toolName:O.toolName}}return d(),g(),$&&(C!=null&&C.length)&&m(C),$}function k(E){var T;return((T=n.get(E))==null?void 0:T.result)??null}function N(E){return i.add(E),()=>i.delete(E)}function j(){return a}function _(){l=!1}function z(){l=!0,c++,i.clear();for(const E of t.values())E.timer&&(clearInterval(E.timer),E.timer=void 0),E.loading=!1,E.needsRefetch=!1;n.clear()}return{evaluateQueries:p,getResult:v,isLoading:y,isAnyLoading:w,invalidate:m,registerMutations:b,fireMutation:x,getMutationResult:k,subscribe:N,getSnapshot:j,activate:_,dispose:z}}function jp(){const e=new Map,t=new Set;let n={};function r(){const h=[...t];for(const u of h)u()}function i(){n=Object.fromEntries(e)}function a(h){return e.get(h)}function o(h,u){const p=e.get(h);if(!Object.is(p,u)){if(u&&p&&typeof u=="object"&&typeof p=="object"&&!Array.isArray(u)&&!Array.isArray(p)){const v=Object.keys(u),y=Object.keys(p);if(v.length===y.length&&v.every(w=>Object.is(u[w],p[w])))return}e.set(h,u),i(),r()}}function l(h){return t.add(h),()=>{t.delete(h)}}function c(){return n}function d(h,u){for(const p of Object.keys(u))e.set(p,u[p]);for(const p of Object.keys(h))e.has(p)||e.set(p,h[p]);i(),r()}function g(){e.clear(),t.clear(),n={}}return{get:a,set:o,subscribe:l,getSnapshot:c,initialize:d,dispose:g}}function Le(e){return Bd(e)}function wp(e){return Xd(e)}const gi=f.createContext(null);function vi(){const e=f.useContext(gi);if(!e)throw new Error("useOpenUI must be used within a <Renderer /> component.");return e}function kp(){return vi().renderNode}f.createContext(void 0);function En(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e?e.value:e}function Np({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:o,onError:l},c){const d=f.useMemo(()=>pp(t.toJSONSchema(),t.root),[t]),g=f.useRef(null),h=f.useMemo(()=>{if(g.current=null,!e)return null;try{return d.set(e)}catch(P){return g.current={source:"parser",code:"parse-exception",message:`Parser crashed: ${P instanceof Error?P.message:String(P)}`,hint:"The response may contain syntax the parser cannot handle"},null}},[d,e]),u=f.useMemo(()=>jp(),[]),p=f.useMemo(()=>xp(o??null),[o]);f.useEffect(()=>(p.activate(),()=>p.dispose()),[p]);const v=f.useRef(Symbol());f.useEffect(()=>{if(!(h!=null&&h.stateDeclarations)&&!a)return;const P=`${JSON.stringify(h==null?void 0:h.stateDeclarations)}::${JSON.stringify(a)}`;if(v.current===P)return;v.current=P;const L={};if(a)for(const[A,M]of Object.entries(a))A.startsWith("$")?L[A]=M:u.set(A,M);u.initialize((h==null?void 0:h.stateDeclarations)??{},L)},[h==null?void 0:h.stateDeclarations,u,a]);const y=f.useSyncExternalStore(u.subscribe,u.getSnapshot,u.getSnapshot),w=f.useSyncExternalStore(p.subscribe,p.getSnapshot,p.getSnapshot),m=f.useMemo(()=>({getState:P=>En(u.get(P)),resolveRef:P=>{const L=p.getMutationResult(P);return L||p.getResult(P)}}),[u,p]);f.useEffect(()=>{if(n)return;const P=((h==null?void 0:h.queryStatements)??[]).map(L=>{const A={};if(L.deps)for(const M of L.deps)A[M]=y[M];return{statementId:L.statementId,toolName:L.toolAST?oe(L.toolAST,m):"",args:L.argsAST?oe(L.argsAST,m):null,defaults:L.defaultsAST?oe(L.defaultsAST,m):null,refreshInterval:L.refreshAST?oe(L.refreshAST,m):void 0,deps:Object.keys(A).length>0?A:void 0,complete:L.complete}});p.evaluateQueries(P)},[n,h==null?void 0:h.queryStatements,m,p,y]),f.useEffect(()=>{if(n)return;const P=((h==null?void 0:h.mutationStatements)??[]).map(L=>({statementId:L.statementId,toolName:L.toolAST?oe(L.toolAST,m):""}));p.registerMutations(P)},[n,h==null?void 0:h.mutationStatements,m,p]);const b=f.useRef({onAction:r,onStateUpdate:i,onError:l});b.current={onAction:r,onStateUpdate:i,onError:l};const x=f.useRef(h);x.current=h;const k=f.useRef(null);f.useEffect(()=>(k.current=u.getSnapshot(),u.subscribe(()=>{var L,A;const P=u.getSnapshot();P!==k.current&&(k.current=null,(A=(L=b.current).onStateUpdate)==null||A.call(L,P))})),[u]);const N=f.useCallback((P,L)=>{if(!P)return En(u.get(L));const A=u.get(P);if(!(!A||typeof A!="object"||Array.isArray(A)))return En(A[L])},[u]),j=f.useCallback((P,L,A,M,F=!0)=>{var J,X;const B={value:M,componentType:L};if(!P)u.set(A,B);else{const Y=u.get(P),V=Y&&typeof Y=="object"&&!Array.isArray(Y)?Y:{};u.set(P,{...V,[A]:B})}F&&((X=(J=b.current).onStateUpdate)==null||X.call(J,u.getSnapshot()))},[u]),_=f.useCallback(P=>{if(P){const L=u.get(P);if(L&&typeof L=="object"&&!Array.isArray(L))return{[P]:L}}return u.getSnapshot()},[u]),z=f.useCallback(async(P,L,A)=>{var J,X,Y;const M=_(L),{onAction:F}=b.current;if(A&&!("steps"in A)){const V=A.type||Zt.ContinueConversation,re={...A.params||{}};A.url&&(re.url=A.url),A.context&&(re.context=A.context),F==null||F({type:V,params:re,humanFriendlyMessage:P,formState:M,formName:L});return}const B=A;if(B!=null&&B.steps){for(const V of B.steps)switch(V.type){case Ue.Run:if(V.refType==="mutation"){const re=(X=(J=x.current)==null?void 0:J.mutationStatements)==null?void 0:X.find(Ne=>Ne.statementId===V.statementId),ye=re!=null&&re.argsAST?oe(re.argsAST,m):{};if(!await p.fireMutation(V.statementId,ye))return}else p.invalidate([V.statementId]);break;case Ue.ToAssistant:F==null||F({type:Zt.ContinueConversation,params:V.context?{context:V.context}:{},humanFriendlyMessage:V.message,formState:M,formName:L});break;case Ue.OpenUrl:F==null||F({type:Zt.OpenUrl,params:{url:V.url},humanFriendlyMessage:"",formState:M,formName:L});break;case Ue.Set:{if(!V.valueAST){console.warn(`[openui] Set action for ${V.target} has no valueAST — skipping`);break}const re=oe(V.valueAST,m);u.set(V.target,re);break}case Ue.Reset:{const re=((Y=x.current)==null?void 0:Y.stateDeclarations)??{};for(const ye of V.targets)u.set(ye,re[ye]??null);break}}return}F==null||F({type:Zt.ContinueConversation,params:{},humanFriendlyMessage:P,formState:M,formName:L})},[p,m,_,u]),E=f.useRef([]),T=f.useRef(n);T.current=n;const C=f.useCallback(P=>{T.current||E.current.push(P)},[]),O=f.useMemo(()=>({library:t,renderNode:c,triggerAction:z,isStreaming:n,getFieldValue:N,setFieldValue:j,store:u,evaluationContext:m,reportError:C}),[t,c,n,z,N,j,u,m,C]),Z=f.useRef([]),$=f.useMemo(()=>{if(!(h!=null&&h.root))return h;const P=[],L={ctx:m,library:t,store:u,errors:P};try{const A=mi(h.root,L);return Z.current=P,{...h,root:A}}catch(A){const M=A instanceof Error?A.message:String(A);return P.push({source:"runtime",code:"runtime-error",message:`Prop evaluation failed: ${M}`}),Z.current=P,h}},[h,m,t,u,y,w]),R=w.__openui_loading.length>0,G=f.useRef("");return f.useEffect(()=>{var A,M,F,B;if(n){G.current!==""&&(G.current="",(M=(A=b.current).onError)==null||M.call(A,[]));return}const P=[];g.current&&P.push(g.current),e&&!(h!=null&&h.root)&&!g.current&&P.push({source:"parser",code:"parse-failed",message:h?"Code parsed but produced no renderable root component":"Response could not be parsed as valid openui-lang",hint:`The entire response must be valid openui-lang code starting with root = ${t.root??"Root"}(...)`}),(B=(F=h==null?void 0:h.meta)==null?void 0:F.errors)!=null&&B.length&&P.push(...mp(h.meta.errors,t.toJSONSchema(),Object.keys(t.components))),P.push(...Z.current),P.push(...E.current),E.current=[],P.push(...w.__openui_errors??[]);const L=JSON.stringify(P);if(L!==G.current){if(G.current=L,b.current.onError)b.current.onError(P);else if(P.length>0)for(const J of P)console.warn(`[openui] ${J.source}/${J.code}: ${J.message}`)}},[n,e,h,$,w,t]),{result:$,parseResult:h,contextValue:O,isQueryLoading:R}}var Sp=class extends f.Component{constructor(t){super(t);xt(this,"lastValidChildren",null);this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidMount(){this.state.hasError||(this.lastValidChildren=this.props.children)}componentDidUpdate(t){this.state.hasError||(this.lastValidChildren=this.props.children),this.state.hasError&&t.children!==this.props.children&&this.setState({hasError:!1})}componentDidCatch(t){var r,i;const n=this.props.componentName??"Unknown";(i=(r=this.props).onError)==null||i.call(r,{source:"runtime",code:"render-error",component:n,message:`Component ${n} render failed: ${t.message}`})}render(){return this.state.hasError?this.lastValidChildren:this.props.children}};function bi(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.map((t,n)=>s.jsx(f.Fragment,{children:bi(t)},n));if(typeof e=="object"&&e!==null){const t=e;if(t.type==="element")return s.jsx(yi,{node:t})}return null}function yi({node:e}){var i;const{library:t,reportError:n}=vi(),r=(i=t.components[e.typeName])==null?void 0:i.component;return r?s.jsx(Sp,{componentName:e.typeName,onError:n,children:s.jsx(Cp,{el:e,Comp:r})}):null}function Cp({el:e,Comp:t}){const n=kp();return s.jsx(t,{props:e.props,renderNode:n})}let nr=!1;function $p(){if(nr||typeof document>"u")return;nr=!0;const e=document.createElement("style");e.textContent="@keyframes openui-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }",document.head.appendChild(e)}const Ep=()=>s.jsx("div",{style:{position:"absolute",top:8,right:8,width:16,height:16,border:"2px solid #e5e7eb",borderTopColor:"#3b82f6",borderRadius:"50%",animation:"openui-spin 0.6s linear infinite",zIndex:10}});function _p({response:e,library:t,isStreaming:n=!1,onAction:r,onStateUpdate:i,initialState:a,onParseResult:o,toolProvider:l,queryLoader:c,onError:d}){f.useInsertionEffect(()=>{$p()},[]);const g=f.useRef(o);g.current=o;const h=f.useRef(l);h.current=l;const u=f.useRef({async callTool(m,b){const x=h.current??null;if(x==null)throw new Error("[openui] toolProvider is null");if(typeof x.callTool=="function")return bp(await x.callTool({name:m,arguments:b}));const k=x,N=k[m];if(!N)throw new qn(m,Object.keys(k));return N(b)}}),{result:p,parseResult:v,contextValue:y,isQueryLoading:w}=Np({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:l!=null?u.current:null,onError:d},bi);return f.useEffect(()=>{var m;(m=g.current)==null||m.call(g,v)},[v]),p!=null&&p.root?s.jsx(gi.Provider,{value:y,children:s.jsxs("div",{style:{position:"relative"},children:[w&&(c??s.jsx(Ep,{})),s.jsx("div",{style:{opacity:w?.7:1,transition:"opacity 0.2s ease"},children:s.jsx(yi,{node:p.root})})]})}):null}f.createContext(null);function Ap(e){if(typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t,"https://placeholder.invalid");return n.origin==="https://placeholder.invalid"||n.protocol==="http:"||n.protocol==="https:"||n.protocol==="mailto:"?t:null}catch{return null}}const Tp=({props:e,renderNode:t})=>{const n=e.children;return s.jsxs("div",{className:"v10-genui-root",children:[e.title?s.jsx("div",{className:"v10-genui-root-title",children:e.title}):null,Array.isArray(n)?n.map((r,i)=>s.jsx(Ce.Fragment,{children:t(r)},i)):t(n)]})},Rp=({props:e})=>{var t;return s.jsxs("div",{className:"v10-genui-card v10-genui-entity-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("div",{className:"v10-genui-card-title",children:e.name}),e.typeLabel?s.jsx("div",{className:"v10-genui-card-type",children:e.typeLabel}):null]}),e.subtitle?s.jsx("div",{className:"v10-genui-card-subtitle",children:e.subtitle}):null,(t=e.chips)!=null&&t.length?s.jsx("div",{className:"v10-genui-chips",children:e.chips.map((n,r)=>s.jsxs("span",{className:`v10-genui-chip tone-${n.tone??"default"}`,children:[s.jsx("span",{className:"v10-genui-chip-label",children:n.label}),s.jsx("span",{className:"v10-genui-chip-value",children:n.value})]},r))}):null]})},Op=({props:e})=>s.jsx("div",{className:"v10-genui-stats-grid",children:e.stats.map((t,n)=>s.jsxs("div",{className:"v10-genui-stat",title:t.hint,children:[s.jsx("div",{className:"v10-genui-stat-value",children:t.value}),s.jsx("div",{className:"v10-genui-stat-label",children:t.label})]},n))}),Ip=({props:e})=>s.jsxs("div",{className:"v10-genui-section",children:[e.heading?s.jsx("div",{className:"v10-genui-section-heading",children:e.heading}):null,s.jsx("div",{className:"v10-genui-triple-table",children:e.rows.map((t,n)=>s.jsxs("div",{className:"v10-genui-triple-row",children:[s.jsx("div",{className:"v10-genui-triple-predicate",children:os(t.predicate)}),s.jsx("div",{className:"v10-genui-triple-object",children:qp(t.object)})]},n))})]}),Pp=({props:e})=>s.jsxs("div",{className:"v10-genui-section",children:[e.heading?s.jsx("div",{className:"v10-genui-section-heading",children:e.heading}):null,s.jsx("div",{className:"v10-genui-type-groups",children:e.groups.map((t,n)=>s.jsxs("div",{className:"v10-genui-type-group",children:[s.jsxs("div",{className:"v10-genui-type-group-head",children:[t.icon?s.jsx("span",{className:"v10-genui-type-icon",children:t.icon}):null,s.jsx("span",{className:"v10-genui-type-label",children:t.typeLabel}),s.jsx("span",{className:"v10-genui-type-count",children:t.items.length})]}),s.jsx("div",{className:"v10-genui-type-items",children:t.items.map((r,i)=>s.jsxs("div",{className:"v10-genui-type-item",title:r.uri,children:[s.jsx("div",{className:"v10-genui-type-item-label",children:r.label}),r.sub?s.jsx("div",{className:"v10-genui-type-item-sub",children:r.sub}):null]},i))})]},n))})]}),zp=({props:e})=>s.jsxs("div",{className:"v10-genui-section",children:[s.jsxs("div",{className:"v10-genui-section-heading",children:[s.jsx("span",{children:e.heading}),e.predicate?s.jsxs("span",{className:"v10-genui-section-sub",children:["· ",os(e.predicate)]}):null]}),s.jsx("div",{className:"v10-genui-crossref",children:e.items.map((t,n)=>s.jsxs("div",{className:"v10-genui-crossref-item",title:t.uri,children:[s.jsx("span",{className:"v10-genui-crossref-label",children:t.label}),t.sub?s.jsx("span",{className:"v10-genui-crossref-sub",children:t.sub}):null]},n))})]}),Lp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-package-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#a855f7"},children:"📦"}),s.jsx("div",{className:"v10-genui-card-title",children:e.name}),e.folder?s.jsxs("div",{className:"v10-genui-card-type",children:["packages/",e.folder]}):null]}),e.description?s.jsx("div",{className:"v10-genui-card-subtitle",children:e.description}):null,s.jsxs("div",{className:"v10-genui-stats-grid",children:[typeof e.fileCount=="number"&&s.jsx(Bt,{label:"Files",value:e.fileCount}),typeof e.classCount=="number"&&s.jsx(Bt,{label:"Classes",value:e.classCount}),typeof e.functionCount=="number"&&s.jsx(Bt,{label:"Functions",value:e.functionCount}),typeof e.interfaceCount=="number"&&s.jsx(Bt,{label:"Interfaces",value:e.interfaceCount})]})]}),Mp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-file-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#3b82f6"},children:"📄"}),s.jsx("div",{className:"v10-genui-card-title",children:Bp(e.path)}),e.language?s.jsxs("div",{className:"v10-genui-card-type",children:[".",e.language]}):null]}),s.jsx("div",{className:"v10-genui-card-subtitle",children:e.path}),s.jsxs("div",{className:"v10-genui-chips",children:[e.packageName?s.jsxs("span",{className:"v10-genui-chip tone-info",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"pkg"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.packageName})]}):null,typeof e.lineCount=="number"?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"lines"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.lineCount})]}):null]})]}),Fp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-decision-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#ef4444"},children:"◆"}),s.jsx("div",{className:"v10-genui-card-title",children:e.title}),e.status?s.jsx("div",{className:`v10-genui-status-chip status-${e.status}`,children:e.status}):null]}),e.date?s.jsxs("div",{className:"v10-genui-card-subtitle",children:["Decided ",e.date]}):null,e.context?s.jsx(Wt,{heading:"Context",body:e.context}):null,e.outcome?s.jsx(Wt,{heading:"Outcome",body:e.outcome}):null,e.consequences?s.jsx(Wt,{heading:"Consequences",body:e.consequences}):null,e.alternatives?s.jsx(Wt,{heading:"Alternatives considered",body:e.alternatives}):null]}),Up=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-pr-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#f59e0b"},children:"⇄"}),s.jsxs("div",{className:"v10-genui-card-title",children:[typeof e.number=="number"?s.jsxs("span",{className:"v10-genui-pr-num",children:["#",e.number]}):null,e.title]}),e.state?s.jsx("div",{className:`v10-genui-status-chip pr-state-${e.state}`,children:e.state}):null]}),s.jsxs("div",{className:"v10-genui-chips",children:[e.author?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"by"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.author})]}):null,e.mergedAt?s.jsxs("span",{className:"v10-genui-chip tone-success",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"merged"}),s.jsx("span",{className:"v10-genui-chip-value",children:e.mergedAt.split("T")[0]})]}):null,(()=>{const t=Ap(e.url);return t?s.jsxs("a",{className:"v10-genui-chip tone-info",href:t,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"view"}),s.jsx("span",{className:"v10-genui-chip-value",children:"github"})]}):null})()]}),e.body?s.jsx("div",{className:"v10-genui-pr-body",children:e.body}):null]}),Dp=({props:e})=>s.jsxs("div",{className:"v10-genui-card v10-genui-task-card",children:[s.jsxs("div",{className:"v10-genui-card-head",children:[s.jsx("span",{className:"v10-genui-card-icon",style:{color:"#06b6d4"},children:"✓"}),s.jsx("div",{className:"v10-genui-card-title",children:e.title}),e.status?s.jsx("div",{className:`v10-genui-status-chip task-status-${e.status}`,children:e.status.replace("_"," ")}):null,e.priority?s.jsx("div",{className:`v10-genui-priority-chip priority-${e.priority}`,children:e.priority.toUpperCase()}):null]}),s.jsxs("div",{className:"v10-genui-chips",children:[e.assignee?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"assignee"}),s.jsxs("span",{className:"v10-genui-chip-value",children:["@",e.assignee]})]}):null,typeof e.estimate=="number"?s.jsxs("span",{className:"v10-genui-chip",children:[s.jsx("span",{className:"v10-genui-chip-label",children:"est"}),s.jsxs("span",{className:"v10-genui-chip-value",children:[e.estimate,"h"]})]}):null]})]}),Zp=({props:e})=>{var t;return s.jsxs("div",{className:"v10-genui-vm-panel",children:[s.jsxs("div",{className:"v10-genui-vm-panel-head",children:[s.jsxs("div",{className:"v10-genui-vm-badge",children:[s.jsx("span",{className:"v10-genui-vm-badge-dot"}),"Verifiable Memory"]}),s.jsx("div",{className:"v10-genui-vm-title",children:"On-chain provenance"})]}),s.jsxs("div",{className:"v10-genui-vm-grid",children:[e.onChain?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsx("div",{className:"v10-genui-vm-block-heading",children:"Anchoring"}),e.onChain.txHash?s.jsx(tt,{label:"tx",value:sr(e.onChain.txHash),mono:!0}):null,e.onChain.blockNumber?s.jsx(tt,{label:"block",value:String(e.onChain.blockNumber),mono:!0}):null,e.onChain.chain?s.jsx(tt,{label:"chain",value:e.onChain.chain}):null]}):null,e.consensus?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsxs("div",{className:"v10-genui-vm-block-heading",children:["Consensus ",e.consensus.quorum?s.jsx("span",{className:"v10-genui-vm-quorum",children:e.consensus.quorum}):null]}),(e.consensus.signers??[]).map((n,r)=>s.jsxs("div",{className:"v10-genui-vm-signer",children:[s.jsx("div",{className:"v10-genui-vm-signer-dot"}),s.jsxs("div",{className:"v10-genui-vm-signer-body",children:[s.jsx("div",{className:"v10-genui-vm-signer-label",children:n.label??Gp(n.did)}),s.jsx("div",{className:"v10-genui-vm-signer-did",children:n.did})]}),typeof n.reputation=="number"?s.jsxs("div",{className:"v10-genui-vm-rep",children:["rep ",n.reputation]}):null]},r))]}):null,e.knowledgeAsset?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsx("div",{className:"v10-genui-vm-block-heading",children:"Knowledge asset"}),e.knowledgeAsset.ual?s.jsx(tt,{label:"ual",value:e.knowledgeAsset.ual,mono:!0}):null,e.knowledgeAsset.contentHash?s.jsx(tt,{label:"hash",value:sr(e.knowledgeAsset.contentHash),mono:!0}):null,e.knowledgeAsset.tracLocked?s.jsx(tt,{label:"trac",value:e.knowledgeAsset.tracLocked}):null,e.knowledgeAsset.tokenId?s.jsx(tt,{label:"nft",value:`#${e.knowledgeAsset.tokenId}`}):null]}):null,(t=e.timeline)!=null&&t.length?s.jsxs("div",{className:"v10-genui-vm-block",children:[s.jsx("div",{className:"v10-genui-vm-block-heading",children:"Timeline"}),e.timeline.map((n,r)=>s.jsxs("div",{className:"v10-genui-vm-timeline-row",children:[s.jsx("div",{className:"v10-genui-vm-timeline-dot"}),s.jsx("div",{className:"v10-genui-vm-timeline-label",children:n.label}),s.jsx("div",{className:"v10-genui-vm-timeline-at",children:n.at})]},r))]}):null]})]})},Bt=({label:e,value:t})=>s.jsxs("div",{className:"v10-genui-stat",children:[s.jsx("div",{className:"v10-genui-stat-value",children:t}),s.jsx("div",{className:"v10-genui-stat-label",children:e})]}),Wt=({heading:e,body:t})=>s.jsxs("div",{className:"v10-genui-decision-section",children:[s.jsx("div",{className:"v10-genui-decision-section-heading",children:e}),s.jsx("div",{className:"v10-genui-decision-section-body",children:t})]}),tt=({label:e,value:t,mono:n})=>s.jsxs("div",{className:"v10-genui-prov-row",children:[s.jsx("span",{className:"v10-genui-prov-label",children:e}),s.jsx("span",{className:`v10-genui-prov-value${n?" mono":""}`,children:t})]});function os(e){return e.replace(/^"|"$/g,"").replace(/^<|>$/g,"").replace("http://www.w3.org/1999/02/22-rdf-syntax-ns#","rdf:").replace("http://www.w3.org/2000/01/rdf-schema#","rdfs:").replace("http://www.w3.org/2001/XMLSchema#","xsd:").replace("http://schema.org/","schema:").replace("http://dkg.io/ontology/code/","code:").replace("http://dkg.io/ontology/github/","gh:").replace("http://dkg.io/ontology/decisions/","dec:").replace("http://dkg.io/ontology/tasks/","task:").replace("http://dkg.io/ontology/profile/","prof:")}function qp(e){return os(e).replace(/\^\^<?.*$/,"").replace(/^"(.+)"$/,"$1")}function sr(e){return e?e.length<=16?e:`${e.slice(0,8)}…${e.slice(-6)}`:""}function Gp(e){return e?e.length>22?`${e.slice(0,12)}…${e.slice(-6)}`:e:""}function Bp(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}const Wp=Le({name:"EntityDetail",description:"Root container for a single-entity detail view. Accepts any number of child blocks (EntityCard, PackageCard, VerifiedProvenancePanel, etc.). Always use this as the outermost element.",props:pe({title:K().optional().describe("Optional top-of-panel title override (defaults to the entity rdfs:label)")}),component:Tp}),Vp=Le({name:"EntityCard",description:"Compact header card for any entity: name, rdf:type label, optional subtitle, and up to 6 small stat chips.",props:pe({name:K().describe("Display name / label of the entity"),typeLabel:K().optional().describe('Human-readable rdf:type label (e.g. "Package", "Pull Request")'),subtitle:K().optional().describe("Short supporting text (e.g. path, author, date)"),chips:Je(pe({label:K(),value:K(),tone:vt(["default","success","warn","danger","info"]).optional()})).max(6).optional()}),component:Rp}),Qp=Le({name:"EntityStatsGrid",description:"Grid of numeric stats with labels. Use for summarising counts (files, classes, additions, deletions).",props:pe({stats:Je(pe({label:K(),value:ss([K(),Be()]),hint:K().optional()})).min(1).max(8)}),component:Op}),Kp=Le({name:"TripleTable",description:"Fallback raw-triples table. Use sparingly — only when the entity has no better structured components in this library.",props:pe({heading:K().optional(),rows:Je(pe({predicate:K(),object:K()})).max(60)}),component:Ip}),Jp=Le({name:"EntityTypeList",description:"Grouped list of child entities by rdf:type. Great for showing a File's contained classes/functions/interfaces as separate sections.",props:pe({heading:K().optional(),groups:Je(pe({typeLabel:K(),icon:K().optional(),items:Je(pe({label:K(),uri:K().optional(),sub:K().optional()})).max(30)})).max(8)}),component:Pp}),Hp=Le({name:"CrossRefList",description:"List of cross-references following a single predicate (e.g. code:imports, github:affects, decisions:affects). Each item can show a short subtitle.",props:pe({heading:K().describe('Human-readable heading (e.g. "Imports", "Affected files")'),predicate:K().optional(),items:Je(pe({label:K(),uri:K().optional(),sub:K().optional()})).max(40)}),component:zp}),Yp=Le({name:"PackageCard",description:"Specialised card for a code:Package entity: name, folder, description, and a mini-stats strip.",props:pe({name:K(),folder:K().optional(),description:K().optional(),fileCount:Be().optional(),classCount:Be().optional(),functionCount:Be().optional(),interfaceCount:Be().optional()}),component:Lp}),Xp=Le({name:"FileCard",description:"Specialised card for a code:File entity: path, language, line count, owning package.",props:pe({path:K(),language:K().optional(),lineCount:Be().optional(),packageName:K().optional()}),component:Mp}),eh=Le({name:"DecisionCard",description:"Specialised card for a decisions:Decision entity: title, status badge, date, context/outcome quoted sections.",props:pe({title:K(),status:vt(["proposed","accepted","rejected","superseded"]).optional(),date:K().optional(),context:K().optional(),outcome:K().optional(),consequences:K().optional(),alternatives:K().optional()}),component:Fp}),th=Le({name:"PRCard",description:"Specialised card for a github:PullRequest entity: title + #number, state, author, merged badge, body preview.",props:pe({title:K(),number:Be().optional(),state:vt(["open","closed","merged"]).optional(),author:K().optional(),mergedAt:K().optional(),body:K().optional(),url:K().optional()}),component:Up}),nh=Le({name:"TaskCard",description:"Specialised card for a tasks:Task entity: title, status chip, priority, assignee, estimate.",props:pe({title:K(),status:vt(["todo","in_progress","blocked","done","cancelled"]).optional(),priority:vt(["p0","p1","p2","p3"]).optional(),assignee:K().optional(),estimate:Be().optional()}),component:Dp}),sh=Le({name:"VerifiedProvenancePanel",description:"The Verifiable Memory hero block. Use at the top of any entity in the VM layer. Surfaces on-chain anchor (tx hash, block), consensus (signing agents with reputation), knowledge-asset identity (UAL, content hash, TRAC locked, NFT token id), and finalisation timeline.",props:pe({onChain:pe({txHash:K().optional(),blockNumber:ss([K(),Be()]).optional(),chain:K().optional()}).optional(),consensus:pe({signers:Je(pe({did:K(),label:K().optional(),reputation:Be().optional(),signature:K().optional()})).max(10).optional(),quorum:K().optional().describe('e.g. "3 of 5"')}).optional(),knowledgeAsset:pe({ual:K().optional(),contentHash:K().optional(),tracLocked:K().optional(),tokenId:K().optional()}).optional(),timeline:Je(pe({label:K(),at:K()})).max(6).optional()}),component:Zp}),xi=wp({components:[Wp,Vp,Qp,Kp,Jp,Hp,Yp,Xp,eh,th,nh,sh],root:"EntityDetail",componentGroups:[{name:"Generic",components:["EntityDetail","EntityCard","EntityStatsGrid","EntityTypeList","CrossRefList","TripleTable"]},{name:"Code domain",components:["PackageCard","FileCard"]},{name:"GitHub domain",components:["PRCard"]},{name:"Decisions & tasks",components:["DecisionCard","TaskCard"]},{name:"Verifiable memory",components:["VerifiedProvenancePanel"]}]});let _n=null;function rh(){return _n===null&&(_n=xi.prompt({preamble:"You are composing a single-entity detail panel for the DKG Node UI. Use only the components below to build a rich, structured view. Always wrap the response in the EntityDetail root element.",additionalRules:["Prefer specialised cards (PackageCard, PRCard, DecisionCard, TaskCard, FileCard) when the rdf:type matches.","Include VerifiedProvenancePanel at the very top if the entity appears in verifiable memory or has on-chain / signature triples.","Keep the tree compact: aim for 3–8 top-level blocks.","Do not invent triple data — only use values present in the provided triples."]})),_n}async function*ih(e){const t=await fetch("/api/genui/render",{method:"POST",headers:{"Content-Type":"application/json",...un()},body:JSON.stringify({contextGraphId:e.contextGraphId,entityUri:e.entityUri,libraryPrompt:e.libraryPrompt}),signal:e.signal});if(!t.ok||!t.body){let a=`HTTP ${t.status}`;try{const o=await t.json();o!=null&&o.error&&(a=o.error)}catch{}yield{type:"error",error:a};return}const n=t.body.getReader(),r=new TextDecoder;let i="";try{for(;;){const{value:a,done:o}=await n.read();if(o)break;i+=r.decode(a,{stream:!0});let l;for(;(l=i.indexOf(`
288
288
 
289
289
  `))!==-1;){const c=i.slice(0,l);i=i.slice(l+2);const d=rr(c);d&&(yield d)}}if(i.trim()){const a=rr(i);a&&(yield a)}}finally{n.releaseLock()}}function rr(e){let t="message",n="";for(const r of e.split(`
290
- `))r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&(n+=r.slice(5).trim());if(!n)return null;try{const r=JSON.parse(n);switch(t){case"start":return{type:"start",...r};case"delta":return{type:"delta",text:r.text??""};case"final":return{type:"final",content:r.content??""};case"error":return{type:"error",error:r.error??"unknown error"};case"done":return{type:"done"};default:return null}}catch{return null}}const ih=({contextGraphId:e,entityUri:t,placeholder:n,fallback:r})=>{const[i,a]=Ce.useState(""),[o,l]=Ce.useState(!0),[c,d]=Ce.useState(null);return Ce.useEffect(()=>{const g=new AbortController;let h="";return a(""),d(null),l(!0),(async()=>{try{const u=sh();for await(const p of rh({contextGraphId:e,entityUri:t,libraryPrompt:u,signal:g.signal}))if(p.type==="delta")h+=p.text,a(h);else if(p.type==="final")p.content&&(h=p.content,a(p.content));else if(p.type==="error"){d(p.error);break}else if(p.type==="done")break}catch(u){u.name!=="AbortError"&&d(u.message)}finally{l(!1)}})(),()=>g.abort()},[e,t]),c?r?s.jsx(s.Fragment,{children:r(c)}):s.jsx(oh,{error:c}):!i&&o?s.jsx(s.Fragment,{children:n??s.jsx("div",{className:"v10-genui-loading",children:"Composing detail view…"})}):s.jsx("div",{className:"v10-genui-panel",children:s.jsx(Ep,{response:i,library:yi,isStreaming:o})})},ah="LLM not configured",oh=({error:e})=>{const t=Vn(r=>r.openTab);return e.includes(ah)?s.jsxs("div",{className:"v10-genui-error v10-genui-error-cta",children:[s.jsxs("div",{className:"v10-genui-error-head",children:[s.jsx("span",{className:"v10-genui-error-icon",children:"⚙"}),s.jsxs("div",{children:[s.jsx("div",{className:"v10-genui-error-title",children:"Set up your LLM to enable GenUI"}),s.jsx("div",{className:"v10-genui-error-desc",children:"GenUI streams entity detail views from an OpenAI-compatible model. Add an API key in Settings and open this entity again."})]})]}),s.jsx("button",{className:"v10-genui-error-cta-btn",onClick:()=>t({id:"settings",label:"Settings",closable:!0}),children:"Open Settings →"})]}):s.jsxs("div",{className:"v10-genui-error",children:["GenUI unavailable: ",e]})};function ir({entity:e,profile:t}){const n=f.useMemo(()=>{for(const l of e.subGraphs)if(l!=="meta")return l;return null},[e.subGraphs]);if(!n||!t)return null;const r=t.forSubGraph(n),i=(r==null?void 0:r.color)??"#64748b",a=(r==null?void 0:r.icon)??"•",o=(r==null?void 0:r.displayName)??n;return s.jsxs("span",{className:"v10-subgraph-badge",style:{"--sg-color":i},title:`In sub-graph: ${o}`,children:[s.jsx("span",{className:"v10-subgraph-badge-icon",style:{color:i},children:a}),s.jsx("span",{className:"v10-subgraph-badge-label",children:o})]})}function lh({entity:e,contextGraphId:t,onVerified:n}){const r=et(),[i,a]=f.useState(!1),[o,l]=f.useState(null),[c,d]=f.useState(null),[g,h]=f.useState(null),u=e.trustLevel,p=f.useMemo(()=>{if(!r)return null;for(const x of e.types){const k=r.forType(x);if(k&&(u==="working"&&(k.promoteLabel||k.promoteHint)||u==="shared"&&(k.publishLabel||k.publishHint)))return k}return null},[e.types,r,u]),v=f.useMemo(()=>{if(!r)return null;for(const x of e.subGraphs){if(x==="meta")continue;const k=r.forSubGraph(x);if(k!=null&&k.sourceAssertion)return{binding:k,subGraph:x}}return null},[e.subGraphs,r]);if(u==="verified"||!p)return null;const y=u==="working"?{kind:"promote",label:p.promoteLabel??"Promote to Shared Memory",hint:p.promoteHint??"Shares the complete owning Knowledge Asset with the team.",busyCopy:"Sharing…",disabled:!(v!=null&&v.binding.sourceAssertion),disabledReason:v!=null&&v.binding.sourceAssertion?null:`No sourceAssertion declared on the sub-graph profile — add profile:sourceAssertion to the SubGraphBinding for "${[...e.subGraphs].filter(x=>x!=="meta")[0]??"?"}".`}:{kind:"publish",label:p.publishLabel??"Verify on DKG",hint:p.publishHint??"Publishes the complete owning Knowledge Asset on-chain.",busyCopy:"Anchoring…",disabled:!(v!=null&&v.binding.sourceAssertion),disabledReason:v!=null&&v.binding.sourceAssertion?null:"This entity is not part of a named Shared-Memory asset, so it cannot be published to Verifiable Memory from here."},w=async()=>{if(y.disabled)return;a(!0),h(null),l(null),d(y.kind);const x=(v==null?void 0:v.binding.sourceAssertion)??"assertion";try{if(y.kind==="promote"){const k=await Xt(t,v.binding.sourceAssertion,v.subGraph?{subGraphName:v.subGraph}:{});l(xr(x,k))}else{const k=await jr(t,v.binding.sourceAssertion,v.subGraph?{subGraphName:v.subGraph}:{});l(k)}n()}catch(k){const S=y.kind==="promote"?en(x,k):null,j=S?S.message:(k==null?void 0:k.message)??"Action failed";h(j)}finally{a(!1)}},m=x=>!!x&&"status"in x,b=x=>!!x&&"kind"in x;return s.jsxs("div",{className:`v10-ka-verify v10-ka-verify-${y.kind}`,children:[s.jsxs("div",{className:"v10-ka-verify-head",children:[s.jsx("span",{className:"v10-ka-verify-arrow",children:y.kind==="promote"?"◈":"◉"}),s.jsx("span",{className:"v10-ka-verify-title",children:y.label})]}),s.jsx("div",{className:"v10-ka-verify-hint",children:y.hint}),y.disabledReason&&s.jsxs("div",{className:"v10-ka-verify-err",children:["! ",y.disabledReason]}),!o&&s.jsx("button",{className:`v10-ka-verify-btn ${y.kind}`,onClick:w,disabled:i||y.disabled,children:i?y.busyCopy:y.label}),g&&s.jsxs("div",{className:"v10-ka-verify-err",children:["✕ ",g]}),o&&c==="promote"&&b(o)&&o.kind==="success"&&s.jsxs("div",{className:"v10-ka-verify-ok",children:[s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Promoted"}),s.jsxs("span",{className:"v10-ka-verify-ok-val",children:["✓ ",o.promotedCount," triple",o.promotedCount===1?"":"s"," now in Shared Memory"]})]}),s.jsx("div",{className:"v10-ka-verify-hint",style:{marginTop:6},children:"Refresh the entity to see the next step appear."})]}),o&&c==="promote"&&b(o)&&o.kind!=="success"&&s.jsxs("div",{className:"v10-ka-verify-err",children:["! ",o.message]}),o&&c==="publish"&&m(o)&&(()=>{var S,j;const x=o.status==="confirmed"&&!!o.txHash,k=x&&!!o.contextGraphError;return s.jsxs("div",{className:x?k?"v10-ka-verify-warn":"v10-ka-verify-ok":"v10-ka-verify-err",children:[s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Status"}),s.jsxs("span",{className:"v10-ka-verify-ok-val",children:[x?k?"⚠":"✓":"✕"," ",o.status,x?k?` (${ta})`:"":" (NOT on-chain)"]})]}),k&&s.jsx("div",{className:"v10-ka-verify-hint",style:{marginTop:6},children:tn(o.contextGraphError)}),o.txHash?s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"TX hash"}),s.jsx("span",{className:"v10-ka-verify-ok-val mono",title:o.txHash,children:o.txHash})]}):s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"TX hash"}),s.jsx("span",{className:"v10-ka-verify-ok-val",children:"none — on-chain submission skipped"})]}),o.blockNumber!=null&&s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Block"}),s.jsxs("span",{className:"v10-ka-verify-ok-val mono",children:["#",o.blockNumber]})]}),((j=(S=o.kas)==null?void 0:S[0])==null?void 0:j.tokenId)&&s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Token"}),s.jsxs("span",{className:"v10-ka-verify-ok-val mono",children:["#",o.kas[0].tokenId]})]})]})})()]})}function ch({entity:e,allEntities:t,allTriples:n,onNavigate:r,onClose:i,contextGraphId:a,onRefresh:o,onOpenAgent:l}){const[c,d]=f.useState("content"),g=fr(C=>C.theme),h=et(),u=It(),{icon:p,type:v}=dn(e,h),y=Hi(e),w=Wn(e),m=w?(u==null?void 0:u.get(w))??null:null,b=e.trustLevel==="verified"?"vm":e.trustLevel==="shared"?"swm":"wm",x=e.trustLevel==="verified"?"Verifiable Memory":e.trustLevel==="shared"?"Shared Working Memory":"Working Memory",k=We(e.trustLevel,1),S=f.useMemo(()=>{const C=[];for(const[,R]of t)for(const G of R.connections)G.targetUri===e.uri&&C.push({pred:ut(G.predicate),entity:R});return C},[e.uri,t]),j=f.useMemo(()=>n.filter(C=>De(C.subject)===e.uri||De(C.object)===e.uri),[e.uri,n]),_=f.useMemo(()=>Xi(e.uri,n,1),[e.uri,n]),z=f.useMemo(()=>{const C=new Set;for(const R of t.values())ea(R)&&C.add(De(R.uri));return C},[t]),E=f.useMemo(()=>new Set([De(e.uri)]),[e.uri]),T=f.useMemo(()=>Yt(_,z,{focalSubjects:E}),[_,z,E]),$=f.useMemo(()=>{const C=nt[e.trustLevel];return{labelMode:"humanized",renderer:"2d",labels:Nr({minZoomForLabels:.2}),style:{namespaceColors:kr(C),defaultNodeColor:C,defaultEdgeColor:"#475569",edgeWidth:1,fontSize:11},hexagon:{baseSize:7,minSize:4,maxSize:10,scaleWithDegree:!0},focus:{maxNodes:500,hops:999}}},[e.trustLevel]),O=f.useMemo(()=>({name:`entity-${e.uri}-${g}`,palette:g,focal:{uri:e.uri,sizeMultiplier:2.4}}),[e.uri,g]),Z=j.length;return s.jsxs("div",{className:"v10-ka-detail",children:[s.jsxs("div",{className:"v10-ka-header",children:[s.jsx("button",{className:"v10-ka-back",onClick:i,children:"← Back to Context Graph"}),s.jsxs("div",{className:"v10-ka-header-left",children:[s.jsx("div",{className:"v10-ka-label",children:k}),s.jsxs("div",{className:"v10-ka-name",children:[p," ",e.label,s.jsx("span",{className:`v10-trust-badge ${b}`,children:x})]}),s.jsxs("div",{className:"v10-ka-ual",children:[e.uri," · ",v," · ",Z," triples"]})]}),(m||w)&&s.jsxs("div",{className:"v10-ka-header-author",children:[s.jsx("div",{className:"v10-ka-header-author-label",children:"Proposed by"}),s.jsx(gt,{agent:m??void 0,fallbackUri:w??void 0,size:"lg",showOperator:!0,onOpenAgent:l})]})]}),s.jsxs("div",{className:"v10-ka-split",children:[s.jsxs("div",{className:"v10-ka-left",children:[s.jsxs("div",{className:"v10-content-tabs",style:{margin:"0 -20px",padding:"0 20px",background:"transparent"},children:[s.jsx("button",{className:`v10-content-tab ${c==="content"?"active":""}`,onClick:()=>d("content"),children:"Content"}),s.jsx("button",{className:`v10-content-tab ${c==="triples"?"active":""}`,onClick:()=>d("triples"),children:"Triples"}),s.jsx("button",{className:`v10-content-tab ${c==="graph"?"active":""}`,onClick:()=>d("graph"),children:"Graph"})]}),c==="content"&&s.jsxs(s.Fragment,{children:[!e.types.map(R=>h==null?void 0:h.forType(R)).find(R=>R==null?void 0:R.detailHint)||!(h!=null&&h.contextGraphId)?null:s.jsx("div",{className:"v10-ka-section",children:s.jsx(ih,{contextGraphId:h.contextGraphId,entityUri:e.uri})}),y&&s.jsx("div",{className:"v10-ka-section",children:s.jsx("div",{className:"v10-ka-desc",children:s.jsx("p",{children:y})})}),e.properties.size>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsx("div",{className:"v10-ka-section-title",children:"Properties"}),[...e.properties].map(([C,R])=>s.jsxs("div",{className:"v10-ka-prop",children:[s.jsx("span",{className:"v10-ka-prop-key",children:ut(C)}),s.jsx("span",{className:"v10-ka-prop-val",children:R.join(", ")})]},C))]}),e.connections.length>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsxs("div",{className:"v10-ka-section-title",children:["References (",e.connections.length,")"]}),e.connections.map((C,R)=>{const G=t.get(C.targetUri);return s.jsxs("button",{className:"v10-ka-conn",onClick:()=>r(C.targetUri),children:[s.jsx("span",{className:"v10-ka-conn-pred",children:ut(C.predicate)}),s.jsx("span",{className:"v10-ka-conn-arrow",children:"→"}),s.jsx("span",{className:"v10-ka-conn-target",children:C.targetLabel}),G&&s.jsx(ir,{entity:G,profile:h})]},R)})]}),S.length>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsxs("div",{className:"v10-ka-section-title",children:["Referenced by (",S.length,")"]}),S.map((C,R)=>s.jsxs("button",{className:"v10-ka-conn",onClick:()=>r(C.entity.uri),children:[s.jsx("span",{className:"v10-ka-conn-target",children:C.entity.label}),s.jsx(ir,{entity:C.entity,profile:h}),s.jsx("span",{className:"v10-ka-conn-arrow",children:"→"}),s.jsx("span",{className:"v10-ka-conn-pred",children:C.pred})]},R))]}),s.jsxs("div",{className:"v10-ka-meta",children:[s.jsxs("span",{className:"v10-ka-meta-item",children:[p," ",v]}),s.jsxs("span",{className:"v10-ka-meta-item",children:[Z," triples"]}),s.jsxs("span",{className:"v10-ka-meta-item",children:[e.connections.length," links"]})]})]}),c==="triples"&&s.jsxs("div",{style:{marginTop:8,overflowX:"auto",border:"1px solid var(--border-default)",borderRadius:6},children:[s.jsxs("table",{className:"v10-ka-triples-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Subject"}),s.jsx("th",{children:"Predicate"}),s.jsx("th",{children:"Object"})]})}),s.jsx("tbody",{children:j.slice(0,50).map((C,R)=>s.jsxs("tr",{children:[s.jsx("td",{title:C.subject,children:ut(C.subject)}),s.jsx("td",{title:C.predicate,children:ut(C.predicate)}),s.jsx("td",{title:C.object,children:C.object.startsWith('"')?vr(C.object).slice(0,60):ut(C.object)})]},R))})]}),s.jsxs("div",{style:{fontSize:10,color:"var(--text-tertiary)",fontFamily:"var(--font-mono)",padding:"6px 8px"},children:[Math.min(j.length,50)," of ",j.length," triples shown"]})]}),c==="graph"&&s.jsx(Qt,{title:`${e.label} graph`,scopeLabel:`Entity detail graph: 1-hop neighborhood around ${e.label}.`,tone:b,className:"v10-ka-graph-shell",renderGraph:C=>T.length>0?s.jsx(f.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Kn,{data:T,format:"triples",options:$,viewConfig:O,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:R=>(R==null?void 0:R.id)&&R.id!==e.uri&&r(R.id),initialFit:!0,initialFocus:e.uri},`${e.uri}:${C?"expanded":"inline"}`)}):s.jsx("div",{className:"v10-graph-placeholder v10-graph-placeholder-centered",children:"No neighborhood data"})})]}),s.jsxs("div",{className:"v10-ka-right",children:[s.jsx(Lo,{contextGraphId:a,entityUri:e.uri,enabled:e.trustLevel==="verified"}),s.jsx("div",{className:"v10-ka-section-title",children:"Provenance Trail"}),s.jsx(uh,{entity:e}),s.jsx(lh,{entity:e,contextGraphId:a,onVerified:o}),s.jsxs("div",{style:{marginTop:16,padding:"10px 12px",borderRadius:6,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)"},children:[s.jsx("div",{className:"v10-ka-section-title",style:{marginBottom:6},children:"Entity Summary"}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:4,fontSize:10},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Type"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:v})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Triples"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:Z})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Links"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:e.connections.length})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Layer"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:x.split(" ")[0]})]})]})]})]})]})]})}function uh({entity:e}){const t=It(),n=o=>{const l=na(e,o),c=sa(e,o),d=l?t==null?void 0:t.get(l):null;return{uri:l,at:c,agent:d}},r=n("created"),i=n("promoted"),a=n("published");return s.jsxs("div",{className:"v10-ka-timeline",children:[e.trustLevel==="verified"&&s.jsx(An,{toneClass:"verified",title:"Published to Verifiable Memory",actionWord:"Published",agent:a.agent,agentUri:a.uri,at:a.at}),(e.trustLevel==="shared"||e.trustLevel==="verified")&&s.jsx(An,{toneClass:"shared",title:"Promoted to Shared Working Memory",actionWord:"Promoted",agent:i.agent,agentUri:i.uri,at:i.at}),s.jsx(An,{toneClass:"created",title:"Created in Working Memory",actionWord:"Created",agent:r.agent,agentUri:r.uri,at:r.at})]})}function An({toneClass:e,title:t,actionWord:n,agent:r,agentUri:i,at:a}){const o=a?ra(a):null;return s.jsxs("div",{className:"v10-ka-event",children:[s.jsx("div",{className:`v10-ka-event-dot ${e}`}),s.jsxs("div",{className:"v10-ka-event-header",children:[s.jsx("span",{className:"v10-ka-event-title",children:t}),o&&s.jsx("time",{className:"v10-ka-event-time",dateTime:a??void 0,children:o})]}),(r||i)&&s.jsxs("div",{className:"v10-ka-event-attribution",children:[s.jsxs("span",{className:"v10-ka-event-attribution-prefix",children:[n," by"]}),s.jsx(gt,{agent:r??void 0,fallbackUri:i??void 0,size:"sm"})]})]})}function ar(){return s.jsxs("div",{className:"v10-subgraph-explorer-header",children:[s.jsx("div",{className:"v10-subgraph-explorer-title",children:"Subgraph Explorer"}),s.jsx("p",{className:"v10-subgraph-explorer-intro",children:"Subgraphs are optional topical partitions inside this Context Graph. An entity belongs to one or more memory layers and, optionally, to one or more subgraphs. Entities in no subgraph live in the context graph root."})]})}function dh({contextGraphId:e,memory:t,onNodeClick:n,onSelectSubGraph:r}){const i=et(),[a,o]=f.useState([]),[l,c]=f.useState(!0),[d,g]=f.useState(null);f.useEffect(()=>{let j=!1;return c(!0),g(null),$t.fetchSubGraphs(e).then(_=>{j||o(_.subGraphs??[])}).catch(_=>{j||g(_ instanceof Error?_.message:"Failed to load subgraphs")}).finally(()=>{j||c(!1)}),()=>{j=!0}},[e]);const{total:h}=Bn(t),u=Object.values(t.layerStatus??{}),p=t.loading||u.some(j=>j==="loading"),v=t.error!==null||t.partial||u.some(j=>j==="error"),y=f.useMemo(()=>{const j=new Map;for(const _ of t.entityList){const z=De(_.uri);for(const E of _.subGraphs){let T=j.get(E);T||(T=new Set,j.set(E,T)),T.add(z)}}return j},[t.entityList]),{triplesBySubGraph:w,tripleCountBySubGraph:m}=f.useMemo(()=>{const j=new Map;for(const E of t.allTriples){if(!E.subGraph)continue;let T=j.get(E.subGraph);T||(T=[],j.set(E.subGraph,T)),T.push(E)}for(const E of t.allTriples)if(!E.subGraph){for(const[T,$]of y)if(Tn(E,{slug:T,isRoot:!1,scopedUris:$})){let O=j.get(T);O||(O=[],j.set(T,O)),O.push(E)}}const _=new Map,z=new Map;for(const[E,T]of j){const O=ms(T,t.entities).map(Z=>({subject:Z.subject,predicate:Z.predicate,object:Z.object}));z.set(E,O.length),_.set(E,ys(O))}return{triplesBySubGraph:_,tripleCountBySubGraph:z}},[t.allTriples,t.entities,y]),b=f.useMemo(()=>{const j=new Map;for(const _ of t.entityList)for(const z of _.subGraphs){let E=j.get(z);E||(E={wm:0,swm:0,vm:0},j.set(z,E)),_.trustLevel==="verified"?E.vm++:_.trustLevel==="shared"?E.swm++:E.wm++}return j},[t.entityList]),x=f.useMemo(()=>{const j=new Map;for(const _ of t.entityList){const z=De(_.uri);for(const E of _.subGraphs){let T=j.get(E);T||(T=new Map,j.set(E,T)),T.set(z,_.trustLevel),z!==_.uri&&T.set(_.uri,_.trustLevel)}}return j},[t.entityList]),k=f.useMemo(()=>a.filter(Qn).map(j=>{const _=(i==null?void 0:i.forSubGraph(j.name))??{},z=w.get(j.name)??[],E=y.get(j.name)??new Set,T=x.get(j.name)??new Map;return{slug:j.name,icon:_.icon??"•",color:_.color??"#64748b",displayName:_.displayName??j.name,description:_.description,rank:_.rank??99,entityCount:E.size>0?E.size:j.entityCount,tripleCount:m.get(j.name)??0,triples:Yt(z,E),layerCounts:b.get(j.name)??{wm:0,swm:0,vm:0},entityTrustByUri:T}}).sort((j,_)=>j.rank-_.rank),[a,i,w,m,b,y,x]),S=f.useMemo(()=>{const j=[],_=new Set,z=new Map;let E=0,T=0,$=0;for(const L of t.entityList){if(L.subGraphs.size>0)continue;j.push(L);const A=De(L.uri);_.add(A),z.set(A,L.trustLevel),A!==L.uri&&z.set(L.uri,L.trustLevel),L.trustLevel==="verified"?$++:L.trustLevel==="shared"?T++:E++}const O=t.allTriples.filter(L=>!L.subGraph),Z=ms(O,t.entities).map(L=>({subject:L.subject,predicate:L.predicate,object:L.object})),C=Z.length,R=Yt(Z,_),G=ys(R),P=(i==null?void 0:i.forSubGraph(Ve))??{};return{slug:Ve,icon:P.icon??"⊘",color:P.color??"#64748b",displayName:P.displayName??"Root",description:P.description,rank:999,entityCount:j.length,tripleCount:C,triples:G,layerCounts:{wm:E,swm:T,vm:$},entityTrustByUri:z}},[t.entityList,t.allTriples,t.entities,i]);return l&&k.length===0?s.jsx(xe,{compact:!0,icon:"#",title:"Loading subgraphs...",className:"v10-sgov-state"}):d&&k.length===0?s.jsx(xe,{icon:"!",title:"Couldn't load subgraphs.",description:"Refresh the page to try again.",tone:"danger",className:"v10-sgov-state"}):k.length===0&&S.entityCount===0?s.jsx(xe,{icon:"#",title:"No subgraphs in this Context Graph yet.",description:s.jsxs(s.Fragment,{children:["A subgraph is a named topical slice of this Context Graph (e.g. ",s.jsx("code",{children:"recipes"}),", ",s.jsx("code",{children:"decisions"}),"). Agents create one when they scope an assertion to a subgraph. All current entities live in the Context Graph root."]}),actions:[{label:"View root",onClick:()=>r(Ve),variant:"primary"}],className:"v10-sgov-state"}):s.jsxs("div",{className:"v10-sgov",children:[s.jsxs("div",{className:"v10-sgov-header",children:[s.jsx("div",{className:"v10-sgov-title",children:"Subgraphs"}),s.jsxs("div",{className:"v10-sgov-sub",children:[k.length," named subgraphs · ",t.counts.total," entities · ",h," triples"]})]}),s.jsxs("div",{className:"v10-sgov-grid",children:[k.map(j=>s.jsx(or,{card:j,isHydrating:p,isFailedOrPartial:v,onNodeClick:n,onOpen:()=>r(j.slug)},j.slug)),s.jsx(or,{card:S,isHydrating:p,isFailedOrPartial:v,onNodeClick:n,onOpen:()=>r(Ve),variant:"root"},Ve)]})]})}function or({card:e,isHydrating:t=!1,isFailedOrPartial:n=!1,onNodeClick:r,onOpen:i,variant:a}){const o=f.useMemo(()=>{const d={};for(const[g,h]of e.entityTrustByUri)d[g]=nt[h];return d},[e.entityTrustByUri]),l=f.useMemo(()=>({labelMode:"humanized",renderer:"2d",labels:Nr({minZoomForLabels:.8}),style:{classColors:oa,predicateColors:aa,namespaceColors:kr(e.color),...Object.keys(o).length>0?{nodeColors:o}:{},defaultNodeColor:e.color,defaultEdgeColor:"#475569",edgeWidth:1,fontSize:12,gradient:!0,gradientIntensity:.35},hexagon:{baseSize:6,minSize:3,maxSize:16,scaleWithDegree:!0},focus:{maxNodes:5e3,hops:999}}),[e.color,o]),c=a==="root";return s.jsxs("div",{className:`v10-sgov-card${c?" root":""}`,style:c?void 0:{"--sg-color":e.color,borderColor:e.color+"55"},children:[s.jsxs("div",{className:"v10-sgov-card-head",children:[s.jsx("span",{className:"v10-sgov-card-icon",style:c?void 0:{color:e.color},children:e.icon}),s.jsxs("div",{className:"v10-sgov-card-title-wrap",children:[s.jsx("div",{className:"v10-sgov-card-title",children:e.displayName}),e.description&&s.jsx("div",{className:"v10-sgov-card-desc",title:e.description,children:e.description})]}),s.jsx("button",{type:"button",className:"v10-sgov-card-open",onClick:i,title:`Focus on ${e.displayName}`,children:"↗"})]}),s.jsxs("div",{className:"v10-sgov-card-stats",children:[s.jsxs("span",{className:"v10-sgov-card-stat",children:[s.jsx("b",{children:e.entityCount})," entities"]}),s.jsxs("span",{className:"v10-sgov-card-stat",title:t&&e.tripleCount===0?"Loading triples for this subgraph…":n?e.tripleCount===0?"Some layers unavailable; count may be incomplete.":`${e.tripleCount} triples (some layers unavailable; count may be incomplete).`:t?`${e.tripleCount} triples (still loading; count may grow).`:e.tripleCount!==e.triples.length?`${e.tripleCount} triples in this subgraph's scope; ${e.triples.length} rendered (some in-scope edges aren't drawn — either endpoints outside this subgraph, or cap-trimmed in dense buckets).`:void 0,children:[s.jsx("b",{children:t&&e.tripleCount===0?"…":e.tripleCount})," triples"]})]}),s.jsx("div",{className:"v10-sgov-card-pyramid",children:s.jsx(xi,{counts:e.layerCounts,compact:!0})}),s.jsx("div",{className:"v10-sgov-card-graph",children:e.triples.length===0?s.jsx("div",{className:"v10-sgov-card-empty",children:e.entityCount>0?"Promoted — open to view":"No data yet"}):s.jsx(f.Suspense,{fallback:s.jsx("div",{className:"v10-sgov-card-empty",children:"Loading…"}),children:s.jsx(Kn,{data:e.triples,format:"triples",options:l,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:r,initialFit:!0})})})]})}function xi({counts:e,activeLayers:t,onClickLayer:n,compact:r=!1}){const i=e.wm+e.swm+e.vm;if(i===0)return r?null:s.jsx("div",{className:"v10-minibar v10-minibar-empty",children:"No data"});const a=[{key:"verified",short:"VM",count:e.vm,color:"#22c55e",label:"Verifiable"},{key:"shared",short:"SWM",count:e.swm,color:"#f59e0b",label:"Shared"},{key:"working",short:"WM",count:e.wm,color:"#64748b",label:"Working"}],o=!!n;return s.jsxs("div",{className:`v10-minibar${r?" compact":""}`,children:[!r&&s.jsx("div",{className:"v10-minibar-bar",children:a.filter(l=>l.count>0).map(l=>{const c=l.count/i*100,d=t?t.has(l.key):!0;return s.jsx("div",{className:`v10-minibar-seg${d?"":" dim"}`,style:{width:`${c}%`,background:l.color},title:`${l.label}: ${l.count}`},l.key)})}),s.jsx("div",{className:"v10-minibar-legend",children:a.map(l=>{const c=t?t.has(l.key):!0;return s.jsxs("button",{type:"button",className:`v10-minibar-chip${c?"":" dim"}${o?" interactive":""}`,onClick:o?()=>n(l.key):void 0,disabled:!o,title:`${l.label} Memory — ${l.count} entities${o?" (click to toggle)":""}`,children:[s.jsx("span",{className:"v10-minibar-dot",style:{background:l.color}}),s.jsx("span",{className:"v10-minibar-short",children:l.short}),s.jsx("span",{className:"v10-minibar-count",children:l.count})]},l.key)})})]})}function ph({items:e,color:t,onSelectEntity:n,scrollKey:r}){const i=et(),a=It(),o=f.useMemo(()=>{const l=new Map;for(const c of e){const d=`${c.date.getFullYear()}-${String(c.date.getMonth()+1).padStart(2,"0")}`,g=l.get(d)??[];g.push(c),l.set(d,g)}return[...l.entries()].sort((c,d)=>c[0].localeCompare(d[0]))},[e]);return e.length===0?s.jsx("div",{className:"v10-subgraph-timeline-empty","data-cg-scroll-key":r,children:s.jsx(xe,{compact:!0,title:"No timeline values yet.",description:"Entities in this sub-graph do not currently expose the configured timeline field."})}):s.jsx("div",{className:"v10-subgraph-timeline","data-cg-scroll-key":r,children:o.map(([l,c])=>s.jsxs("div",{className:"v10-subgraph-timeline-bucket",children:[s.jsxs("div",{className:"v10-subgraph-timeline-bucket-head",children:[s.jsx("span",{className:"v10-subgraph-timeline-bucket-dot",style:{background:t}}),s.jsx("span",{className:"v10-subgraph-timeline-bucket-label",children:ia(l)}),s.jsx("span",{className:"v10-subgraph-timeline-bucket-count",children:c.length})]}),s.jsx("div",{className:"v10-subgraph-timeline-items",children:c.map(({entity:d,date:g})=>{const{icon:h}=dn(d,i),u=Wn(d),p=u?a==null?void 0:a.get(u):null;return s.jsxs("button",{className:"v10-subgraph-timeline-item",onClick:()=>n(d.uri),title:`${d.label} · ${g.toISOString().slice(0,10)}`,children:[s.jsx("span",{className:"v10-subgraph-timeline-item-icon",children:h}),s.jsx("span",{className:"v10-subgraph-timeline-item-label",children:d.label}),(p||u)&&s.jsx(gt,{agent:p??void 0,fallbackUri:u??void 0,size:"sm"}),s.jsx("span",{className:"v10-subgraph-timeline-item-date",children:g.toISOString().slice(0,10)})]},d.uri)})})]},l))})}function hh({slug:e,rawMemory:t,contextGraphId:n,onNodeClick:r,onSelectEntity:i,activeTab:a,onTabChange:o,initialLayer:l,initialEnabledLayers:c,onEnabledLayersChange:d,onOpenQueryCatalog:g}){const h=et(),u=h==null?void 0:h.forSubGraph(e),p=(h==null?void 0:h.chipsFor(e))??[],v=(h==null?void 0:h.savedQueryCatalogsFor(e))??[],y=u==null?void 0:u.timelinePredicate,[w,m]=f.useState("items"),b=a??w,x=b==="timeline"&&!y?"items":b,k=o??m,[S,j]=f.useState(u!=null&&u.timelinePredicate?"created-desc":"triples");f.useEffect(()=>{j(u!=null&&u.timelinePredicate?"created-desc":"triples")},[e,u==null?void 0:u.timelinePredicate]);const _=f.useMemo(()=>c&&c.size>0?new Set(c):l==="wm"?new Set(["working"]):l==="swm"?new Set(["shared"]):l==="vm"?new Set(["verified"]):new Set(["working","shared","verified"]),[l,c]),[z,E]=f.useState(_);f.useEffect(()=>{d==null||d(z)},[z,d]);const[T,$]=f.useState(new Map),[O,Z]=f.useState(null),[C,R]=f.useState(null),[G,P]=f.useState(!1),[L,A]=f.useState(null),M=e===Ve,F=f.useMemo(()=>{const U=[];for(const W of t.entityList)(M?W.subGraphs.size===0:W.subGraphs.has(e))&&U.push(W);return U},[t.entityList,e,M]),B=f.useMemo(()=>new Set(F.map(U=>U.uri)),[F]),J=f.useMemo(()=>t.graphTriples.filter(U=>Tn(U,{slug:e,isRoot:M,scopedUris:B})),[t.graphTriples,B,e,M]),X=f.useMemo(()=>{let U=0,W=0,Q=0;for(const ie of F)ie.trustLevel==="verified"?Q++:ie.trustLevel==="shared"?W++:U++;return{wm:U,swm:W,vm:Q,total:F.length}},[F]),H=f.useMemo(()=>{if(z.size!==1)return null;const U=z.values().next().value;return U==="verified"?"vm":U==="shared"?"swm":U==="working"?"wm":null},[z]),V=f.useMemo(()=>{let U=F;if(z.size<3&&(U=U.filter(W=>z.has(W.trustLevel))),T.size>0)for(const W of p){const Q=T.get(W.slug);!Q||Q.size===0||(U=U.filter(ie=>{const ae=ie.properties.get(W.predicate);return!ae||ae.length===0?!1:ae.some(ce=>Q.has(ce))}))}return C&&(U=U.filter(W=>C.has(W.uri))),U},[F,z,T,p,C]),re=f.useMemo(()=>new Set(V.map(U=>U.uri)),[V]),ye=f.useMemo(()=>V.length===F.length?J:J.filter(U=>re.has(U.subject)||re.has(U.object)),[J,F,V,re]),Te=f.useMemo(()=>{if(!H)return null;const U=H==="vm"?"verified":H==="swm"?"shared":"working",W=F.filter(ce=>{if(!ce.layers.has(U))return!1;if(T.size>0)for(const Fe of p){const Ee=T.get(Fe.slug);if(!Ee||Ee.size===0)continue;const Pe=ce.properties.get(Fe.predicate);if(!Pe||Pe.length===0||!Pe.some(ot=>Ee.has(ot)))return!1}return!(C&&!C.has(ce.uri))}),Q=new Set(W.map(ce=>ce.uri)),ie=new Set,ae=[];for(const ce of t.allTriples){if(ce.layer!==U||!Tn(ce,{slug:e,isRoot:M,scopedUris:B,requireResourceObject:!0})||!(Q.has(ce.subject)||Q.has(ce.object)))continue;const Fe=`${ce.subject}|${ce.predicate}|${ce.object}`;ie.has(Fe)||(ie.add(Fe),ae.push({subject:ce.subject,predicate:ce.predicate,object:ce.object,subGraph:ce.subGraph}))}return ae},[H,t.allTriples,B,e,M,F,p,T,C])??ye,q=f.useMemo(()=>{if(H){const U=H==="vm"?"verified":H==="swm"?"shared":"working";return F.filter(W=>{if(!W.layers.has(U))return!1;if(T.size>0)for(const Q of p){const ie=T.get(Q.slug);if(!ie||ie.size===0)continue;const ae=W.properties.get(Q.predicate);if(!ae||ae.length===0||!ae.some(ce=>ie.has(ce)))return!1}return!(C&&!C.has(W.uri))})}return V},[H,F,V,p,T,C]),ne=f.useMemo(()=>q.map(U=>({uri:U.uri,label:U.label})),[q]),se=f.useMemo(()=>{if(H)return;const U={};for(const W of q){U[W.uri]=nt[W.trustLevel];const Q=De(W.uri);Q!==W.uri&&(U[Q]=nt[W.trustLevel])}return U},[H,q]),$e=z.size===3?"All layers":H?Oe[H].title:Array.from(z).map(U=>Oe[U==="verified"?"vm":U==="shared"?"swm":"wm"].trustLabel).join(" + "),fe=f.useMemo(()=>{if(!y)return[];const U=[];for(const W of V){const Q=Vt(W,y);Q!=null&&U.push({entity:W,date:new Date(Q)})}return U.sort((W,Q)=>W.date.getTime()-Q.date.getTime()),U},[V,y]),ge=f.useMemo(()=>{const U=[...V];if((S==="created-desc"||S==="created-asc")&&y){const W=S==="created-desc"?-1:1;return U.sort((Q,ie)=>{const ae=Vt(Q,y),ce=Vt(ie,y);return ae==null&&ce==null?0:ae==null?1:ce==null?-1:(ae-ce)*W}),U}return S==="label"?(U.sort((W,Q)=>(W.label??"").localeCompare(Q.label??"")),U):(U.sort((W,Q)=>{const ie=W.tripleCount??0;return(Q.tripleCount??0)-ie}),U)},[V,S,y]),Se=S==="created-desc"?"newest first · click to open":S==="created-asc"?"oldest first · click to open":S==="label"?"A → Z · click to open":"sorted by triples · click to open",be=f.useCallback(U=>{E(W=>{const Q=new Set(W);return Q.has(U)?Q.size>1&&Q.delete(U):Q.add(U),Q})},[]),Ze=f.useCallback((U,W)=>{$(Q=>{const ie=new Map(Q),ae=new Set(ie.get(U)??[]);return ae.has(W)?ae.delete(W):ae.add(W),ae.size===0?ie.delete(U):ie.set(U,ae),ie})},[]),ue=f.useCallback(()=>{Z(null),R(null),A(null)},[]),Me=f.useCallback(async U=>{var W;if((((W=U.parameters)==null?void 0:W.length)??0)>0){g==null||g();return}P(!0),A(null),Z(U.slug);try{const Q=Nt(U),ae=(await wr(Q.sparql,{contextGraphId:n,view:Q.view,subGraphName:Q.subGraphName})).result,ce=ae.type;if(ce!=="bindings")throw new Error(`${U.name} returns ${ce==="boolean"?"an ASK result":"graph quads"} and cannot be used as an entity filter. Open it in Query Catalogue instead.`);const Fe=ae.bindings,Ee=U.resultColumn||"uri",Pe=new Set;for(const ot of Fe){const lt=ot[Ee];if(!lt)continue;const ct=typeof lt=="string"?lt:String(lt),qe=ct.startsWith("<")&&ct.endsWith(">")?ct.slice(1,-1):ct;Pe.add(qe)}R(Pe)}catch(Q){A((Q==null?void 0:Q.message)??String(Q)),R(null),Z(null)}finally{P(!1)}},[n,g]),de=(u==null?void 0:u.color)??(M?"var(--text-tertiary)":"#64748b"),bt=(u==null?void 0:u.icon)??"•",yt=(u==null?void 0:u.displayName)??e,Lt=u==null?void 0:u.description;f.useEffect(()=>{E(_),$(new Map),ue()},[e,ue,_]),f.useEffect(()=>{a||m("items")},[e,a]),f.useEffect(()=>{b!==x&&k(x)},[b,x,k]);const at=!(z.size===_.size&&[...z].every(U=>_.has(U)))||T.size>0||!!C,vn=()=>{E(new Set(_)),$(new Map),ue()};return s.jsxs("div",{className:"v10-layer-detail v10-subgraph-detail",style:{"--sg-color":de},children:[s.jsxs("div",{className:"v10-subgraph-detail-header",children:[s.jsx("span",{className:"v10-subgraph-detail-icon",style:{color:de},children:bt}),s.jsxs("div",{className:"v10-subgraph-detail-title-wrap",children:[s.jsx("div",{className:"v10-subgraph-detail-title",children:yt}),Lt&&s.jsx("div",{className:"v10-subgraph-detail-desc",children:Lt})]}),s.jsx(xi,{counts:{wm:X.wm,swm:X.swm,vm:X.vm},activeLayers:z,onClickLayer:be,compact:!0})]}),s.jsxs("div",{className:"v10-subgraph-cross-layer",children:[s.jsx("div",{className:"v10-subgraph-cross-layer-lede",children:M?"Root entities, across the three memory layers:":"This subgraph, across the three memory layers:"}),s.jsxs("div",{className:"v10-subgraph-cross-layer-strip","data-testid":"cross-layer-strip",children:[s.jsxs("button",{type:"button",className:"v10-subgraph-cross-layer-cell","data-layer":"wm","aria-pressed":z.has("working"),onClick:()=>be("working"),children:[s.jsx("span",{className:"v10-subgraph-cross-layer-cell-icon",style:{color:nt.working},children:"◇"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-label",children:"Working"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-count",children:X.wm})]}),s.jsx("span",{className:"v10-subgraph-cross-layer-arrow","aria-hidden":"true",children:"→"}),s.jsxs("button",{type:"button",className:"v10-subgraph-cross-layer-cell","data-layer":"swm","aria-pressed":z.has("shared"),onClick:()=>be("shared"),title:H==="swm"?"Showing Shared Working Memory only — graph is colored by contributing agent (see legend).":void 0,children:[s.jsx("span",{className:"v10-subgraph-cross-layer-cell-icon",style:{color:nt.shared},children:"◈"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-label",children:"Shared"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-count",children:X.swm})]}),s.jsx("span",{className:"v10-subgraph-cross-layer-arrow","aria-hidden":"true",children:"→"}),s.jsxs("button",{type:"button",className:"v10-subgraph-cross-layer-cell","data-layer":"vm","aria-pressed":z.has("verified"),onClick:()=>be("verified"),children:[s.jsx("span",{className:"v10-subgraph-cross-layer-cell-icon",style:{color:nt.verified},children:"◉"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-label",children:"Verifiable"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-count",children:X.vm})]})]}),s.jsxs("span",{className:`v10-subgraph-active-layer-pill${z.size===3?" all-layers":""}`,"data-testid":"active-layer-pill",children:[s.jsx("span",{className:"v10-subgraph-active-layer-pill-label",children:"Active layer:"}),s.jsx("span",{className:"v10-subgraph-active-layer-pill-value",children:$e})]})]}),v.length>0&&s.jsxs("div",{className:"v10-subgraph-savedqueries",children:[s.jsx("span",{className:"v10-subgraph-savedqueries-label",children:"Query catalog"}),v.map(U=>s.jsxs(Ce.Fragment,{children:[s.jsx("span",{className:"v10-subgraph-savedqueries-label",title:U.description||U.name,style:{marginLeft:8,opacity:.8},children:U.name}),U.queries.map(W=>{var ae;const Q=O===W.slug,ie=(((ae=W.parameters)==null?void 0:ae.length)??0)>0;return s.jsxs("button",{type:"button",className:`v10-subgraph-savedquery${Q?" active":""}`,onClick:()=>Q?ue():Me(W),title:ie?`${W.description||W.name} Open Query Catalogue to enter parameters.`:W.description||W.name,disabled:G&&!Q,children:[s.jsx("span",{className:"v10-subgraph-savedquery-glyph",children:ie?"↗":G&&Q?"…":Q?"✓":"◎"}),W.name]},W.slug)})]},U.slug)),L&&s.jsx("span",{className:"v10-subgraph-savedquery-error",title:L,children:"✕ query failed"}),C&&O&&s.jsxs("span",{className:"v10-subgraph-savedquery-count",children:[C.size," match",C.size===1?"":"es"]})]}),p.length>0&&s.jsxs("div",{className:"v10-subgraph-filters",children:[p.map(U=>{const W=T.get(U.slug)??new Set;return s.jsxs("div",{className:"v10-subgraph-filter-row",children:[s.jsx("span",{className:"v10-subgraph-filter-label",children:U.label}),s.jsx("div",{className:"v10-subgraph-filter-chips",children:U.values.map(Q=>{const ie=W.has(Q);return s.jsx("button",{type:"button",className:`v10-subgraph-filter-chip${ie?" active":""}`,onClick:()=>Ze(U.slug,Q),children:Q},Q)})})]},U.slug)}),at&&s.jsx("button",{type:"button",className:"v10-subgraph-filter-reset",onClick:vn,children:"Reset filters"})]}),s.jsxs("div",{className:"v10-layer-detail-body",children:[s.jsxs("div",{className:"v10-layer-expand-tabs",children:[s.jsxs("button",{className:`v10-layer-expand-tab ${x==="items"?"active":""}`,onClick:()=>k("items"),children:["Entities (",V.length,V.length!==F.length?` / ${F.length}`:"",")"]}),s.jsx("button",{className:`v10-layer-expand-tab ${x==="graph"?"active":""}`,onClick:()=>k("graph"),children:"Graph"}),y&&s.jsx("button",{className:`v10-layer-expand-tab ${x==="timeline"?"active":""}`,onClick:()=>k("timeline"),children:"Timeline"}),s.jsx("button",{className:`v10-layer-expand-tab ${x==="docs"?"active":""}`,onClick:()=>k("docs"),children:"Documents"})]}),x==="items"&&s.jsx("div",{className:"v10-layer-expand-body entities-tab","data-cg-scroll-key":`subgraph:${e}:items`,children:s.jsx(_r,{entities:ge,layerKey:"wm",layerIcon:bt,onSelectEntity:i,externallySorted:!0,sortLabel:Se,timestampPredicate:y,perEntityTrustBadge:!0,headerExtra:s.jsxs("label",{className:"v10-entity-list-sort",children:[s.jsx("span",{className:"v10-entity-list-sort-label",children:"Sort"}),s.jsxs("select",{className:"v10-entity-list-sort-select",value:S,onChange:U=>j(U.target.value),"aria-label":"Sort entities",children:[y&&s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"created-desc",children:"Newest first"}),s.jsx("option",{value:"created-asc",children:"Oldest first"})]}),s.jsx("option",{value:"triples",children:"Most triples"}),s.jsx("option",{value:"label",children:"Label (A→Z)"})]})]})})}),x==="graph"&&s.jsx("div",{className:"v10-layer-expand-body full-width","data-cg-scroll-key":`subgraph:${e}:graph`,children:s.jsx(Cr,{layer:H??"wm",triples:Te,onNodeClick:r,contextGraphId:n,title:yt,scopeLabel:`Subgraph graph: ${yt} entities and entity-to-entity triples from loaded subgraph data.`,trustLegendActiveLayer:H,scopeEntities:ne,layerEntities:q,nodeColorsOverride:se})}),x==="timeline"&&y&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(ph,{items:fe,color:de,onSelectEntity:i,scrollKey:`subgraph:${e}:timeline`})}),x==="docs"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(Ar,{entities:V,contextGraphId:n,scrollKey:`subgraph:${e}:docs`})})]})]})}const mh={wm:"items",swm:"items",vm:"items"},lr={wm:"working",swm:"shared",vm:"verified"};function Rn(e){return e==="wm"||e==="swm"||e==="vm"}function fh(e){const t=new Set;return e.filter(n=>{const r=`${De(n.subject)}|${n.predicate}|${De(n.object)}`;return t.has(r)?!1:(t.add(r),!0)})}function cr(e,t){if(typeof document>"u")return t;const n=document.querySelectorAll("[data-cg-scroll-key]");for(const r of n)if(r.dataset.cgScrollKey===e)return r;return t}function Nh({contextGraphId:e}){const{data:t,error:n,loading:r,refresh:i}=ft($t.fetchContextGraphs,[],3e4),[a,o]=f.useState(!1),[l,c]=f.useState(!1),[d,g]=f.useState("overview"),[h,u]=f.useState(!1),[p,v]=f.useState(null);f.useEffect(()=>{u(!1)},[e]);const[y,w]=f.useState({contextGraphId:null,list:[],status:"loading"}),[m,b]=f.useState(null),[x,k]=f.useState(!1),S=f.useRef(0),[j,_]=f.useState(null),[z,E]=f.useState(null),T=f.useRef(null),[$,O]=f.useState(null),Z=f.useCallback(D=>{T.current=D,O(D)},[]),C=f.useRef(null),R=f.useCallback(D=>{C.current=D,D===null&&(T.current=null,O(null)),_(D)},[]),[G,P]=f.useState(null),L=f.useRef(null);f.useEffect(()=>{L.current=p},[p]);const[A,M]=f.useState(mh),[F,B]=f.useState({}),J=f.useRef(null),X=f.useRef(null),H=f.useRef(null),V=f.useRef(0),re=ga(e),ye=va(e),Ne=Vn(D=>D.openTab),{data:Te,loading:q,error:ne}=la(),se=f.useCallback(()=>j?`subgraph:${j}:${F[j]??"items"}`:Rn(d)?`layer:${d}:${A[d]}`:"page",[d,j,A,F]),$e=f.useCallback(D=>{const te=D??se(),le=cr(te,J.current);return{activeLayer:d,activeSubGraph:j,layerTabs:{...A},subGraphTabs:{...F},scroll:{key:te,top:(le==null?void 0:le.scrollTop)??0},subGraphEnabledLayers:j!==null&&T.current?new Set(T.current):null}},[d,j,se,A,F]),fe=f.useCallback(D=>{const te=()=>{const le=cr(D.key,J.current);le&&(le.scrollTop=D.top)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(te):setTimeout(te,0)},[]),ge=f.useCallback((D,te)=>{(!L.current||!X.current)&&(X.current=$e(te)),v(D)},[$e]),Se=f.useCallback(()=>{X.current=null},[]);f.useEffect(()=>{if(p)return;const D=H.current;D&&(H.current=null,fe(D))},[p,d,j,A,F,fe]),f.useEffect(()=>{const D=te=>{const le=te.detail;le&&le.contextGraphId===e&&typeof le.entityUri=="string"&&(P(null),ge(le.entityUri))};return window.addEventListener("v10:open-entity",D),()=>window.removeEventListener("v10:open-entity",D)},[e,ge]);const be=f.useCallback(D=>{var ze;const te=D.startsWith("urn:dkg:agent:")?D.slice(14):D,le=((ze=ye.get(D))==null?void 0:ze.name)??te;Ne({id:`agent:${e}|${te}`,label:`@ ${le}`,closable:!0})},[ye,e,Ne]),Ze=f.useMemo(()=>({...ye,openAgent:be}),[ye,be]),ue=f.useMemo(()=>{var D;return(D=t==null?void 0:t.contextGraphs)==null?void 0:D.find(te=>te.id===e)},[t,e]),de=ca(e,{signalErrors:!0,includeQueryCatalog:h&&(d==="wm"||d==="swm")}),bt=Bn(de).total,yt=pa({activeLayer:d,activeSubGraph:j}),Lt=Sr(yt?e:void 0),Mt=!j&&d==="overview",at=Da(Mt?e:void 0),vn=Mt?at.resultContextGraphId===e?at.events:[]:void 0,U=Mt&&at.resultContextGraphId===e?at.error:null,W=f.useCallback(()=>{const D=ue==null?void 0:ue.id;if(!D)return;const te=V.current+1;V.current=te,w({contextGraphId:D,list:[],status:"loading"}),$t.listParticipants(D).then(le=>{V.current===te&&w({contextGraphId:D,list:le.allowedAgents,status:"ok"})}).catch(()=>{V.current===te&&w({contextGraphId:D,list:[],status:"error"})})},[ue==null?void 0:ue.id]);f.useEffect(()=>{W()},[W]);const Q=f.useCallback(()=>{const D=++S.current;$t.fetchSubGraphs(e).then(te=>{if(S.current!==D)return;const le=(te.subGraphs??[]).filter(Qn).length;b(le),k(!1)}).catch(()=>{S.current===D&&(b(null),k(!0))})},[e]);f.useEffect(()=>{b(null),k(!1),Q()},[Q]),mr(e,Q);const ie=G?lr[G]:null,ae=f.useMemo(()=>ie?de.allTriples.filter(D=>D.layer===ie):de.graphTriples,[de.allTriples,de.graphTriples,ie]),ce=f.useMemo(()=>ie?fh(ae):ae,[ae,ie]),Fe=f.useMemo(()=>ie?ua(ae):de.entities,[ae,de.entities,ie]),Ee=f.useMemo(()=>p?Fe.get(p)??null:null,[p,Fe]);f.useEffect(()=>{!p||Ee||de.loading||(v(null),P(null),Se())},[p,Ee,de.loading,Se]);const Pe=f.useCallback((D,te)=>{const le=C.current;if(Se(),R(D),D===null)E(null);else if(te!==void 0){const ze=new Set([lr[te]]);E(ze),T.current=ze,O(ze)}else{if(le!==null&&D===le)return;if(le!==null&&T.current){const ze=new Set(T.current);E(ze),T.current=ze,O(ze)}else E(null),T.current=null,O(null)}v(null),P(null)},[Se,R]),ot=f.useCallback(D=>{Se(),g(D),v(null),P(null),R(null),E(null)},[Se,R]),lt=f.useCallback((D,te)=>{M(le=>le[D]===te?le:{...le,[D]:te})},[]),ct=f.useCallback((D,te)=>{B(le=>le[D]===te?le:{...le,[D]:te})},[]),qe=f.useCallback((D,te,le)=>{const ze=L.current!=null;ge(D,te),P(Ei=>le??(ze?Ei:null))},[ge]),ji=f.useCallback(()=>{const D=X.current;if(X.current=null,v(null),P(null),!!D){if(g(D.activeLayer),R(D.activeSubGraph),D.activeSubGraph!==null&&D.subGraphEnabledLayers){const te=new Set(D.subGraphEnabledLayers);E(te),T.current=te,O(te)}M(D.layerTabs),B(D.subGraphTabs),H.current=D.scroll}},[R]),bn=f.useCallback(D=>{if(!(D!=null&&D.id))return;const te=Rn(D.trustLayer)?D.trustLayer:void 0;qe(D.id,void 0,te)},[qe]),wi=f.useCallback(D=>{const te=Rn(d)?d:void 0;qe(D,void 0,te)},[d,qe]),ki=f.useCallback(D=>{qe(D,"page")},[qe]),ls=f.useCallback(()=>{Ne(da)},[Ne]),yn=!!n&&/authentication|unauthor|expired|sign in|log in/i.test(n);if(!ue)return n||t&&!r?s.jsxs("div",{className:"v10-view-placeholder",children:[s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:12,marginBottom:10},children:n?yn?n:"Failed to load context graph.":"Context graph not found."}),yn?s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:()=>window.location.reload(),children:"Refresh page"}):s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:i,children:"Retry"})]}):s.jsx("div",{className:"v10-view-placeholder",children:s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:12},children:"Loading context graph..."})});const Ni=j?re.forSubGraph(j):null,xn=!de.loading&&!de.error&&!de.partial?de.entityList:void 0,Si=Ee?"entity":j?"subgraph":d,Ci=y.contextGraphId===ue.id?y.list:[],$i=y.contextGraphId===ue.id?y.status:"loading";return s.jsx(ba.Provider,{value:re,children:s.jsx(ya.Provider,{value:Ze,children:s.jsxs("div",{className:"v10-memory-explorer",children:[n&&s.jsx("div",{className:"v10-stale-banner",role:"status",children:yn?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:n}),s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:()=>window.location.reload(),children:"Refresh page"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Couldn’t refresh context-graph data — showing last known values."}),s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:i,children:"Retry"})]})}),s.jsx(Xa,{cg:ue,profile:re,activeSubGraph:Ni,onClearSubGraph:()=>Pe(null)}),s.jsx(Ha,{active:d,counts:de.counts,onSwitch:ot,onShare:()=>c(!0),onImport:()=>o(!0),onRefresh:de.refresh}),s.jsxs("main",{className:"v10-memory-explorer-page","data-view":Si,"data-cg-scroll-key":"page",ref:J,children:[Ee&&s.jsx(ch,{entity:Ee,allEntities:Fe,allTriples:ce,onNavigate:qe,onClose:ji,contextGraphId:e,onRefresh:de.refresh}),j&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(ar,{}),s.jsx(wn,{contextGraphId:e,profile:re,selected:j,entities:xn,onSelect:Pe,enabledScope:$??void 0,allTriplesTotal:bt}),s.jsx(hh,{slug:j,rawMemory:de,contextGraphId:e,onNodeClick:bn,onSelectEntity:qe,activeTab:F[j]??"items",onTabChange:D=>ct(j,D),initialEnabledLayers:z??void 0,onEnabledLayersChange:Z,onOpenQueryCatalog:()=>{R(null),g("query")}})]}),!j&&d==="overview"&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(io,{cg:ue,memory:de,subGraphCount:m,subGraphFetchFailed:x,participants:Ci,participantsStatus:$i,currentAgent:Te??null,currentAgentStatus:q?"loading":ne?"error":"ok",onSwitchLayer:ot,onOpenPrimer:ls}),s.jsx(ao,{contextGraphId:e,curatorStatus:so({cg:ue,currentAgent:Te??null,currentAgentStatus:q?"loading":ne?"error":"ok"}),onParticipantsChanged:W}),de.loading&&s.jsx("div",{className:"v10-me-loading",children:s.jsx("div",{className:"v10-me-loading-text",children:"Loading memory..."})}),de.error&&s.jsxs("div",{className:"v10-me-error",children:["Error: ",de.error]}),s.jsx("div",{"data-section":"activity",children:s.jsx(xa,{entities:de.entityList,lifecycleEvents:vn,lifecycleError:U,onSelectEntity:ki,title:"Recent activity",limit:40,includeUndated:!1,emptyHint:"Once knowledge starts being added and managed in this context graph, activities will show up here as a live feed.",className:"v10-overview-activity"})}),s.jsx(oo,{onOpenPrimer:ls})]}),!j&&d==="graph-overview"&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(ar,{}),s.jsx(wn,{contextGraphId:e,profile:re,selected:null,entities:xn,onSelect:Pe,allTriplesTotal:bt}),s.jsx(dh,{contextGraphId:e,memory:de,onNodeClick:bn,onSelectSubGraph:Pe})]}),!j&&d==="query"&&!Ee&&s.jsx(zo,{contextGraphId:e}),!j&&(d==="wm"||d==="swm"||d==="vm")&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(wn,{contextGraphId:e,profile:re,selected:j,entities:xn,onSelect:Pe,layer:d}),s.jsx(So,{layer:d,memory:de,onNodeClick:bn,onSelectEntity:wi,contextGraphId:e,activeTab:A[d],onTabChange:D=>lt(d,D),swmAttribution:Lt,showQueryCatalog:h,onShowQueryCatalogChange:u})]})]}),s.jsx(_a,{open:a,onClose:()=>o(!1),contextGraphId:ue.id,contextGraphName:ue.name}),s.jsx(Ra,{open:l,onClose:()=>c(!1),contextGraphId:ue.id,contextGraphName:ue.name})]})})})}export{Nh as ProjectView};
290
+ `))r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&(n+=r.slice(5).trim());if(!n)return null;try{const r=JSON.parse(n);switch(t){case"start":return{type:"start",...r};case"delta":return{type:"delta",text:r.text??""};case"final":return{type:"final",content:r.content??""};case"error":return{type:"error",error:r.error??"unknown error"};case"done":return{type:"done"};default:return null}}catch{return null}}const ah=({contextGraphId:e,entityUri:t,placeholder:n,fallback:r})=>{const[i,a]=Ce.useState(""),[o,l]=Ce.useState(!0),[c,d]=Ce.useState(null);return Ce.useEffect(()=>{const g=new AbortController;let h="";return a(""),d(null),l(!0),(async()=>{try{const u=rh();for await(const p of ih({contextGraphId:e,entityUri:t,libraryPrompt:u,signal:g.signal}))if(p.type==="delta")h+=p.text,a(h);else if(p.type==="final")p.content&&(h=p.content,a(p.content));else if(p.type==="error"){d(p.error);break}else if(p.type==="done")break}catch(u){u.name!=="AbortError"&&d(u.message)}finally{l(!1)}})(),()=>g.abort()},[e,t]),c?r?s.jsx(s.Fragment,{children:r(c)}):s.jsx(lh,{error:c}):!i&&o?s.jsx(s.Fragment,{children:n??s.jsx("div",{className:"v10-genui-loading",children:"Composing detail view…"})}):s.jsx("div",{className:"v10-genui-panel",children:s.jsx(_p,{response:i,library:xi,isStreaming:o})})},oh="LLM not configured",lh=({error:e})=>{const t=Vn(r=>r.openTab);return e.includes(oh)?s.jsxs("div",{className:"v10-genui-error v10-genui-error-cta",children:[s.jsxs("div",{className:"v10-genui-error-head",children:[s.jsx("span",{className:"v10-genui-error-icon",children:"⚙"}),s.jsxs("div",{children:[s.jsx("div",{className:"v10-genui-error-title",children:"Set up your LLM to enable GenUI"}),s.jsx("div",{className:"v10-genui-error-desc",children:"GenUI streams entity detail views from an OpenAI-compatible model. Add an API key in Settings and open this entity again."})]})]}),s.jsx("button",{className:"v10-genui-error-cta-btn",onClick:()=>t({id:"settings",label:"Settings",closable:!0}),children:"Open Settings →"})]}):s.jsxs("div",{className:"v10-genui-error",children:["GenUI unavailable: ",e]})};function ir({entity:e,profile:t}){const n=f.useMemo(()=>{for(const l of e.subGraphs)if(l!=="meta")return l;return null},[e.subGraphs]);if(!n||!t)return null;const r=t.forSubGraph(n),i=(r==null?void 0:r.color)??"#64748b",a=(r==null?void 0:r.icon)??"•",o=(r==null?void 0:r.displayName)??n;return s.jsxs("span",{className:"v10-subgraph-badge",style:{"--sg-color":i},title:`In sub-graph: ${o}`,children:[s.jsx("span",{className:"v10-subgraph-badge-icon",style:{color:i},children:a}),s.jsx("span",{className:"v10-subgraph-badge-label",children:o})]})}function ch({entity:e,contextGraphId:t,onVerified:n}){const r=et(),[i,a]=f.useState(!1),[o,l]=f.useState(null),[c,d]=f.useState(null),[g,h]=f.useState(null),u=e.trustLevel,p=f.useMemo(()=>{if(!r)return null;for(const x of e.types){const k=r.forType(x);if(k&&(u==="working"&&(k.promoteLabel||k.promoteHint)||u==="shared"&&(k.publishLabel||k.publishHint)))return k}return null},[e.types,r,u]),v=f.useMemo(()=>{if(!r)return null;for(const x of e.subGraphs){if(x==="meta")continue;const k=r.forSubGraph(x);if(k!=null&&k.sourceAssertion)return{binding:k,subGraph:x}}return null},[e.subGraphs,r]);if(u==="verified"||!p)return null;const y=u==="working"?{kind:"promote",label:p.promoteLabel??"Promote to Shared Memory",hint:p.promoteHint??"Shares the complete owning Knowledge Asset with the team.",busyCopy:"Sharing…",disabled:!(v!=null&&v.binding.sourceAssertion),disabledReason:v!=null&&v.binding.sourceAssertion?null:`No sourceAssertion declared on the sub-graph profile — add profile:sourceAssertion to the SubGraphBinding for "${[...e.subGraphs].filter(x=>x!=="meta")[0]??"?"}".`}:{kind:"publish",label:p.publishLabel??"Verify on DKG",hint:p.publishHint??"Publishes the complete owning Knowledge Asset on-chain.",busyCopy:"Anchoring…",disabled:!(v!=null&&v.binding.sourceAssertion),disabledReason:v!=null&&v.binding.sourceAssertion?null:"This entity is not part of a named Shared-Memory asset, so it cannot be published to Verifiable Memory from here."},w=async()=>{if(y.disabled)return;a(!0),h(null),l(null),d(y.kind);const x=(v==null?void 0:v.binding.sourceAssertion)??"assertion";try{if(y.kind==="promote"){const k=await Xt(t,v.binding.sourceAssertion,v.subGraph?{subGraphName:v.subGraph}:{});l(jr(x,k))}else{const k=await wr(t,v.binding.sourceAssertion,v.subGraph?{subGraphName:v.subGraph}:{});l(k)}n()}catch(k){const N=y.kind==="promote"?en(x,k):null,j=N?N.message:(k==null?void 0:k.message)??"Action failed";h(j)}finally{a(!1)}},m=x=>!!x&&"status"in x,b=x=>!!x&&"kind"in x;return s.jsxs("div",{className:`v10-ka-verify v10-ka-verify-${y.kind}`,children:[s.jsxs("div",{className:"v10-ka-verify-head",children:[s.jsx("span",{className:"v10-ka-verify-arrow",children:y.kind==="promote"?"◈":"◉"}),s.jsx("span",{className:"v10-ka-verify-title",children:y.label})]}),s.jsx("div",{className:"v10-ka-verify-hint",children:y.hint}),y.disabledReason&&s.jsxs("div",{className:"v10-ka-verify-err",children:["! ",y.disabledReason]}),!o&&s.jsx("button",{className:`v10-ka-verify-btn ${y.kind}`,onClick:w,disabled:i||y.disabled,children:i?y.busyCopy:y.label}),g&&s.jsxs("div",{className:"v10-ka-verify-err",children:["✕ ",g]}),o&&c==="promote"&&b(o)&&o.kind==="success"&&s.jsxs("div",{className:"v10-ka-verify-ok",children:[s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Promoted"}),s.jsxs("span",{className:"v10-ka-verify-ok-val",children:["✓ ",o.promotedCount," triple",o.promotedCount===1?"":"s"," now in Shared Memory"]})]}),s.jsx("div",{className:"v10-ka-verify-hint",style:{marginTop:6},children:"Refresh the entity to see the next step appear."})]}),o&&c==="promote"&&b(o)&&o.kind!=="success"&&s.jsxs("div",{className:"v10-ka-verify-err",children:["! ",o.message]}),o&&c==="publish"&&m(o)&&(()=>{var N,j;const x=o.status==="confirmed"&&!!o.txHash,k=x&&!!o.contextGraphError;return s.jsxs("div",{className:x?k?"v10-ka-verify-warn":"v10-ka-verify-ok":"v10-ka-verify-err",children:[s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Status"}),s.jsxs("span",{className:"v10-ka-verify-ok-val",children:[x?k?"⚠":"✓":"✕"," ",o.status,x?k?` (${na})`:"":" (NOT on-chain)"]})]}),k&&s.jsx("div",{className:"v10-ka-verify-hint",style:{marginTop:6},children:tn(o.contextGraphError)}),o.txHash?s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"TX hash"}),s.jsx("span",{className:"v10-ka-verify-ok-val mono",title:o.txHash,children:o.txHash})]}):s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"TX hash"}),s.jsx("span",{className:"v10-ka-verify-ok-val",children:"none — on-chain submission skipped"})]}),o.blockNumber!=null&&s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Block"}),s.jsxs("span",{className:"v10-ka-verify-ok-val mono",children:["#",o.blockNumber]})]}),((j=(N=o.kas)==null?void 0:N[0])==null?void 0:j.tokenId)&&s.jsxs("div",{className:"v10-ka-verify-ok-row",children:[s.jsx("span",{className:"v10-ka-verify-ok-lbl",children:"Token"}),s.jsxs("span",{className:"v10-ka-verify-ok-val mono",children:["#",o.kas[0].tokenId]})]})]})})()]})}function uh({entity:e,allEntities:t,allTriples:n,onNavigate:r,onClose:i,contextGraphId:a,onRefresh:o,onOpenAgent:l}){const[c,d]=f.useState("content"),g=fr($=>$.theme),h=et(),u=It(),{icon:p,type:v}=dn(e,h),y=Xi(e),w=Wn(e),m=w?(u==null?void 0:u.get(w))??null:null,b=e.trustLevel==="verified"?"vm":e.trustLevel==="shared"?"swm":"wm",x=e.trustLevel==="verified"?"Verifiable Memory":e.trustLevel==="shared"?"Shared Working Memory":"Working Memory",k=We(e.trustLevel,1),N=f.useMemo(()=>{const $=[];for(const[,R]of t)for(const G of R.connections)G.targetUri===e.uri&&$.push({pred:ut(G.predicate),entity:R});return $},[e.uri,t]),j=f.useMemo(()=>n.filter($=>De($.subject)===e.uri||De($.object)===e.uri),[e.uri,n]),_=f.useMemo(()=>ea(e.uri,n,1),[e.uri,n]),z=f.useMemo(()=>{const $=new Set;for(const R of t.values())ta(R)&&$.add(De(R.uri));return $},[t]),E=f.useMemo(()=>new Set([De(e.uri)]),[e.uri]),T=f.useMemo(()=>Ht(_,z,{focalSubjects:E}),[_,z,E]),C=f.useMemo(()=>{const $=nt[e.trustLevel];return{labelMode:"humanized",renderer:"2d",labels:Sr({minZoomForLabels:.2}),style:{namespaceColors:Nr($),defaultNodeColor:$,defaultEdgeColor:"#475569",edgeWidth:1,fontSize:11},hexagon:{baseSize:7,minSize:4,maxSize:10,scaleWithDegree:!0},focus:{maxNodes:500,hops:999}}},[e.trustLevel]),O=f.useMemo(()=>({name:`entity-${e.uri}-${g}`,palette:g,focal:{uri:e.uri,sizeMultiplier:2.4}}),[e.uri,g]),Z=j.length;return s.jsxs("div",{className:"v10-ka-detail",children:[s.jsxs("div",{className:"v10-ka-header",children:[s.jsx("button",{className:"v10-ka-back",onClick:i,children:"← Back to Context Graph"}),s.jsxs("div",{className:"v10-ka-header-left",children:[s.jsx("div",{className:"v10-ka-label",children:k}),s.jsxs("div",{className:"v10-ka-name",children:[p," ",e.label,s.jsx("span",{className:`v10-trust-badge ${b}`,children:x})]}),s.jsxs("div",{className:"v10-ka-ual",children:[e.uri," · ",v," · ",Z," triples"]})]}),(m||w)&&s.jsxs("div",{className:"v10-ka-header-author",children:[s.jsx("div",{className:"v10-ka-header-author-label",children:"Proposed by"}),s.jsx(gt,{agent:m??void 0,fallbackUri:w??void 0,size:"lg",showOperator:!0,onOpenAgent:l})]})]}),s.jsxs("div",{className:"v10-ka-split",children:[s.jsxs("div",{className:"v10-ka-left",children:[s.jsxs("div",{className:"v10-content-tabs",style:{margin:"0 -20px",padding:"0 20px",background:"transparent"},children:[s.jsx("button",{className:`v10-content-tab ${c==="content"?"active":""}`,onClick:()=>d("content"),children:"Content"}),s.jsx("button",{className:`v10-content-tab ${c==="triples"?"active":""}`,onClick:()=>d("triples"),children:"Triples"}),s.jsx("button",{className:`v10-content-tab ${c==="graph"?"active":""}`,onClick:()=>d("graph"),children:"Graph"})]}),c==="content"&&s.jsxs(s.Fragment,{children:[!e.types.map(R=>h==null?void 0:h.forType(R)).find(R=>R==null?void 0:R.detailHint)||!(h!=null&&h.contextGraphId)?null:s.jsx("div",{className:"v10-ka-section",children:s.jsx(ah,{contextGraphId:h.contextGraphId,entityUri:e.uri})}),y&&s.jsx("div",{className:"v10-ka-section",children:s.jsx("div",{className:"v10-ka-desc",children:s.jsx("p",{children:y})})}),e.properties.size>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsx("div",{className:"v10-ka-section-title",children:"Properties"}),[...e.properties].map(([$,R])=>s.jsxs("div",{className:"v10-ka-prop",children:[s.jsx("span",{className:"v10-ka-prop-key",children:ut($)}),s.jsx("span",{className:"v10-ka-prop-val",children:R.join(", ")})]},$))]}),e.connections.length>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsxs("div",{className:"v10-ka-section-title",children:["References (",e.connections.length,")"]}),e.connections.map(($,R)=>{const G=t.get($.targetUri);return s.jsxs("button",{className:"v10-ka-conn",onClick:()=>r($.targetUri),children:[s.jsx("span",{className:"v10-ka-conn-pred",children:ut($.predicate)}),s.jsx("span",{className:"v10-ka-conn-arrow",children:"→"}),s.jsx("span",{className:"v10-ka-conn-target",children:$.targetLabel}),G&&s.jsx(ir,{entity:G,profile:h})]},R)})]}),N.length>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsxs("div",{className:"v10-ka-section-title",children:["Referenced by (",N.length,")"]}),N.map(($,R)=>s.jsxs("button",{className:"v10-ka-conn",onClick:()=>r($.entity.uri),children:[s.jsx("span",{className:"v10-ka-conn-target",children:$.entity.label}),s.jsx(ir,{entity:$.entity,profile:h}),s.jsx("span",{className:"v10-ka-conn-arrow",children:"→"}),s.jsx("span",{className:"v10-ka-conn-pred",children:$.pred})]},R))]}),s.jsxs("div",{className:"v10-ka-meta",children:[s.jsxs("span",{className:"v10-ka-meta-item",children:[p," ",v]}),s.jsxs("span",{className:"v10-ka-meta-item",children:[Z," triples"]}),s.jsxs("span",{className:"v10-ka-meta-item",children:[e.connections.length," links"]})]})]}),c==="triples"&&s.jsxs("div",{style:{marginTop:8,overflowX:"auto",border:"1px solid var(--border-default)",borderRadius:6},children:[s.jsxs("table",{className:"v10-ka-triples-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Subject"}),s.jsx("th",{children:"Predicate"}),s.jsx("th",{children:"Object"})]})}),s.jsx("tbody",{children:j.slice(0,50).map(($,R)=>s.jsxs("tr",{children:[s.jsx("td",{title:$.subject,children:ut($.subject)}),s.jsx("td",{title:$.predicate,children:ut($.predicate)}),s.jsx("td",{title:$.object,children:$.object.startsWith('"')?vr($.object).slice(0,60):ut($.object)})]},R))})]}),s.jsxs("div",{style:{fontSize:10,color:"var(--text-tertiary)",fontFamily:"var(--font-mono)",padding:"6px 8px"},children:[Math.min(j.length,50)," of ",j.length," triples shown"]})]}),c==="graph"&&s.jsx(Qt,{title:`${e.label} graph`,scopeLabel:`Entity detail graph: 1-hop neighborhood around ${e.label}.`,tone:b,className:"v10-ka-graph-shell",renderGraph:$=>T.length>0?s.jsx(f.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Kn,{data:T,format:"triples",options:C,viewConfig:O,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:R=>(R==null?void 0:R.id)&&R.id!==e.uri&&r(R.id),initialFit:!0,initialFocus:e.uri},`${e.uri}:${$?"expanded":"inline"}`)}):s.jsx("div",{className:"v10-graph-placeholder v10-graph-placeholder-centered",children:"No neighborhood data"})})]}),s.jsxs("div",{className:"v10-ka-right",children:[s.jsx(Mo,{contextGraphId:a,entityUri:e.uri,enabled:e.trustLevel==="verified"}),s.jsx("div",{className:"v10-ka-section-title",children:"Provenance Trail"}),s.jsx(dh,{entity:e}),s.jsx(ch,{entity:e,contextGraphId:a,onVerified:o}),s.jsxs("div",{style:{marginTop:16,padding:"10px 12px",borderRadius:6,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)"},children:[s.jsx("div",{className:"v10-ka-section-title",style:{marginBottom:6},children:"Entity Summary"}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:4,fontSize:10},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Type"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:v})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Triples"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:Z})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Links"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:e.connections.length})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[s.jsx("span",{style:{color:"var(--text-tertiary)"},children:"Layer"}),s.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontFamily:"var(--font-mono)"},children:x.split(" ")[0]})]})]})]})]})]})]})}function dh({entity:e}){const t=It(),n=o=>{const l=sa(e,o),c=ra(e,o),d=l?t==null?void 0:t.get(l):null;return{uri:l,at:c,agent:d}},r=n("created"),i=n("promoted"),a=n("published");return s.jsxs("div",{className:"v10-ka-timeline",children:[e.trustLevel==="verified"&&s.jsx(An,{toneClass:"verified",title:"Published to Verifiable Memory",actionWord:"Published",agent:a.agent,agentUri:a.uri,at:a.at}),(e.trustLevel==="shared"||e.trustLevel==="verified")&&s.jsx(An,{toneClass:"shared",title:"Promoted to Shared Working Memory",actionWord:"Promoted",agent:i.agent,agentUri:i.uri,at:i.at}),s.jsx(An,{toneClass:"created",title:"Created in Working Memory",actionWord:"Created",agent:r.agent,agentUri:r.uri,at:r.at})]})}function An({toneClass:e,title:t,actionWord:n,agent:r,agentUri:i,at:a}){const o=a?ia(a):null;return s.jsxs("div",{className:"v10-ka-event",children:[s.jsx("div",{className:`v10-ka-event-dot ${e}`}),s.jsxs("div",{className:"v10-ka-event-header",children:[s.jsx("span",{className:"v10-ka-event-title",children:t}),o&&s.jsx("time",{className:"v10-ka-event-time",dateTime:a??void 0,children:o})]}),(r||i)&&s.jsxs("div",{className:"v10-ka-event-attribution",children:[s.jsxs("span",{className:"v10-ka-event-attribution-prefix",children:[n," by"]}),s.jsx(gt,{agent:r??void 0,fallbackUri:i??void 0,size:"sm"})]})]})}function ar(){return s.jsxs("div",{className:"v10-subgraph-explorer-header",children:[s.jsx("div",{className:"v10-subgraph-explorer-title",children:"Subgraph Explorer"}),s.jsx("p",{className:"v10-subgraph-explorer-intro",children:"Subgraphs are optional topical partitions inside this Context Graph. An entity belongs to one or more memory layers and, optionally, to one or more subgraphs. Entities in no subgraph live in the context graph root."})]})}function ph({contextGraphId:e,memory:t,onNodeClick:n,onSelectSubGraph:r}){const i=et(),[a,o]=f.useState([]),[l,c]=f.useState(!0),[d,g]=f.useState(null);f.useEffect(()=>{let j=!1;return c(!0),g(null),$t.fetchSubGraphs(e).then(_=>{j||o(_.subGraphs??[])}).catch(_=>{j||g(_ instanceof Error?_.message:"Failed to load subgraphs")}).finally(()=>{j||c(!1)}),()=>{j=!0}},[e]);const{total:h}=Bn(t),u=Object.values(t.layerStatus??{}),p=t.loading||u.some(j=>j==="loading"),v=t.error!==null||t.partial||u.some(j=>j==="error"),y=f.useMemo(()=>{const j=new Map;for(const _ of t.entityList){const z=De(_.uri);for(const E of _.subGraphs){let T=j.get(E);T||(T=new Set,j.set(E,T)),T.add(z)}}return j},[t.entityList]),{triplesBySubGraph:w,tripleCountBySubGraph:m}=f.useMemo(()=>{const j=new Map;for(const E of t.allTriples){if(!E.subGraph)continue;let T=j.get(E.subGraph);T||(T=[],j.set(E.subGraph,T)),T.push(E)}for(const E of t.allTriples)if(!E.subGraph){for(const[T,C]of y)if(Rn(E,{slug:T,isRoot:!1,scopedUris:C})){let O=j.get(T);O||(O=[],j.set(T,O)),O.push(E)}}const _=new Map,z=new Map;for(const[E,T]of j){const O=ms(T,t.entities).map(Z=>({subject:Z.subject,predicate:Z.predicate,object:Z.object}));z.set(E,O.length),_.set(E,ys(O))}return{triplesBySubGraph:_,tripleCountBySubGraph:z}},[t.allTriples,t.entities,y]),b=f.useMemo(()=>{const j=new Map;for(const _ of t.entityList)for(const z of _.subGraphs){let E=j.get(z);E||(E={wm:0,swm:0,vm:0},j.set(z,E)),_.trustLevel==="verified"?E.vm++:_.trustLevel==="shared"?E.swm++:E.wm++}return j},[t.entityList]),x=f.useMemo(()=>{const j=new Map;for(const _ of t.entityList){const z=De(_.uri);for(const E of _.subGraphs){let T=j.get(E);T||(T=new Map,j.set(E,T)),T.set(z,_.trustLevel),z!==_.uri&&T.set(_.uri,_.trustLevel)}}return j},[t.entityList]),k=f.useMemo(()=>a.filter(Qn).map(j=>{const _=(i==null?void 0:i.forSubGraph(j.name))??{},z=w.get(j.name)??[],E=y.get(j.name)??new Set,T=x.get(j.name)??new Map;return{slug:j.name,icon:_.icon??"•",color:_.color??"#64748b",displayName:_.displayName??j.name,description:_.description,rank:_.rank??99,entityCount:E.size>0?E.size:j.entityCount,tripleCount:m.get(j.name)??0,triples:Ht(z,E),layerCounts:b.get(j.name)??{wm:0,swm:0,vm:0},entityTrustByUri:T}}).sort((j,_)=>j.rank-_.rank),[a,i,w,m,b,y,x]),N=f.useMemo(()=>{const j=[],_=new Set,z=new Map;let E=0,T=0,C=0;for(const L of t.entityList){if(L.subGraphs.size>0)continue;j.push(L);const A=De(L.uri);_.add(A),z.set(A,L.trustLevel),A!==L.uri&&z.set(L.uri,L.trustLevel),L.trustLevel==="verified"?C++:L.trustLevel==="shared"?T++:E++}const O=t.allTriples.filter(L=>!L.subGraph),Z=ms(O,t.entities).map(L=>({subject:L.subject,predicate:L.predicate,object:L.object})),$=Z.length,R=Ht(Z,_),G=ys(R),P=(i==null?void 0:i.forSubGraph(Ve))??{};return{slug:Ve,icon:P.icon??"⊘",color:P.color??"#64748b",displayName:P.displayName??"Root",description:P.description,rank:999,entityCount:j.length,tripleCount:$,triples:G,layerCounts:{wm:E,swm:T,vm:C},entityTrustByUri:z}},[t.entityList,t.allTriples,t.entities,i]);return l&&k.length===0?s.jsx(xe,{compact:!0,icon:"#",title:"Loading subgraphs...",className:"v10-sgov-state"}):d&&k.length===0?s.jsx(xe,{icon:"!",title:"Couldn't load subgraphs.",description:"Refresh the page to try again.",tone:"danger",className:"v10-sgov-state"}):k.length===0&&N.entityCount===0?s.jsx(xe,{icon:"#",title:"No subgraphs in this Context Graph yet.",description:s.jsxs(s.Fragment,{children:["A subgraph is a named topical slice of this Context Graph (e.g. ",s.jsx("code",{children:"recipes"}),", ",s.jsx("code",{children:"decisions"}),"). Agents create one when they scope an assertion to a subgraph. All current entities live in the Context Graph root."]}),actions:[{label:"View root",onClick:()=>r(Ve),variant:"primary"}],className:"v10-sgov-state"}):s.jsxs("div",{className:"v10-sgov",children:[s.jsxs("div",{className:"v10-sgov-header",children:[s.jsx("div",{className:"v10-sgov-title",children:"Subgraphs"}),s.jsxs("div",{className:"v10-sgov-sub",children:[k.length," named subgraphs · ",t.counts.total," entities · ",h," triples"]})]}),s.jsxs("div",{className:"v10-sgov-grid",children:[k.map(j=>s.jsx(or,{card:j,isHydrating:p,isFailedOrPartial:v,onNodeClick:n,onOpen:()=>r(j.slug)},j.slug)),s.jsx(or,{card:N,isHydrating:p,isFailedOrPartial:v,onNodeClick:n,onOpen:()=>r(Ve),variant:"root"},Ve)]})]})}function or({card:e,isHydrating:t=!1,isFailedOrPartial:n=!1,onNodeClick:r,onOpen:i,variant:a}){const o=f.useMemo(()=>{const d={};for(const[g,h]of e.entityTrustByUri)d[g]=nt[h];return d},[e.entityTrustByUri]),l=f.useMemo(()=>({labelMode:"humanized",renderer:"2d",labels:Sr({minZoomForLabels:.8}),style:{classColors:la,predicateColors:oa,namespaceColors:Nr(e.color),...Object.keys(o).length>0?{nodeColors:o}:{},defaultNodeColor:e.color,defaultEdgeColor:"#475569",edgeWidth:1,fontSize:12,gradient:!0,gradientIntensity:.35},hexagon:{baseSize:6,minSize:3,maxSize:16,scaleWithDegree:!0},focus:{maxNodes:5e3,hops:999}}),[e.color,o]),c=a==="root";return s.jsxs("div",{className:`v10-sgov-card${c?" root":""}`,style:c?void 0:{"--sg-color":e.color,borderColor:e.color+"55"},children:[s.jsxs("div",{className:"v10-sgov-card-head",children:[s.jsx("span",{className:"v10-sgov-card-icon",style:c?void 0:{color:e.color},children:e.icon}),s.jsxs("div",{className:"v10-sgov-card-title-wrap",children:[s.jsx("div",{className:"v10-sgov-card-title",children:e.displayName}),e.description&&s.jsx("div",{className:"v10-sgov-card-desc",title:e.description,children:e.description})]}),s.jsx("button",{type:"button",className:"v10-sgov-card-open",onClick:i,title:`Focus on ${e.displayName}`,children:"↗"})]}),s.jsxs("div",{className:"v10-sgov-card-stats",children:[s.jsxs("span",{className:"v10-sgov-card-stat",children:[s.jsx("b",{children:e.entityCount})," entities"]}),s.jsxs("span",{className:"v10-sgov-card-stat",title:t&&e.tripleCount===0?"Loading triples for this subgraph…":n?e.tripleCount===0?"Some layers unavailable; count may be incomplete.":`${e.tripleCount} triples (some layers unavailable; count may be incomplete).`:t?`${e.tripleCount} triples (still loading; count may grow).`:e.tripleCount!==e.triples.length?`${e.tripleCount} triples in this subgraph's scope; ${e.triples.length} rendered (some in-scope edges aren't drawn — either endpoints outside this subgraph, or cap-trimmed in dense buckets).`:void 0,children:[s.jsx("b",{children:t&&e.tripleCount===0?"…":e.tripleCount})," triples"]})]}),s.jsx("div",{className:"v10-sgov-card-pyramid",children:s.jsx(ji,{counts:e.layerCounts,compact:!0})}),s.jsx("div",{className:"v10-sgov-card-graph",children:e.triples.length===0?s.jsx("div",{className:"v10-sgov-card-empty",children:e.entityCount>0?"Promoted — open to view":"No data yet"}):s.jsx(f.Suspense,{fallback:s.jsx("div",{className:"v10-sgov-card-empty",children:"Loading…"}),children:s.jsx(Kn,{data:e.triples,format:"triples",options:l,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:r,initialFit:!0})})})]})}function ji({counts:e,activeLayers:t,onClickLayer:n,compact:r=!1}){const i=e.wm+e.swm+e.vm;if(i===0)return r?null:s.jsx("div",{className:"v10-minibar v10-minibar-empty",children:"No data"});const a=[{key:"verified",short:"VM",count:e.vm,color:"#22c55e",label:"Verifiable"},{key:"shared",short:"SWM",count:e.swm,color:"#f59e0b",label:"Shared"},{key:"working",short:"WM",count:e.wm,color:"#64748b",label:"Working"}],o=!!n;return s.jsxs("div",{className:`v10-minibar${r?" compact":""}`,children:[!r&&s.jsx("div",{className:"v10-minibar-bar",children:a.filter(l=>l.count>0).map(l=>{const c=l.count/i*100,d=t?t.has(l.key):!0;return s.jsx("div",{className:`v10-minibar-seg${d?"":" dim"}`,style:{width:`${c}%`,background:l.color},title:`${l.label}: ${l.count}`},l.key)})}),s.jsx("div",{className:"v10-minibar-legend",children:a.map(l=>{const c=t?t.has(l.key):!0;return s.jsxs("button",{type:"button",className:`v10-minibar-chip${c?"":" dim"}${o?" interactive":""}`,onClick:o?()=>n(l.key):void 0,disabled:!o,title:`${l.label} Memory — ${l.count} entities${o?" (click to toggle)":""}`,children:[s.jsx("span",{className:"v10-minibar-dot",style:{background:l.color}}),s.jsx("span",{className:"v10-minibar-short",children:l.short}),s.jsx("span",{className:"v10-minibar-count",children:l.count})]},l.key)})})]})}function hh({items:e,color:t,onSelectEntity:n,scrollKey:r}){const i=et(),a=It(),o=f.useMemo(()=>{const l=new Map;for(const c of e){const d=`${c.date.getFullYear()}-${String(c.date.getMonth()+1).padStart(2,"0")}`,g=l.get(d)??[];g.push(c),l.set(d,g)}return[...l.entries()].sort((c,d)=>c[0].localeCompare(d[0]))},[e]);return e.length===0?s.jsx("div",{className:"v10-subgraph-timeline-empty","data-cg-scroll-key":r,children:s.jsx(xe,{compact:!0,title:"No timeline values yet.",description:"Entities in this sub-graph do not currently expose the configured timeline field."})}):s.jsx("div",{className:"v10-subgraph-timeline","data-cg-scroll-key":r,children:o.map(([l,c])=>s.jsxs("div",{className:"v10-subgraph-timeline-bucket",children:[s.jsxs("div",{className:"v10-subgraph-timeline-bucket-head",children:[s.jsx("span",{className:"v10-subgraph-timeline-bucket-dot",style:{background:t}}),s.jsx("span",{className:"v10-subgraph-timeline-bucket-label",children:aa(l)}),s.jsx("span",{className:"v10-subgraph-timeline-bucket-count",children:c.length})]}),s.jsx("div",{className:"v10-subgraph-timeline-items",children:c.map(({entity:d,date:g})=>{const{icon:h}=dn(d,i),u=Wn(d),p=u?a==null?void 0:a.get(u):null;return s.jsxs("button",{className:"v10-subgraph-timeline-item",onClick:()=>n(d.uri),title:`${d.label} · ${g.toISOString().slice(0,10)}`,children:[s.jsx("span",{className:"v10-subgraph-timeline-item-icon",children:h}),s.jsx("span",{className:"v10-subgraph-timeline-item-label",children:d.label}),(p||u)&&s.jsx(gt,{agent:p??void 0,fallbackUri:u??void 0,size:"sm"}),s.jsx("span",{className:"v10-subgraph-timeline-item-date",children:g.toISOString().slice(0,10)})]},d.uri)})})]},l))})}function mh({slug:e,rawMemory:t,contextGraphId:n,onNodeClick:r,onSelectEntity:i,activeTab:a,onTabChange:o,initialLayer:l,initialEnabledLayers:c,onEnabledLayersChange:d,onOpenQueryCatalog:g}){const h=et(),u=h==null?void 0:h.forSubGraph(e),p=(h==null?void 0:h.chipsFor(e))??[],v=(h==null?void 0:h.savedQueryCatalogsFor(e))??[],y=u==null?void 0:u.timelinePredicate,[w,m]=f.useState("items"),b=a??w,x=b==="timeline"&&!y?"items":b,k=o??m,[N,j]=f.useState(u!=null&&u.timelinePredicate?"created-desc":"triples");f.useEffect(()=>{j(u!=null&&u.timelinePredicate?"created-desc":"triples")},[e,u==null?void 0:u.timelinePredicate]);const _=f.useMemo(()=>c&&c.size>0?new Set(c):l==="wm"?new Set(["working"]):l==="swm"?new Set(["shared"]):l==="vm"?new Set(["verified"]):new Set(["working","shared","verified"]),[l,c]),[z,E]=f.useState(_);f.useEffect(()=>{d==null||d(z)},[z,d]);const[T,C]=f.useState(new Map),[O,Z]=f.useState(null),[$,R]=f.useState(null),[G,P]=f.useState(!1),[L,A]=f.useState(null),M=e===Ve,F=f.useMemo(()=>{const U=[];for(const W of t.entityList)(M?W.subGraphs.size===0:W.subGraphs.has(e))&&U.push(W);return U},[t.entityList,e,M]),B=f.useMemo(()=>new Set(F.map(U=>U.uri)),[F]),J=f.useMemo(()=>t.graphTriples.filter(U=>Rn(U,{slug:e,isRoot:M,scopedUris:B})),[t.graphTriples,B,e,M]),X=f.useMemo(()=>{let U=0,W=0,Q=0;for(const ie of F)ie.trustLevel==="verified"?Q++:ie.trustLevel==="shared"?W++:U++;return{wm:U,swm:W,vm:Q,total:F.length}},[F]),Y=f.useMemo(()=>{if(z.size!==1)return null;const U=z.values().next().value;return U==="verified"?"vm":U==="shared"?"swm":U==="working"?"wm":null},[z]),V=f.useMemo(()=>{let U=F;if(z.size<3&&(U=U.filter(W=>z.has(W.trustLevel))),T.size>0)for(const W of p){const Q=T.get(W.slug);!Q||Q.size===0||(U=U.filter(ie=>{const ae=ie.properties.get(W.predicate);return!ae||ae.length===0?!1:ae.some(ce=>Q.has(ce))}))}return $&&(U=U.filter(W=>$.has(W.uri))),U},[F,z,T,p,$]),re=f.useMemo(()=>new Set(V.map(U=>U.uri)),[V]),ye=f.useMemo(()=>V.length===F.length?J:J.filter(U=>re.has(U.subject)||re.has(U.object)),[J,F,V,re]),Re=f.useMemo(()=>{if(!Y)return null;const U=Y==="vm"?"verified":Y==="swm"?"shared":"working",W=F.filter(ce=>{if(!ce.layers.has(U))return!1;if(T.size>0)for(const Fe of p){const Ee=T.get(Fe.slug);if(!Ee||Ee.size===0)continue;const Pe=ce.properties.get(Fe.predicate);if(!Pe||Pe.length===0||!Pe.some(ot=>Ee.has(ot)))return!1}return!($&&!$.has(ce.uri))}),Q=new Set(W.map(ce=>ce.uri)),ie=new Set,ae=[];for(const ce of t.allTriples){if(ce.layer!==U||!Rn(ce,{slug:e,isRoot:M,scopedUris:B,requireResourceObject:!0})||!(Q.has(ce.subject)||Q.has(ce.object)))continue;const Fe=`${ce.subject}|${ce.predicate}|${ce.object}`;ie.has(Fe)||(ie.add(Fe),ae.push({subject:ce.subject,predicate:ce.predicate,object:ce.object,subGraph:ce.subGraph}))}return ae},[Y,t.allTriples,B,e,M,F,p,T,$])??ye,q=f.useMemo(()=>{if(Y){const U=Y==="vm"?"verified":Y==="swm"?"shared":"working";return F.filter(W=>{if(!W.layers.has(U))return!1;if(T.size>0)for(const Q of p){const ie=T.get(Q.slug);if(!ie||ie.size===0)continue;const ae=W.properties.get(Q.predicate);if(!ae||ae.length===0||!ae.some(ce=>ie.has(ce)))return!1}return!($&&!$.has(W.uri))})}return V},[Y,F,V,p,T,$]),ne=f.useMemo(()=>q.map(U=>({uri:U.uri,label:U.label})),[q]),se=f.useMemo(()=>{if(Y)return;const U={};for(const W of q){U[W.uri]=nt[W.trustLevel];const Q=De(W.uri);Q!==W.uri&&(U[Q]=nt[W.trustLevel])}return U},[Y,q]),$e=z.size===3?"All layers":Y?Oe[Y].title:Array.from(z).map(U=>Oe[U==="verified"?"vm":U==="shared"?"swm":"wm"].trustLabel).join(" + "),fe=f.useMemo(()=>{if(!y)return[];const U=[];for(const W of V){const Q=Vt(W,y);Q!=null&&U.push({entity:W,date:new Date(Q)})}return U.sort((W,Q)=>W.date.getTime()-Q.date.getTime()),U},[V,y]),ge=f.useMemo(()=>{const U=[...V];if((N==="created-desc"||N==="created-asc")&&y){const W=N==="created-desc"?-1:1;return U.sort((Q,ie)=>{const ae=Vt(Q,y),ce=Vt(ie,y);return ae==null&&ce==null?0:ae==null?1:ce==null?-1:(ae-ce)*W}),U}return N==="label"?(U.sort((W,Q)=>(W.label??"").localeCompare(Q.label??"")),U):(U.sort((W,Q)=>{const ie=W.tripleCount??0;return(Q.tripleCount??0)-ie}),U)},[V,N,y]),Se=N==="created-desc"?"newest first · click to open":N==="created-asc"?"oldest first · click to open":N==="label"?"A → Z · click to open":"sorted by triples · click to open",be=f.useCallback(U=>{E(W=>{const Q=new Set(W);return Q.has(U)?Q.size>1&&Q.delete(U):Q.add(U),Q})},[]),Ze=f.useCallback((U,W)=>{C(Q=>{const ie=new Map(Q),ae=new Set(ie.get(U)??[]);return ae.has(W)?ae.delete(W):ae.add(W),ae.size===0?ie.delete(U):ie.set(U,ae),ie})},[]),ue=f.useCallback(()=>{Z(null),R(null),A(null)},[]),Me=f.useCallback(async U=>{var W;if((((W=U.parameters)==null?void 0:W.length)??0)>0){g==null||g();return}P(!0),A(null),Z(U.slug);try{const Q=Nt(U),ae=(await kr(Q.sparql,{contextGraphId:n,view:Q.view,subGraphName:Q.subGraphName})).result,ce=ae.type;if(ce!=="bindings")throw new Error(`${U.name} returns ${ce==="boolean"?"an ASK result":"graph quads"} and cannot be used as an entity filter. Open it in Query Catalogue instead.`);const Fe=ae.bindings,Ee=U.resultColumn||"uri",Pe=new Set;for(const ot of Fe){const lt=ot[Ee];if(!lt)continue;const ct=typeof lt=="string"?lt:String(lt),qe=ct.startsWith("<")&&ct.endsWith(">")?ct.slice(1,-1):ct;Pe.add(qe)}R(Pe)}catch(Q){A((Q==null?void 0:Q.message)??String(Q)),R(null),Z(null)}finally{P(!1)}},[n,g]),de=(u==null?void 0:u.color)??(M?"var(--text-tertiary)":"#64748b"),bt=(u==null?void 0:u.icon)??"•",yt=(u==null?void 0:u.displayName)??e,Lt=u==null?void 0:u.description;f.useEffect(()=>{E(_),C(new Map),ue()},[e,ue,_]),f.useEffect(()=>{a||m("items")},[e,a]),f.useEffect(()=>{b!==x&&k(x)},[b,x,k]);const at=!(z.size===_.size&&[...z].every(U=>_.has(U)))||T.size>0||!!$,vn=()=>{E(new Set(_)),C(new Map),ue()};return s.jsxs("div",{className:"v10-layer-detail v10-subgraph-detail",style:{"--sg-color":de},children:[s.jsxs("div",{className:"v10-subgraph-detail-header",children:[s.jsx("span",{className:"v10-subgraph-detail-icon",style:{color:de},children:bt}),s.jsxs("div",{className:"v10-subgraph-detail-title-wrap",children:[s.jsx("div",{className:"v10-subgraph-detail-title",children:yt}),Lt&&s.jsx("div",{className:"v10-subgraph-detail-desc",children:Lt})]}),s.jsx(ji,{counts:{wm:X.wm,swm:X.swm,vm:X.vm},activeLayers:z,onClickLayer:be,compact:!0})]}),s.jsxs("div",{className:"v10-subgraph-cross-layer",children:[s.jsx("div",{className:"v10-subgraph-cross-layer-lede",children:M?"Root entities, across the three memory layers:":"This subgraph, across the three memory layers:"}),s.jsxs("div",{className:"v10-subgraph-cross-layer-strip","data-testid":"cross-layer-strip",children:[s.jsxs("button",{type:"button",className:"v10-subgraph-cross-layer-cell","data-layer":"wm","aria-pressed":z.has("working"),onClick:()=>be("working"),children:[s.jsx("span",{className:"v10-subgraph-cross-layer-cell-icon",style:{color:nt.working},children:"◇"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-label",children:"Working"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-count",children:X.wm})]}),s.jsx("span",{className:"v10-subgraph-cross-layer-arrow","aria-hidden":"true",children:"→"}),s.jsxs("button",{type:"button",className:"v10-subgraph-cross-layer-cell","data-layer":"swm","aria-pressed":z.has("shared"),onClick:()=>be("shared"),title:Y==="swm"?"Showing Shared Working Memory only — graph is colored by contributing agent (see legend).":void 0,children:[s.jsx("span",{className:"v10-subgraph-cross-layer-cell-icon",style:{color:nt.shared},children:"◈"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-label",children:"Shared"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-count",children:X.swm})]}),s.jsx("span",{className:"v10-subgraph-cross-layer-arrow","aria-hidden":"true",children:"→"}),s.jsxs("button",{type:"button",className:"v10-subgraph-cross-layer-cell","data-layer":"vm","aria-pressed":z.has("verified"),onClick:()=>be("verified"),children:[s.jsx("span",{className:"v10-subgraph-cross-layer-cell-icon",style:{color:nt.verified},children:"◉"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-label",children:"Verifiable"}),s.jsx("span",{className:"v10-subgraph-cross-layer-cell-count",children:X.vm})]})]}),s.jsxs("span",{className:`v10-subgraph-active-layer-pill${z.size===3?" all-layers":""}`,"data-testid":"active-layer-pill",children:[s.jsx("span",{className:"v10-subgraph-active-layer-pill-label",children:"Active layer:"}),s.jsx("span",{className:"v10-subgraph-active-layer-pill-value",children:$e})]})]}),v.length>0&&s.jsxs("div",{className:"v10-subgraph-savedqueries",children:[s.jsx("span",{className:"v10-subgraph-savedqueries-label",children:"Query catalog"}),v.map(U=>s.jsxs(Ce.Fragment,{children:[s.jsx("span",{className:"v10-subgraph-savedqueries-label",title:U.description||U.name,style:{marginLeft:8,opacity:.8},children:U.name}),U.queries.map(W=>{var ae;const Q=O===W.slug,ie=(((ae=W.parameters)==null?void 0:ae.length)??0)>0;return s.jsxs("button",{type:"button",className:`v10-subgraph-savedquery${Q?" active":""}`,onClick:()=>Q?ue():Me(W),title:ie?`${W.description||W.name} Open Query Catalogue to enter parameters.`:W.description||W.name,disabled:G&&!Q,children:[s.jsx("span",{className:"v10-subgraph-savedquery-glyph",children:ie?"↗":G&&Q?"…":Q?"✓":"◎"}),W.name]},W.slug)})]},U.slug)),L&&s.jsx("span",{className:"v10-subgraph-savedquery-error",title:L,children:"✕ query failed"}),$&&O&&s.jsxs("span",{className:"v10-subgraph-savedquery-count",children:[$.size," match",$.size===1?"":"es"]})]}),p.length>0&&s.jsxs("div",{className:"v10-subgraph-filters",children:[p.map(U=>{const W=T.get(U.slug)??new Set;return s.jsxs("div",{className:"v10-subgraph-filter-row",children:[s.jsx("span",{className:"v10-subgraph-filter-label",children:U.label}),s.jsx("div",{className:"v10-subgraph-filter-chips",children:U.values.map(Q=>{const ie=W.has(Q);return s.jsx("button",{type:"button",className:`v10-subgraph-filter-chip${ie?" active":""}`,onClick:()=>Ze(U.slug,Q),children:Q},Q)})})]},U.slug)}),at&&s.jsx("button",{type:"button",className:"v10-subgraph-filter-reset",onClick:vn,children:"Reset filters"})]}),s.jsxs("div",{className:"v10-layer-detail-body",children:[s.jsxs("div",{className:"v10-layer-expand-tabs",children:[s.jsxs("button",{className:`v10-layer-expand-tab ${x==="items"?"active":""}`,onClick:()=>k("items"),children:["Entities (",V.length,V.length!==F.length?` / ${F.length}`:"",")"]}),s.jsx("button",{className:`v10-layer-expand-tab ${x==="graph"?"active":""}`,onClick:()=>k("graph"),children:"Graph"}),y&&s.jsx("button",{className:`v10-layer-expand-tab ${x==="timeline"?"active":""}`,onClick:()=>k("timeline"),children:"Timeline"}),s.jsx("button",{className:`v10-layer-expand-tab ${x==="docs"?"active":""}`,onClick:()=>k("docs"),children:"Documents"})]}),x==="items"&&s.jsx("div",{className:"v10-layer-expand-body entities-tab","data-cg-scroll-key":`subgraph:${e}:items`,children:s.jsx(Ar,{entities:ge,layerKey:"wm",layerIcon:bt,onSelectEntity:i,externallySorted:!0,sortLabel:Se,timestampPredicate:y,perEntityTrustBadge:!0,headerExtra:s.jsxs("label",{className:"v10-entity-list-sort",children:[s.jsx("span",{className:"v10-entity-list-sort-label",children:"Sort"}),s.jsxs("select",{className:"v10-entity-list-sort-select",value:N,onChange:U=>j(U.target.value),"aria-label":"Sort entities",children:[y&&s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"created-desc",children:"Newest first"}),s.jsx("option",{value:"created-asc",children:"Oldest first"})]}),s.jsx("option",{value:"triples",children:"Most triples"}),s.jsx("option",{value:"label",children:"Label (A→Z)"})]})]})})}),x==="graph"&&s.jsx("div",{className:"v10-layer-expand-body full-width","data-cg-scroll-key":`subgraph:${e}:graph`,children:s.jsx($r,{layer:Y??"wm",triples:Re,onNodeClick:r,contextGraphId:n,title:yt,scopeLabel:`Subgraph graph: ${yt} entities and entity-to-entity triples from loaded subgraph data.`,trustLegendActiveLayer:Y,scopeEntities:ne,layerEntities:q,nodeColorsOverride:se})}),x==="timeline"&&y&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(hh,{items:fe,color:de,onSelectEntity:i,scrollKey:`subgraph:${e}:timeline`})}),x==="docs"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(Tr,{entities:V,contextGraphId:n,scrollKey:`subgraph:${e}:docs`})})]})]})}const fh={wm:"items",swm:"items",vm:"items"},lr={wm:"working",swm:"shared",vm:"verified"};function Tn(e){return e==="wm"||e==="swm"||e==="vm"}function gh(e){const t=new Set;return e.filter(n=>{const r=`${De(n.subject)}|${n.predicate}|${De(n.object)}`;return t.has(r)?!1:(t.add(r),!0)})}function cr(e,t){if(typeof document>"u")return t;const n=document.querySelectorAll("[data-cg-scroll-key]");for(const r of n)if(r.dataset.cgScrollKey===e)return r;return t}function Sh({contextGraphId:e}){const{data:t,error:n,loading:r,refresh:i}=ft($t.fetchContextGraphs,[],3e4),[a,o]=f.useState(!1),[l,c]=f.useState(!1),[d,g]=f.useState("overview"),[h,u]=f.useState(!1),[p,v]=f.useState(null);f.useEffect(()=>{u(!1)},[e]);const[y,w]=f.useState({contextGraphId:null,list:[],status:"loading"}),[m,b]=f.useState(null),[x,k]=f.useState(!1),N=f.useRef(0),[j,_]=f.useState(null),[z,E]=f.useState(null),T=f.useRef(null),[C,O]=f.useState(null),Z=f.useCallback(D=>{T.current=D,O(D)},[]),$=f.useRef(null),R=f.useCallback(D=>{$.current=D,D===null&&(T.current=null,O(null)),_(D)},[]),[G,P]=f.useState(null),L=f.useRef(null);f.useEffect(()=>{L.current=p},[p]);const[A,M]=f.useState(fh),[F,B]=f.useState({}),J=f.useRef(null),X=f.useRef(null),Y=f.useRef(null),V=f.useRef(0),re=va(e),ye=ba(e),Ne=Vn(D=>D.openTab),{data:Re,loading:q,error:ne}=ca(),se=f.useCallback(()=>j?`subgraph:${j}:${F[j]??"items"}`:Tn(d)?`layer:${d}:${A[d]}`:"page",[d,j,A,F]),$e=f.useCallback(D=>{const te=D??se(),le=cr(te,J.current);return{activeLayer:d,activeSubGraph:j,layerTabs:{...A},subGraphTabs:{...F},scroll:{key:te,top:(le==null?void 0:le.scrollTop)??0},subGraphEnabledLayers:j!==null&&T.current?new Set(T.current):null}},[d,j,se,A,F]),fe=f.useCallback(D=>{const te=()=>{const le=cr(D.key,J.current);le&&(le.scrollTop=D.top)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(te):setTimeout(te,0)},[]),ge=f.useCallback((D,te)=>{(!L.current||!X.current)&&(X.current=$e(te)),v(D)},[$e]),Se=f.useCallback(()=>{X.current=null},[]);f.useEffect(()=>{if(p)return;const D=Y.current;D&&(Y.current=null,fe(D))},[p,d,j,A,F,fe]),f.useEffect(()=>{const D=te=>{const le=te.detail;le&&le.contextGraphId===e&&typeof le.entityUri=="string"&&(P(null),ge(le.entityUri))};return window.addEventListener("v10:open-entity",D),()=>window.removeEventListener("v10:open-entity",D)},[e,ge]);const be=f.useCallback(D=>{var ze;const te=D.startsWith("urn:dkg:agent:")?D.slice(14):D,le=((ze=ye.get(D))==null?void 0:ze.name)??te;Ne({id:`agent:${e}|${te}`,label:`@ ${le}`,closable:!0})},[ye,e,Ne]),Ze=f.useMemo(()=>({...ye,openAgent:be}),[ye,be]),ue=f.useMemo(()=>{var D;return(D=t==null?void 0:t.contextGraphs)==null?void 0:D.find(te=>te.id===e)},[t,e]),de=ua(e,{signalErrors:!0,includeQueryCatalog:h&&(d==="wm"||d==="swm")}),bt=Bn(de).total,yt=ha({activeLayer:d,activeSubGraph:j}),Lt=Cr(yt?e:void 0),Mt=!j&&d==="overview",at=Za(Mt?e:void 0),vn=Mt?at.resultContextGraphId===e?at.events:[]:void 0,U=Mt&&at.resultContextGraphId===e?at.error:null,W=f.useCallback(()=>{const D=ue==null?void 0:ue.id;if(!D)return;const te=V.current+1;V.current=te,w({contextGraphId:D,list:[],status:"loading"}),$t.listParticipants(D).then(le=>{V.current===te&&w({contextGraphId:D,list:le.allowedAgents,status:"ok"})}).catch(()=>{V.current===te&&w({contextGraphId:D,list:[],status:"error"})})},[ue==null?void 0:ue.id]);f.useEffect(()=>{W()},[W]);const Q=f.useCallback(()=>{const D=++N.current;$t.fetchSubGraphs(e).then(te=>{if(N.current!==D)return;const le=(te.subGraphs??[]).filter(Qn).length;b(le),k(!1)}).catch(()=>{N.current===D&&(b(null),k(!0))})},[e]);f.useEffect(()=>{b(null),k(!1),Q()},[Q]),mr(e,Q);const ie=G?lr[G]:null,ae=f.useMemo(()=>ie?de.allTriples.filter(D=>D.layer===ie):de.graphTriples,[de.allTriples,de.graphTriples,ie]),ce=f.useMemo(()=>ie?gh(ae):ae,[ae,ie]),Fe=f.useMemo(()=>ie?da(ae):de.entities,[ae,de.entities,ie]),Ee=f.useMemo(()=>p?Fe.get(p)??null:null,[p,Fe]);f.useEffect(()=>{!p||Ee||de.loading||(v(null),P(null),Se())},[p,Ee,de.loading,Se]);const Pe=f.useCallback((D,te)=>{const le=$.current;if(Se(),R(D),D===null)E(null);else if(te!==void 0){const ze=new Set([lr[te]]);E(ze),T.current=ze,O(ze)}else{if(le!==null&&D===le)return;if(le!==null&&T.current){const ze=new Set(T.current);E(ze),T.current=ze,O(ze)}else E(null),T.current=null,O(null)}v(null),P(null)},[Se,R]),ot=f.useCallback(D=>{Se(),g(D),v(null),P(null),R(null),E(null)},[Se,R]),lt=f.useCallback((D,te)=>{M(le=>le[D]===te?le:{...le,[D]:te})},[]),ct=f.useCallback((D,te)=>{B(le=>le[D]===te?le:{...le,[D]:te})},[]),qe=f.useCallback((D,te,le)=>{const ze=L.current!=null;ge(D,te),P(_i=>le??(ze?_i:null))},[ge]),wi=f.useCallback(()=>{const D=X.current;if(X.current=null,v(null),P(null),!!D){if(g(D.activeLayer),R(D.activeSubGraph),D.activeSubGraph!==null&&D.subGraphEnabledLayers){const te=new Set(D.subGraphEnabledLayers);E(te),T.current=te,O(te)}M(D.layerTabs),B(D.subGraphTabs),Y.current=D.scroll}},[R]),bn=f.useCallback(D=>{if(!(D!=null&&D.id))return;const te=Tn(D.trustLayer)?D.trustLayer:void 0;qe(D.id,void 0,te)},[qe]),ki=f.useCallback(D=>{const te=Tn(d)?d:void 0;qe(D,void 0,te)},[d,qe]),Ni=f.useCallback(D=>{qe(D,"page")},[qe]),ls=f.useCallback(()=>{Ne(pa)},[Ne]),yn=!!n&&/authentication|unauthor|expired|sign in|log in/i.test(n);if(!ue)return n||t&&!r?s.jsxs("div",{className:"v10-view-placeholder",children:[s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:12,marginBottom:10},children:n?yn?n:"Failed to load context graph.":"Context graph not found."}),yn?s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:()=>window.location.reload(),children:"Refresh page"}):s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:i,children:"Retry"})]}):s.jsx("div",{className:"v10-view-placeholder",children:s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:12},children:"Loading context graph..."})});const Si=j?re.forSubGraph(j):null,xn=!de.loading&&!de.error&&!de.partial?de.entityList:void 0,Ci=Ee?"entity":j?"subgraph":d,$i=y.contextGraphId===ue.id?y.list:[],Ei=y.contextGraphId===ue.id?y.status:"loading";return s.jsx(ya.Provider,{value:re,children:s.jsx(xa.Provider,{value:Ze,children:s.jsxs("div",{className:"v10-memory-explorer",children:[n&&s.jsx("div",{className:"v10-stale-banner",role:"status",children:yn?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:n}),s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:()=>window.location.reload(),children:"Refresh page"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Couldn’t refresh context-graph data — showing last known values."}),s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:i,children:"Retry"})]})}),s.jsx(eo,{cg:ue,profile:re,activeSubGraph:Si,onClearSubGraph:()=>Pe(null)}),s.jsx(Xa,{active:d,counts:de.counts,onSwitch:ot,onShare:()=>c(!0),onImport:()=>o(!0),onRefresh:de.refresh}),s.jsxs("main",{className:"v10-memory-explorer-page","data-view":Ci,"data-cg-scroll-key":"page",ref:J,children:[Ee&&s.jsx(uh,{entity:Ee,allEntities:Fe,allTriples:ce,onNavigate:qe,onClose:wi,contextGraphId:e,onRefresh:de.refresh}),j&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(ar,{}),s.jsx(wn,{contextGraphId:e,profile:re,selected:j,entities:xn,onSelect:Pe,enabledScope:C??void 0,allTriplesTotal:bt}),s.jsx(mh,{slug:j,rawMemory:de,contextGraphId:e,onNodeClick:bn,onSelectEntity:qe,activeTab:F[j]??"items",onTabChange:D=>ct(j,D),initialEnabledLayers:z??void 0,onEnabledLayersChange:Z,onOpenQueryCatalog:()=>{R(null),g("query")}})]}),!j&&d==="overview"&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(ao,{cg:ue,memory:de,subGraphCount:m,subGraphFetchFailed:x,participants:$i,participantsStatus:Ei,currentAgent:Re??null,currentAgentStatus:q?"loading":ne?"error":"ok",onSwitchLayer:ot,onOpenPrimer:ls}),s.jsx(oo,{contextGraphId:e,curatorStatus:ro({cg:ue,currentAgent:Re??null,currentAgentStatus:q?"loading":ne?"error":"ok"}),onParticipantsChanged:W}),de.loading&&s.jsx("div",{className:"v10-me-loading",children:s.jsx("div",{className:"v10-me-loading-text",children:"Loading memory..."})}),de.error&&s.jsxs("div",{className:"v10-me-error",children:["Error: ",de.error]}),s.jsx("div",{"data-section":"activity",children:s.jsx(ja,{entities:de.entityList,lifecycleEvents:vn,lifecycleError:U,onSelectEntity:Ni,title:"Recent activity",limit:40,includeUndated:!1,emptyHint:"Once knowledge starts being added and managed in this context graph, activities will show up here as a live feed.",className:"v10-overview-activity"})}),s.jsx(lo,{onOpenPrimer:ls})]}),!j&&d==="graph-overview"&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(ar,{}),s.jsx(wn,{contextGraphId:e,profile:re,selected:null,entities:xn,onSelect:Pe,allTriplesTotal:bt}),s.jsx(ph,{contextGraphId:e,memory:de,onNodeClick:bn,onSelectSubGraph:Pe})]}),!j&&d==="query"&&!Ee&&s.jsx(Lo,{contextGraphId:e}),!j&&(d==="wm"||d==="swm"||d==="vm")&&!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(wn,{contextGraphId:e,profile:re,selected:j,entities:xn,onSelect:Pe,layer:d}),s.jsx(Co,{layer:d,memory:de,onNodeClick:bn,onSelectEntity:ki,contextGraphId:e,activeTab:A[d],onTabChange:D=>lt(d,D),swmAttribution:Lt,showQueryCatalog:h,onShowQueryCatalogChange:u})]})]}),s.jsx(Aa,{open:a,onClose:()=>o(!1),contextGraphId:ue.id,contextGraphName:ue.name}),s.jsx(Ra,{open:l,onClose:()=>c(!1),contextGraphId:ue.id,contextGraphName:ue.name})]})})})}export{Sh as ProjectView};