@origintrail-official/dkg-node-ui 10.0.24 → 10.0.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-ui/assets/ActivityFeed-vyl2XdLo.js +99 -0
- package/dist-ui/assets/{AgentHub-BO9jGbJl.js → AgentHub-CYfAoOWF.js} +1 -1
- package/dist-ui/assets/AgentProfilePage-BjQm0je4.js +1 -0
- package/dist-ui/assets/{ApproveWalletsModal-C2Tu29tB.js → ApproveWalletsModal-CzWJ4KyU.js} +3 -3
- package/dist-ui/assets/{ContextGraphPrimitives-BqlTIZHy.js → ContextGraphPrimitives-ecppTns4.js} +1 -1
- package/dist-ui/assets/{ConvictionDetailView-J-DAKHtP.js → ConvictionDetailView-CuLUhbzR.js} +2 -2
- package/dist-ui/assets/MemoryLayerView-Dymg_Zf_.js +2 -0
- package/dist-ui/assets/MemoryReadStatus-D4HXCImC.js +1 -0
- package/dist-ui/assets/MemoryStackView-Bq8Fbh5W.js +1 -0
- package/dist-ui/assets/{Network-DV9K48MH.js → Network-F76S9_1V.js} +1 -1
- package/dist-ui/assets/{OnChainProvenanceCard-jxk66g53.js → OnChainProvenanceCard-CCwK3sRG.js} +1 -1
- package/dist-ui/assets/{Operations-CNB1BMYg.js → Operations-aVCBUh8u.js} +1 -1
- package/dist-ui/assets/ProjectView-Cb1PQ-jm.js +290 -0
- package/dist-ui/assets/{PublishingConviction-DbP1i3v0.js → PublishingConviction-BnAJjHL8.js} +2 -2
- package/dist-ui/assets/{Settings-I6g3MQCV.js → Settings-rEyPw1oS.js} +1 -1
- package/dist-ui/assets/{browserWalletTransaction-CXv612Pn.js → browserWalletTransaction-BJBFRjXx.js} +3 -3
- package/dist-ui/assets/{ccip-DY93ay8e.js → ccip-DYOqJfs7.js} +1 -1
- package/dist-ui/assets/{index-CIt7zWgM.css → index-CAdbSAQK.css} +1 -1
- package/dist-ui/assets/index-HEpqHVfE.js +1143 -0
- package/dist-ui/assets/index-_vQ99L0s.js +192 -0
- package/dist-ui/assets/{jsonld-32FQRO67-DKLfQ_nD.js → jsonld-32FQRO67-DVqZhSL_.js} +2 -2
- package/dist-ui/assets/{jsonld-BgpgXlDQ.js → jsonld-Dpm03cay.js} +1 -1
- package/dist-ui/assets/renderer-3d-IRPVRQWX-DjW_h88e.js +5126 -0
- package/dist-ui/assets/{shikiHighlighter-BXl6qMQO.js → shikiHighlighter-DL7LOds2.js} +4 -4
- package/dist-ui/assets/truncate-BWdqLeqV.js +22 -0
- package/dist-ui/assets/{useEntityOnChainReceipt-CUGQNIsP.js → useEntityOnChainReceipt-B_uLyqZc.js} +5 -5
- package/dist-ui/index.html +2 -2
- package/package.json +4 -4
- package/dist-ui/assets/3d-force-graph-DvzZZzFn.js +0 -1015
- package/dist-ui/assets/ActivityFeed-B5QxV1dk.js +0 -99
- package/dist-ui/assets/AgentProfilePage-DJJTn1WD.js +0 -1
- package/dist-ui/assets/MemoryLayerView-BOxI-_TF.js +0 -2
- package/dist-ui/assets/MemoryStackView-BTyZZKNm.js +0 -1
- package/dist-ui/assets/ProjectView-BP4vNSXI.js +0 -290
- package/dist-ui/assets/index-CumB6j2m.js +0 -192
- package/dist-ui/assets/index-DW3dBcQk.js +0 -1175
- package/dist-ui/assets/renderer-3d-2EVDZII7-BCmzI8Ii.js +0 -2
- package/dist-ui/assets/three.module-BXIk8GZS.js +0 -4112
- package/dist-ui/assets/truncate-BaiMkAOo.js +0 -1
- package/dist-ui/assets/useProjectActivity-BOgGdtS7.js +0 -1
|
@@ -1,290 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CumB6j2m.js","assets/index-DW3dBcQk.js","assets/index-CIt7zWgM.css","assets/string-DtUow4KV.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Ri=Object.defineProperty;var Ti=(e,t,n)=>t in e?Ri(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{aP as s,be as f,bH as ur,aG as Oi,q as un,aV as Ii,Q as Pi,aU as dr,bh as zi,p as pr,bg as hr,R as Ce,n as $t,bG as mr,_ as Li,L as Oe,bD as fr,bO as Mi,u as De,al as Jt,r as Fi,aF as gr,A as vr,i as Ui,t as Ie,b1 as Gn,by as Bn,aR as We,bI as Di,bL as br,bA as ft,aj as Zi,Y as qi,Z as Gi,a8 as cs,w as us,b6 as Bi,V as yr,J as dn,aS as Yt,bc as Xt,E as en,bd as xr,b3 as jr,b4 as tn,f as Wi,bC as Vi,I as Wn,K as Vt,at as Qi,bN as Vn,S as jn,M as ds,l as ps,D as hs,bi as Ki,G as Hi,U as Ji,F as wr,aQ as kr,O as Nr,bR as Yi,ag as Xi,aB as ea,bk as ut,a$ as ta,aH as na,T as nt,b0 as Sr,aZ as Cr,P as sa,bs as ra,bt as ia,aw as aa,m as Tn,o as ms,av as oa,a as la,C as ca,bz as ua,bF as da,s as pa,b as ha,bl as ma}from"./index-DW3dBcQk.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 fa,c as nn,q as ga,d as va,U as sn,g as ba,u as ya,P as xa,b as ja,A as wa}from"./ActivityFeed-B5QxV1dk.js";import{E as xe,t as At,S as pn}from"./ContextGraphPrimitives-BqlTIZHy.js";import{t as ka}from"./truncate-BaiMkAOo.js";import{b as Na,u as Sa,a as fs,t as dt}from"./useEntityOnChainReceipt-CUGQNIsP.js";import"./useProjectActivity-BOgGdtS7.js";function Ca(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 $a={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=$a[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=Ca(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 Aa(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 Ra({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}`)),H=M.filter(X=>!B.has(`${X.name}:${X.size}`));return[...F,...H.map(X=>({file:X,id:`${X.name}-${X.size}-${Date.now()}`}))]})},[]),j=A=>{a(M=>M.filter(F=>F.id!==A))},E=A=>{A.preventDefault(),A.stopPropagation(),x(!0)},z=A=>{A.preventDefault(),A.stopPropagation(),x(!1)},_=A=>{A.preventDefault(),A.stopPropagation(),x(!1),A.dataTransfer.files.length>0&&N(A.dataTransfer.files)},R=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],H=B.name.replace(/[^a-zA-Z0-9._-]/g,"_"),X=`${Date.now().toString(36)}-${F}-${H}`;try{const Y=await Oi(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),T=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:E,onDragLeave:z,onDrop:_,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:Aa(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:[T>0&&s.jsxs(s.Fragment,{children:["Successfully imported ",T," file",T!==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:[T>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:[T," file",T!==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:R,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 Oa({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(()=>{}),Ii(n).then(C=>d(C.allowedAgents)).catch(()=>d([])),Pi().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,E=(C,O)=>{navigator.clipboard.writeText(C).then(()=>{a(O),setTimeout(()=>a(null),2e3)}).catch(()=>{})},z=async C=>{try{await zi(n,C),d(O=>O.filter(Z=>Z!==C))}catch{}},_=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)}},R=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:()=>E(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:()=>_(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:()=>R(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 Ia(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 Pa(e){return e.startsWith("did:")||e.startsWith("12D3")?e:/^0x[0-9a-fA-F]{40}$/.test(e)?`did:dkg:agent:${e}`:e}function za(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 La(e){return`PREFIX dkg: <http://dkg.io/ontology/>
|
|
4
|
-
PREFIX prov: <http://www.w3.org/ns/prov#>
|
|
5
|
-
SELECT ?op ?root ?agent ?publishedAt ?g WHERE {
|
|
6
|
-
GRAPH ?g {
|
|
7
|
-
?op a dkg:WorkspaceOperation ;
|
|
8
|
-
dkg:rootEntity ?root ;
|
|
9
|
-
dkg:publishedAt ?publishedAt ;
|
|
10
|
-
prov:wasAttributedTo ?agent .
|
|
11
|
-
}
|
|
12
|
-
FILTER(
|
|
13
|
-
STRSTARTS(STR(?g), "${`did:dkg:context-graph:${e}/`}") &&
|
|
14
|
-
CONTAINS(STR(?g), "_shared_memory_meta")
|
|
15
|
-
)
|
|
16
|
-
} ORDER BY DESC(?publishedAt) LIMIT 5000`}function Ma(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 Fa(e){const t=[...new Set(e)].sort(),n=new Set,r=new Map;for(const i of t){const a=Ma(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 $r(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 E=()=>!N&&x===y.current;return u(!0),g(null),(async()=>{var z;try{const _=new Promise((A,M)=>{j=setTimeout(()=>{k.abort(),M(new Error(`SWM attribution query timed out after ${Math.round(vs/1e3)}s`))},vs)}),R=(async()=>{const A=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...un()},signal:k.signal,body:JSON.stringify({sparql:La(e)})});if(!A.ok)throw new Error(`SPARQL query failed: ${A.status}`);return A.json()})(),C=await Promise.race([R,_]),Z=(((z=C==null?void 0:C.result)==null?void 0:z.bindings)??[]).slice().reverse(),$=new Map,T=new Map,G=[];for(const A of Z){const M=jt(A.op),F=jt(A.root),B=jt(A.agent),H=jt(A.publishedAt),X=jt(A.g);if(!M||!F||!B||!H)continue;const Y=Pa(B),V=X?za(X,e):void 0;G.push({opUri:M,rootUri:F,agent:Y,publishedAt:H,subGraph:V});const re={agent:Y,opUri:M,publishedAt:H,subGraph:V},ye=$.get(F);ye?ye.some(Te=>Te.agent===Y)||ye.push(re):$.set(F,[re]);let Ne=T.get(Y);Ne||(Ne=new Set,T.set(Y,Ne)),Ne.add(F)}const P=Fa(T.keys()),L=[...T.entries()].map(([A,M])=>({agent:A,color:P.get(A),label:Ia(A),entityCount:M.size})).sort((A,M)=>M.entityCount-A.entityCount);if(!E())return;n($),i(G),o(L),c(P),v(e)}catch(_){if(!E())return;g((_==null?void 0:_.message)??"Failed to load SWM attributions"),n(new Map),i([]),o([]),c(new Map),v(e)}finally{j&&clearTimeout(j),E()&&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 E=j[0].agent,z=l.get(E);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 Ua(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 Da(e){const t=`did:dkg:context-graph:${e}/_meta`;return`PREFIX dkg: <${On}>
|
|
17
|
-
PREFIX prov: <http://www.w3.org/ns/prov#>
|
|
18
|
-
SELECT ?event ?type ?assertion ?name ?agent ?ts ?subGraphName ?assertionGraph (COUNT(DISTINCT ?root) AS ?entityCount) (COUNT(DISTINCT ?subjRoot) AS ?subjectEntityCount) WHERE {
|
|
19
|
-
GRAPH <${t}> {
|
|
20
|
-
?event a ?type ;
|
|
21
|
-
prov:startedAtTime ?ts .
|
|
22
|
-
FILTER(?type IN (dkg:AssertionCreated, dkg:AssertionPromoted))
|
|
23
|
-
OPTIONAL { ?event prov:wasAssociatedWith ?agentAssoc }
|
|
24
|
-
OPTIONAL { ?event prov:generated ?gen }
|
|
25
|
-
OPTIONAL { ?event prov:used ?used }
|
|
26
|
-
BIND(COALESCE(?gen, ?used) AS ?assertion)
|
|
27
|
-
?assertion dkg:assertionName ?name .
|
|
28
|
-
OPTIONAL { ?assertion prov:wasAttributedTo ?agentAttr }
|
|
29
|
-
BIND(COALESCE(?agentAssoc, ?agentAttr) AS ?agent)
|
|
30
|
-
OPTIONAL { ?assertion dkg:subGraphName ?subGraphName }
|
|
31
|
-
OPTIONAL { ?assertion dkg:assertionGraph ?assertionGraph }
|
|
32
|
-
OPTIONAL { ?event dkg:rootEntity ?root }
|
|
33
|
-
OPTIONAL { ?assertion dkg:rootEntity ?subjRoot }
|
|
34
|
-
}
|
|
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 Za(e){return e===`${On}AssertionCreated`?"created":e===`${On}AssertionPromoted`?"promoted":null}function qa(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:Da(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),E=Ge(k.assertion),z=Ge(k.name),_=Ge(k.agent),R=Ge(k.ts);if(!N||!E||!_||!R)continue;const C=Za(j);if(!C)continue;let O;if(C==="promoted"){const T=Ge(k.entityCount),G=T!=null?Number(T):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 T=Ge(k.assertionGraph);T&&($=Ua(T,e))}x.push({eventUri:N,kind:C,assertionUri:E,assertionName:z??"",agentUri:_,publishedAt:R,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 Ga={wm:"working",swm:"shared",vm:"verified"};function Ba(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(()=>Ba(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([Ga[a]]):null,[o,a]),y=Ce.useMemo(()=>{if(!i)return null;const $=new Map;for(const T of i)if(!(v&&!v.has(T.trustLevel)))for(const G of T.subGraphs)$.set(G,($.get(G)??0)+1);return $},[v,i]),w=Ce.useMemo(()=>{if(!i)return null;let $=0;for(const T of i)v&&!v.has(T.trustLevel)||$++;return $},[v,i]),m=Ce.useMemo(()=>{if(!i)return null;let $=0;for(const T of i)v&&!v.has(T.trustLevel)||T.subGraphs.size>0||$++;return $},[v,i]),b=Ce.useCallback(()=>{const $=++p.current;h(!0),$t.fetchSubGraphs(e).then(T=>{$===p.current&&d(T.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 T=t.forSubGraph($.name),G=y!==null?y.get($.name)??0:$.entityCount;return{slug:$.name,icon:T.icon??"•",color:T.color??"#64748b",displayName:T.displayName??$.name,description:T.description??$.description,rank:T.rank??99,entityCount:G,tripleCount:$.tripleCount,layerScoped:y!==null}}).sort(($,T)=>$.rank-T.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(($,T)=>$+T.entityCount,0),E=x.reduce(($,T)=>$+T.tripleCount,0),z={working:"Working Memory",shared:"Shared Working Memory",verified:"Verifiable Memory"},_=v?[...v].map($=>z[$]).join(" + "):null,R=_?` in ${_}`:"",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${R}${_?"":` · ${l??E} 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${R}.`;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 T=u.get($.slug);return s.jsxs("button",{type:"button",className:`v10-subgraph-chip${n===$.slug?" active":""}${T?" has-badge":""}`,onClick:()=>r($.slug,a),title:`${$.displayName}${$.description?" · "+$.description:""} · ${$.entityCount} entities${R}${_?"":` · ${$.tripleCount} triples`}${T?" · "+T.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}),T&&s.jsxs("span",{className:`v10-subgraph-chip-badge tone-${T.tone}`,children:[s.jsx("span",{className:"v10-subgraph-chip-badge-dot"}),T.label]})]},$.slug)}),N&&(()=>{const $=m??0,T=n===Ve;return s.jsxs("button",{type:"button",className:`v10-subgraph-chip v10-subgraph-chip-root${T?" active":""}`,"data-active":T,"data-count":$,onClick:()=>r(Ve,a),title:`Entities not in any subgraph (Context Graph root) · ${$} entities${R}`,"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(()=>Li(()=>import("./index-CumB6j2m.js").then(e=>e.h),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.RdfGraph}))),Wa="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",Va=new Map(Ui.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 Qa(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=Va.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)===Wa||!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 Ka(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 Ha({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(Ha,{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}=Mi(e==="vm"&&r?r:void 0,v),m=$r(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 Jt(t,M)},[t,d]),k=f.useMemo(()=>{const M=new Set,F=[],B=H=>{const X=`${H.subject}|${H.predicate}|${H.object}`;M.has(X)||(M.add(X),F.push({subject:H.subject,predicate:H.predicate,object:H.object}))};for(const H of x)B(H);for(const H of w)B(H);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]),E=f.useMemo(()=>Fi(e,j),[e,j]),{canvasTriples:z,singletonItems:_}=f.useMemo(()=>Qa(N),[N]),R=f.useMemo(()=>{if(!l||l.length===0)return _;const M=new Set(_.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 H=Qe(B.uri);M.has(H)||(M.add(H),F.push({uri:H,label:B.label||gr(void 0,H)}))}return F.length===0?_:[..._,...F].sort((B,H)=>B.label.localeCompare(H.label))},[_,z,l]),C=`${r??"context"}:${e}`,O=e==="swm"&&!!r&&b.loading,Z=`${u} graph`,$=i??Ka(e),T=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(Xa,{anchors:y}),e==="swm"&&b.palette.length>0&&s.jsx(Ya,{palette:b.palette,conflicts:b.conflicts.length})]}):null,A=f.useMemo(()=>({name:`${C}:${p}`,palette:p}),[C,p]);return k.length===0&&R.length===0?s.jsx(Qt,{title:Z,scopeLabel:$,tone:e,className:"v10-graph-view-fill",showScopeLabel:T,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:T,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:T,singletonItems:R,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:E,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 Ya({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 Xa({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 eo({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 to({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 no(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 so(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 ro(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 io({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 ao(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 oo({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=no(e,o??null,l,i,a),y=ro(e==null?void 0:e.accessPolicy),w=so(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=ao(o??null),N=Object.values(t.layerStatus??{}),j=N.filter(B=>B==="error").length,E=!t.loading&&N.length===3&&j===3,z=!t.loading&&j>0,_=t.loading?"Loading memory layers...":E||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.",R=E?"Unavailable":p.toLocaleString(),{total:C}=Bn(t),O=!t.loading&&(t.partial||z),Z=E?"Unavailable":t.loading&&C===0?"...":O?`${C.toLocaleString()}+`:C.toLocaleString(),$=E?"Live triple counts are unavailable.":O?"One or more layer triple counts are currently a lower bound.":"Canonical triple total across all layers.",T=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:R,label:"Entities",tooltip:_},{id:"triples",value:Z,label:"Triples",tooltip:$},{id:"subgraphs",value:T,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 H=B.count>0?B.count/p*100:0;return s.jsx("span",{className:`v10-po-pipeline-seg ${B.key}`,style:{width:`${H}%`,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,H)=>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:H+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:",H=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:H(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:H(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),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 lo({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]),Di(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 co({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 uo=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function po(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 Zi().catch(()=>null),l=(o==null?void 0:o.wallets)??[];let c=!1;try{const{contextGraphs:g}=await qi(),h=(g??[]).find(p=>(p==null?void 0:p.id)===e),u=h==null?void 0:h.curator;if(u){const p=await Gi().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=>uo(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 E=us(j);if(E.outcome==="inconclusive"){x=!0;continue}if(E.outcome!=="unregistered"){if(E.outcome==="covers"){y={accountId:N,discountBps:j.discountBps,untracked:!1};break}E.dead&&(w=!0,b||(b=N)),E.hasBudget||(m=!0)}}if(!y&&!x&&!w&&!m){const N=await Bi(g).catch(()=>{});if(N===void 0)x=!0;else if(N.accountId!=null&&!n.includes(N.accountId)){const j=N.accountId,E=await cs(j,g,{extended:!0}).catch(()=>null);if(E===null)x=!0;else{const z=us(E);z.outcome==="covers"?y={accountId:j,discountBps:E.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 ho(e){return e.verdict==="fallthrough-no-funds"&&!(e.ownerPublish&&e.anyGasFunded)}function mo(e){const t=br(o=>o.trackedIds),n=po(e,3e4),r=ho(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 fo({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 Hn({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 go({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(Hn,{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 vo({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(Hn,{title:"Layer Stats",children:s.jsx(pn,{compact:!0,layer:r,items:[{id:"entities",label:We(r,t),value:t},{id:"triples",value:n,...r==="vm"?yr:{label:"Stored triples",tooltip:"Promotion normalizes draft blank nodes and can leave draft residue; publication adds provenance. Raw triple counts are not expected to match across memory layers."}},{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 Ar({title:e,footnote:t,context:n,result:r,error:i,extras:a,children:o}){return s.jsxs(Hn,{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 bo({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(Ar,{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 yo({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=mo(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 xr(t,w),b=jr(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(Ar,{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(Wi,{convictionCostCovered:i}),g.chipVisible&&s.jsx(fo,{...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 xo({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(vo,{entities:t,entityCount:n,triples:i,layer:e}),s.jsx(go,{entities:t})]}),(e==="wm"||e==="swm")&&a&&r>0&&s.jsx("div",{className:"v10-layer-widgets-strip-action",children:e==="wm"?s.jsx(bo,{count:r,contextGraphId:a,onComplete:o,onResult:c}):s.jsx(yo,{count:r,contextGraphId:a,onComplete:o,onResult:c})})]})}const jo={working:{layerKey:"wm",icon:"◇",label:"Working"},shared:{layerKey:"swm",icon:"◈",label:"Shared"},verified:{layerKey:"vm",icon:"◉",label:"Verifiable"}},wo=new Set(["http://dkg.io/ontology/profile/QueryCatalog","http://dkg.io/ontology/profile/SavedQuery"]);function ko(e){return e.types.some(t=>wo.has(t))}function Rr({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:E=>{E.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:Qi(j)}),s.jsxs("span",{className:"v10-entity-card-triples",children:[x," triples"]})]})]}),d?(()=>{const E=jo[w.trustLevel];return s.jsxs("span",{className:`v10-trust-badge ${E.layerKey}`,title:`${E.label} Memory`,children:[E.icon," ",E.label]})})():s.jsxs("span",{className:`v10-trust-badge ${t}`,children:[n," ",v]})]},w.uri)})]})}function No({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 E;const v=Oe[e],y=We(e,2),w=f.useMemo(()=>t.filter(z=>!ko(z)).length,[t]),m=((E=a.layerStatus)==null?void 0:E.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=>_=>{_.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(So,{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(xo,{layer:e,entities:t,entityCount:N,actionEntityCount:w,tripleCount:n,contextGraphId:i,onComplete:a.refresh}),s.jsx(Rr,{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(Co,{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 So({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(),...yr},{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 Co({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}:{}),E=wr(N.name,j);u(E.message)}else{const j=await kr(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 E=en(N.name,j);v(E?E.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 E=0;for(const _ of j)N=_.name,(await Xt(e,_.name,_.subGraph?{subGraphName:_.subGraph}:{})).promotedCount===0&&(E+=1);const z=j.length-E;if(z>0){const _=E>0?` (${E} already shared or still committing)`:"";u(`Shared ${z} complete Knowledge Asset${z!==1?"s":""}${_}`)}else u("No Knowledge Assets were newly shared — all were already in Shared Memory or still committing.")}else{const E=await xr(e,j),z=jr(E),_=z?` — ⚠ ${z}`:"";if(E.published>0){const R=E.failures.length?` (${E.failures.length} could not be published)`:"",C=E.partial>0?` — ⚠ ${E.partial}: ${tn(E.partialError)}`:"";u(`Published ${E.published} knowledge asset${E.published!==1?"s":""} to Verifiable Memory${R}${C}${_}`)}else if(z&&E.failures.length===0)u(`⚠ ${z}`);else throw new Error(`${E.failures[0]?`${E.failures[0].name}: ${E.failures[0].error}`:"Publish failed"}${_}`)}l(),r()}catch(j){const E=en(N??"selected assertion",j);v(E?E.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:["› ",ka(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 $o({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=Vi(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(No,{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}=Ki(l,c,d);r({id:Hi(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 Or(e){return`SELECT ?g ?s ?p ?o WHERE {
|
|
37
|
-
GRAPH ?g { ?s ?p ?o }
|
|
38
|
-
${Pn(e)}
|
|
39
|
-
}
|
|
40
|
-
LIMIT 1000`}const rn="User-created SPARQL saved in this node profile for this Context Graph.";function xs(e){return JSON.stringify(e)}function Pn(e){const t=`did:dkg:context-graph:${e}`,n=`${t}/`;return`FILTER(
|
|
41
|
-
(
|
|
42
|
-
STR(?g) = ${xs(t)} ||
|
|
43
|
-
STRSTARTS(STR(?g), ${xs(n)})
|
|
44
|
-
) &&
|
|
45
|
-
!CONTAINS(STR(?g), "/_private")
|
|
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:Or(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
|
-
GRAPH ?g { ?s ?p ?o }
|
|
48
|
-
${Pn(e)}
|
|
49
|
-
}
|
|
50
|
-
GROUP BY ?g
|
|
51
|
-
ORDER BY DESC(?triples)
|
|
52
|
-
LIMIT 100`,resultColumn:"g",rank:2}),a({slug:"types",name:"Types",description:"Count entities by RDF type across the context graph.",sparql:`SELECT ?type (COUNT(DISTINCT ?s) AS ?entities) WHERE {
|
|
53
|
-
GRAPH ?g { ?s a ?type }
|
|
54
|
-
${Pn(e)}
|
|
55
|
-
}
|
|
56
|
-
GROUP BY ?type
|
|
57
|
-
ORDER BY DESC(?entities)
|
|
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}-${ga(o)}`,d=va({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 Ao(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 Ro(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 Oo(e){return e.subGraph===Xe?"context":"subgraph"}function Io(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 Po(e){return hn(e)?"UI-provided SPARQL for common Context Graph checks.":e.subGraph===Xe&&e.slug===nn?rn:e.description??""}function zo(e,t){return hn(e)?"Preset":t==="context"?"Saved":"Subgraph"}function Lo(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 Mo({contextGraphId:e}){var Te;const t=et(),n=f.useMemo(()=>Or(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),E=f.useMemo(()=>_o(e),[e]),z=f.useMemo(()=>js([E,...l,...(t==null?void 0:t.queryCatalogs)??[]]),[E,l,t==null?void 0:t.queryCatalogs]),_=f.useMemo(()=>t!=null&&t.loading||t!=null&&t.error?js([E,...l]):z,[E,l,t==null?void 0:t.error,t==null?void 0:t.loading,z]),R=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:T,error:G,refresh:P}=ft(()=>Nr(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,H=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=R&&R.sparql.trim()===$e?R: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 Yi(e,Se),c(ue=>Ao(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,R,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}),_.length>0&&s.jsx("div",{className:"v10-cg-query-catalog-groups",children:_.map(q=>{const ne=Oo(q),se=ne==="context"||t==null?void 0:t.forSubGraph(q.subGraph),$e=(se==null?void 0:se.color)??"#38bdf8",fe=Io(q,ne,se==null?void 0:se.displayName),ge=Po(q),Se=zo(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&&!H&&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:[R&&(((Te=R.parameters)==null?void 0:Te.length)??0)>0&&s.jsx("div",{className:"v10-cg-query-parameters","aria-label":"Query parameters",children:(R.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:fa(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&&T&&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:Lo(G)}),L&&!T&&!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&&!T&&!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&&!T&&!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=Ro(q[se]);return s.jsx("td",{className:"v10-mlv-cell",title:$e,children:To($e)},se)})},ne))})]})]})]})]})]})}const Fo=({contextGraphId:e,entityUri:t,enabled:n})=>{const r=It(),i=Na(e,t,n),a=Sa(e,t,n),{data:o}=ft(Xi,[],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?Uo(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 Uo(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 Ir={};function st(e){return Ir}function Pr(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 Do(e,t){return typeof t=="bigint"?t.toString():t}function zr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Jn(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 Zo(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 Lr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const qo=zr(()=>{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 Go=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 J(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 Bo(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Wo={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 Vo(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 Qo(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 Ko(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 Ho(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 Yo(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 _t(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 Mr=(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,Do,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fr=I("$ZodError",Mr),Ur=I("$ZodError",Mr,{Parent:Error});function Xo(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 el(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 tl=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 Lr(l,i==null?void 0:i.callee),l}return o.value},nl=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 Lr(l,i==null?void 0:i.callee),l}return o.value},Dr=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??Fr)(a.issues.map(o=>rt(o,i,st())))}:{success:!0,data:a.value}},sl=Dr(Ur),Zr=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}},rl=Zr(Ur),il=/^[cC][^\s-]{8,}$/,al=/^[0-9a-z]+$/,ol=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ll=/^[0-9a-vA-V]{20}$/,cl=/^[A-Za-z0-9]{27}$/,ul=/^[a-zA-Z0-9_-]{21}$/,dl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,pl=/^([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)$/,hl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ml="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function fl(){return new RegExp(ml,"u")}const 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])$/,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})$/,bl=/^((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])$/,yl=/^(([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])$/,xl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qr=/^[A-Za-z0-9_-]*$/,jl=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,wl=/^\+(?:[0-9]){6,14}[0-9]$/,Gr="(?:(?:\\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])))",kl=new RegExp(`^${Gr}$`);function Br(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 Nl(e){return new RegExp(`^${Br(e)}$`)}function Sl(e){const t=Br({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(`^${Gr}T(?:${r})$`)}const Cl=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}$`)},$l=/^\d+$/,_l=/^-?\d+(?:\.\d+)?/i,El=/^[^A-Z]*$/,Al=/^[^a-z]*$/,Re=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Wr={number:"number",bigint:"bigint",object:"date"},Vr=I("$ZodCheckLessThan",(e,t)=>{Re.init(e,t);const n=Wr[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})}}),Qr=I("$ZodCheckGreaterThan",(e,t)=>{Re.init(e,t);const n=Wr[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})}}),Rl=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):Zo(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;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]=Wo[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=$l)}),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})}}),Ol=I("$ZodCheckMaxLength",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Jn(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})}}),Il=I("$ZodCheckMinLength",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Jn(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})}}),Pl=I("$ZodCheckLengthEquals",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Jn(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=()=>{})}),zl=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})}}),Ll=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=El),fn.init(e,t)}),Ml=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Al),fn.init(e,t)}),Fl=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})}}),Ul=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})}}),Dl=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})}}),Zl=I("$ZodCheckOverwrite",(e,t)=>{Re.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class ql{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
|
-
`).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 Gl={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=Gl;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=_t(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=_t(o,u)))});else{if(o.issues.length===u)continue;d||(d=_t(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=sl(e,a);return l.success?{value:l.data}:{issues:(o=l.error)==null?void 0:o.issues}}catch{return rl(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()??Cl(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)}),Bl=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=pl),me.init(e,t)}),Wl=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)}),Vl=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=hl),me.init(e,t)}),Ql=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:jl.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})}}}),Kl=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=fl()),me.init(e,t)}),Hl=I("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ul),me.init(e,t)}),Jl=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=il),me.init(e,t)}),Yl=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=al),me.init(e,t)}),Xl=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ol),me.init(e,t)}),ec=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ll),me.init(e,t)}),tc=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=cl),me.init(e,t)}),nc=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Sl(t)),me.init(e,t)}),sc=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=kl),me.init(e,t)}),rc=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Nl(t)),me.init(e,t)}),ic=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=dl),me.init(e,t)}),ac=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=gl),me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),oc=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vl),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})}}}),lc=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bl),me.init(e,t)}),cc=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=yl),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 Kr(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const uc=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xl),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Kr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function dc(e){if(!qr.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Kr(n)}const pc=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qr),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{dc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),hc=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=wl),me.init(e,t)});function mc(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 fc=I("$ZodJWT",(e,t)=>{me.init(e,t),e._zod.check=n=>{mc(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Hr=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}}),gc=I("$ZodNumber",(e,t)=>{Tl.init(e,t),Hr.init(e,t)}),vc=I("$ZodUnknown",(e,t)=>{je.init(e,t),e._zod.parse=n=>n}),bc=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 yc=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 xc=I("$ZodObject",(e,t)=>{je.init(e,t);const n=zr(()=>{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=Bo(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 ql(["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
|
-
if (${x}.issues.length) {
|
|
63
|
-
if (input[${k}] === undefined) {
|
|
64
|
-
if (${k} in input) {
|
|
65
|
-
newResult[${k}] = undefined;
|
|
66
|
-
}
|
|
67
|
-
} else {
|
|
68
|
-
payload.issues = payload.issues.concat(
|
|
69
|
-
${x}.issues.map((iss) => ({
|
|
70
|
-
...iss,
|
|
71
|
-
path: iss.path ? [${k}, ...iss.path] : [${k}],
|
|
72
|
-
}))
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
} else if (${x}.value === undefined) {
|
|
76
|
-
if (${k} in input) newResult[${k}] = undefined;
|
|
77
|
-
} else {
|
|
78
|
-
newResult[${k}] = ${x}.value;
|
|
79
|
-
}
|
|
80
|
-
`)}else{const x=y[b];u.write(`const ${x} = ${v(b)};`),u.write(`
|
|
81
|
-
if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
|
|
82
|
-
...iss,
|
|
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=!Ir.jitless,c=o&&qo.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),E=N._zod.optin==="optional"&&N._zod.optout==="optional";j instanceof Promise?v.push(j.then(z=>E?Ns(z,h,k,p):Ut(z,h,k))):E?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 jc=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)}}),wc=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),_t(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 kc=I("$ZodEnum",(e,t)=>{je.init(e,t);const n=Pr(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>Go.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}}),Nc=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}}),Sc=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)}),Cc=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)}),$c=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=>_s(a,e)):_s(i,e)}});function _s(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 Ac=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)}}),Rc=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=>Es(a,t,r)):Es(i,t,r)}});function Es(e,t,n){return _t(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 Oc=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 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 Yr(){return new Jr}const Ct=Yr();function Ic(e,t){return new e({type:"string",...J(t)})}function Pc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...J(t)})}function Ts(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...J(t)})}function zc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...J(t)})}function Lc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(t)})}function Mc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(t)})}function Fc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(t)})}function Uc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...J(t)})}function Dc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...J(t)})}function Zc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(t)})}function qc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...J(t)})}function Gc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(t)})}function Bc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...J(t)})}function Wc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...J(t)})}function Vc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(t)})}function Qc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(t)})}function Kc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(t)})}function Hc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(t)})}function Jc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(t)})}function Yc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...J(t)})}function Xc(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...J(t)})}function eu(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...J(t)})}function tu(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...J(t)})}function nu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(t)})}function su(e,t){return new e({type:"string",format:"date",check:"string_format",...J(t)})}function ru(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...J(t)})}function iu(e,t){return new e({type:"string",format:"duration",check:"string_format",...J(t)})}function au(e,t){return new e({type:"number",checks:[],...J(t)})}function ou(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...J(t)})}function lu(e){return new e({type:"unknown"})}function cu(e,t){return new e({type:"never",...J(t)})}function Os(e,t){return new Vr({check:"less_than",...J(t),value:e,inclusive:!1})}function kn(e,t){return new Vr({check:"less_than",...J(t),value:e,inclusive:!0})}function Is(e,t){return new Qr({check:"greater_than",...J(t),value:e,inclusive:!1})}function Nn(e,t){return new Qr({check:"greater_than",...J(t),value:e,inclusive:!0})}function Ps(e,t){return new Rl({check:"multiple_of",...J(t),value:e})}function Xr(e,t){return new Ol({check:"max_length",...J(t),maximum:e})}function an(e,t){return new Il({check:"min_length",...J(t),minimum:e})}function ei(e,t){return new Pl({check:"length_equals",...J(t),length:e})}function uu(e,t){return new zl({check:"string_format",format:"regex",...J(t),pattern:e})}function du(e){return new Ll({check:"string_format",format:"lowercase",...J(e)})}function pu(e){return new Ml({check:"string_format",format:"uppercase",...J(e)})}function hu(e,t){return new Fl({check:"string_format",format:"includes",...J(t),includes:e})}function mu(e,t){return new Ul({check:"string_format",format:"starts_with",...J(t),prefix:e})}function fu(e,t){return new Dl({check:"string_format",format:"ends_with",...J(t),suffix:e})}function Pt(e){return new Zl({check:"overwrite",tx:e})}function gu(e){return Pt(t=>t.normalize(e))}function vu(){return Pt(e=>e.trim())}function bu(){return Pt(e=>e.toLowerCase())}function yu(){return Pt(e=>e.toUpperCase())}function xu(e,t,n){return new e({type:"array",element:t,...J(n)})}function ju(e,t,n){return new e({type:"custom",check:"custom",fn:t,...J(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 E=[...N];E.length===1?m.pattern=E[0].source:E.length>1&&(l.schema.allOf=[...E.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:E}=t._zod.bag;typeof k=="string"&&k.includes("int")?m.type="integer":m.type="number",typeof E=="number"&&(m.exclusiveMinimum=E),typeof b=="number"&&(m.minimum=b,typeof E=="number"&&(E>=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=Pr(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,E=r.external.uri??(_=>_);if(j)return{ref:E(j)};const z=w[1].defId??w[1].schema.id??`schema${this.counter++}`;return w[1].defId=z,{defId:z,ref:`${E("__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
|
-
|
|
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 wu(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 ku=I("ZodISODateTime",(e,t)=>{nc.init(e,t),ve.init(e,t)});function Nu(e){return nu(ku,e)}const Su=I("ZodISODate",(e,t)=>{sc.init(e,t),ve.init(e,t)});function Cu(e){return su(Su,e)}const $u=I("ZodISOTime",(e,t)=>{rc.init(e,t),ve.init(e,t)});function _u(e){return ru($u,e)}const Eu=I("ZodISODuration",(e,t)=>{ic.init(e,t),ve.init(e,t)});function Au(e){return iu(Eu,e)}const Ru=(e,t)=>{Fr.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>el(e,n)},flatten:{value:n=>Xo(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",Ru,{Parent:Error}),Tu=tl(gn),Ou=nl(gn),Iu=Dr(gn),Pu=Zr(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)=>Iu(e,n,r),e.parseAsync=async(n,r)=>Ou(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Pu(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(Nd(n,r)),e.superRefine=n=>e.check(Sd(n)),e.overwrite=n=>e.check(Pt(n)),e.optional=()=>Us(e),e.nullable=()=>Ds(e),e.nullish=()=>Us(Ds(e)),e.nonoptional=n=>gd(e,n),e.array=()=>He(e),e.or=n=>ss([e,n]),e.and=n=>ld(e,n),e.transform=n=>Zs(e,ud(n)),e.default=n=>hd(e,n),e.prefault=n=>fd(e,n),e.catch=n=>bd(e,n),e.pipe=n=>Zs(e,n),e.readonly=()=>jd(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)),ti=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(uu(...r)),e.includes=(...r)=>e.check(hu(...r)),e.startsWith=(...r)=>e.check(mu(...r)),e.endsWith=(...r)=>e.check(fu(...r)),e.min=(...r)=>e.check(an(...r)),e.max=(...r)=>e.check(Xr(...r)),e.length=(...r)=>e.check(ei(...r)),e.nonempty=(...r)=>e.check(an(1,...r)),e.lowercase=r=>e.check(du(r)),e.uppercase=r=>e.check(pu(r)),e.trim=()=>e.check(vu()),e.normalize=(...r)=>e.check(gu(...r)),e.toLowerCase=()=>e.check(bu()),e.toUpperCase=()=>e.check(yu())}),zu=I("ZodString",(e,t)=>{ns.init(e,t),ti.init(e,t),e.email=n=>e.check(Pc(Lu,n)),e.url=n=>e.check(Uc(Mu,n)),e.jwt=n=>e.check(tu(Xu,n)),e.emoji=n=>e.check(Dc(Fu,n)),e.guid=n=>e.check(Ts(Ls,n)),e.uuid=n=>e.check(zc(Dt,n)),e.uuidv4=n=>e.check(Lc(Dt,n)),e.uuidv6=n=>e.check(Mc(Dt,n)),e.uuidv7=n=>e.check(Fc(Dt,n)),e.nanoid=n=>e.check(Zc(Uu,n)),e.guid=n=>e.check(Ts(Ls,n)),e.cuid=n=>e.check(qc(Du,n)),e.cuid2=n=>e.check(Gc(Zu,n)),e.ulid=n=>e.check(Bc(qu,n)),e.base64=n=>e.check(Yc(Hu,n)),e.base64url=n=>e.check(Xc(Ju,n)),e.xid=n=>e.check(Wc(Gu,n)),e.ksuid=n=>e.check(Vc(Bu,n)),e.ipv4=n=>e.check(Qc(Wu,n)),e.ipv6=n=>e.check(Kc(Vu,n)),e.cidrv4=n=>e.check(Hc(Qu,n)),e.cidrv6=n=>e.check(Jc(Ku,n)),e.e164=n=>e.check(eu(Yu,n)),e.datetime=n=>e.check(Nu(n)),e.date=n=>e.check(Cu(n)),e.time=n=>e.check(_u(n)),e.duration=n=>e.check(Au(n))});function K(e){return Ic(zu,e)}const ve=I("ZodStringFormat",(e,t)=>{me.init(e,t),ti.init(e,t)}),Lu=I("ZodEmail",(e,t)=>{Vl.init(e,t),ve.init(e,t)}),Ls=I("ZodGUID",(e,t)=>{Bl.init(e,t),ve.init(e,t)}),Dt=I("ZodUUID",(e,t)=>{Wl.init(e,t),ve.init(e,t)}),Mu=I("ZodURL",(e,t)=>{Ql.init(e,t),ve.init(e,t)}),Fu=I("ZodEmoji",(e,t)=>{Kl.init(e,t),ve.init(e,t)}),Uu=I("ZodNanoID",(e,t)=>{Hl.init(e,t),ve.init(e,t)}),Du=I("ZodCUID",(e,t)=>{Jl.init(e,t),ve.init(e,t)}),Zu=I("ZodCUID2",(e,t)=>{Yl.init(e,t),ve.init(e,t)}),qu=I("ZodULID",(e,t)=>{Xl.init(e,t),ve.init(e,t)}),Gu=I("ZodXID",(e,t)=>{ec.init(e,t),ve.init(e,t)}),Bu=I("ZodKSUID",(e,t)=>{tc.init(e,t),ve.init(e,t)}),Wu=I("ZodIPv4",(e,t)=>{ac.init(e,t),ve.init(e,t)}),Vu=I("ZodIPv6",(e,t)=>{oc.init(e,t),ve.init(e,t)}),Qu=I("ZodCIDRv4",(e,t)=>{lc.init(e,t),ve.init(e,t)}),Ku=I("ZodCIDRv6",(e,t)=>{cc.init(e,t),ve.init(e,t)}),Hu=I("ZodBase64",(e,t)=>{uc.init(e,t),ve.init(e,t)}),Ju=I("ZodBase64URL",(e,t)=>{pc.init(e,t),ve.init(e,t)}),Yu=I("ZodE164",(e,t)=>{hc.init(e,t),ve.init(e,t)}),Xu=I("ZodJWT",(e,t)=>{fc.init(e,t),ve.init(e,t)}),ni=I("ZodNumber",(e,t)=>{Hr.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 au(ni,e)}const ed=I("ZodNumberFormat",(e,t)=>{gc.init(e,t),ni.init(e,t)});function Ms(e){return ou(ed,e)}const td=I("ZodUnknown",(e,t)=>{vc.init(e,t),ke.init(e,t)});function Fs(){return lu(td)}const nd=I("ZodNever",(e,t)=>{bc.init(e,t),ke.init(e,t)});function sd(e){return cu(nd,e)}const rd=I("ZodArray",(e,t)=>{yc.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(Xr(n,r)),e.length=(n,r)=>e.check(ei(n,r)),e.unwrap=()=>e.element});function He(e,t){return xu(rd,e,t)}const id=I("ZodObject",(e,t)=>{xc.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:sd()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Ko(e,n),e.merge=n=>Ho(e,n),e.pick=n=>Vo(e,n),e.omit=n=>Qo(e,n),e.partial=(...n)=>Jo(si,e,n[0]),e.required=(...n)=>Yo(ri,e,n[0])});function pe(e,t){const n={type:"object",get shape(){return Xn(this,"shape",{...e}),this.shape},...J(t)};return new id(n)}const ad=I("ZodUnion",(e,t)=>{jc.init(e,t),ke.init(e,t),e.options=t.options});function ss(e,t){return new ad({type:"union",options:e,...J(t)})}const od=I("ZodIntersection",(e,t)=>{wc.init(e,t),ke.init(e,t)});function ld(e,t){return new od({type:"intersection",left:e,right:t})}const Fn=I("ZodEnum",(e,t)=>{kc.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:[],...J(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:[],...J(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,...J(t)})}const cd=I("ZodTransform",(e,t)=>{Nc.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 ud(e){return new cd({type:"transform",transform:e})}const si=I("ZodOptional",(e,t)=>{Sc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Us(e){return new si({type:"optional",innerType:e})}const dd=I("ZodNullable",(e,t)=>{Cc.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ds(e){return new dd({type:"nullable",innerType:e})}const pd=I("ZodDefault",(e,t)=>{$c.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function hd(e,t){return new pd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const md=I("ZodPrefault",(e,t)=>{_c.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fd(e,t){return new md({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ri=I("ZodNonOptional",(e,t)=>{Ec.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function gd(e,t){return new ri({type:"nonoptional",innerType:e,...J(t)})}const vd=I("ZodCatch",(e,t)=>{Ac.init(e,t),ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function bd(e,t){return new vd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const yd=I("ZodPipe",(e,t)=>{Rc.init(e,t),ke.init(e,t),e.in=t.in,e.out=t.out});function Zs(e,t){return new yd({type:"pipe",in:e,out:t})}const xd=I("ZodReadonly",(e,t)=>{Tc.init(e,t),ke.init(e,t)});function jd(e){return new xd({type:"readonly",innerType:e})}const wd=I("ZodCustom",(e,t)=>{Oc.init(e,t),ke.init(e,t)});function kd(e){const t=new Re({check:"custom"});return t._zod.check=e,t}function Nd(e,t={}){return ju(wd,e,t)}function Sd(e){const t=kd(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"]),Cd={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"},ii=new Set(["Action",...Object.keys(Ue)]),$d=new Set([...Object.keys(rs),...is,...ii]);function Ot(e){return $d.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 ai(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]=ai(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 Ad(){const e=Object.values(rs).map(n=>`@${n.signature} — ${n.description}`),t=Object.values(Cd).map(n=>`@${n.signature} — ${n.description}`);return`## Built-in Functions
|
|
88
|
-
|
|
89
|
-
Data functions prefixed with \`@\` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.
|
|
90
|
-
Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.
|
|
91
|
-
|
|
92
|
-
${[...e,...t].join(`
|
|
93
|
-
`)}
|
|
94
|
-
|
|
95
|
-
Builtins compose — output of one is input to the next:
|
|
96
|
-
\`@Count(@Filter(data.rows, "field", "==", "val"))\` for KPIs/chart values, \`@Round(@Avg(data.rows.score), 1)\`, \`@Each(data.rows, "item", Comp(item.field))\` for per-item rendering.
|
|
97
|
-
Array pluck: \`data.rows.field\` extracts a field from every row → use with @Sum, @Avg, charts, tables.
|
|
98
|
-
|
|
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
|
-
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 Rd(){return`## Query — Live Data Fetching
|
|
102
|
-
|
|
103
|
-
Fetch data from available tools. Returns defaults instantly, swaps in real data when it arrives.
|
|
104
|
-
|
|
105
|
-
\`\`\`
|
|
106
|
-
metrics = Query("tool_name", {arg1: value, arg2: $binding}, {defaultField: 0, defaultData: []}, refreshInterval?)
|
|
107
|
-
\`\`\`
|
|
108
|
-
|
|
109
|
-
- First arg: tool name (string)
|
|
110
|
-
- Second arg: arguments object (may reference $bindings — re-fetches automatically on change)
|
|
111
|
-
- Third arg: default data (rendered immediately before fetch resolves)
|
|
112
|
-
- Fourth arg (optional): refresh interval in seconds (e.g. 30 for auto-refresh every 30s)
|
|
113
|
-
- Use dot access on results: metrics.totalEvents, metrics.data.day (array pluck)
|
|
114
|
-
- Query results must use regular identifiers: \`metrics = Query(...)\`, NOT \`$metrics = Query(...)\`
|
|
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 Td(){return`## Mutation — Write Operations
|
|
117
|
-
|
|
118
|
-
Execute state-changing tool calls (create, update, delete). Unlike Query (auto-fetches on render), Mutation fires only on button click via Action.
|
|
119
|
-
|
|
120
|
-
\`\`\`
|
|
121
|
-
result = Mutation("tool_name", {arg1: $binding, arg2: "value"})
|
|
122
|
-
\`\`\`
|
|
123
|
-
|
|
124
|
-
- First arg: tool name (string)
|
|
125
|
-
- Second arg: arguments object (evaluated with current $binding values at click time)
|
|
126
|
-
- result.status: "idle" | "loading" | "success" | "error"
|
|
127
|
-
- result.data: tool response on success
|
|
128
|
-
- result.error: error message on failure
|
|
129
|
-
- Mutation results use regular identifiers: \`result = Mutation(...)\`, NOT \`$result\`
|
|
130
|
-
- Show loading state: \`result.status == "loading" ? TextContent("Saving...") : null\``}function Od(e){const t=['- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")','- @OpenUrl("https://...") — Navigate to a URL'];e.bindings&&t.push("- @Set($variable, value) — Set a $variable to a specific value",'- @Reset($var1, $var2, ...) — Reset $variables to their declared defaults (e.g. @Reset($title, $priority) restores $title="" and $priority="medium")'),e.toolCalls&&t.unshift("- @Run(queryOrMutationRef) — Execute a Mutation or re-fetch a Query (ref must be a declared Query/Mutation)");const n=[];e.toolCalls&&n.push('Example — mutation + refresh + reset (PREFERRED pattern):\n```\n$binding = "default"\nresult = Mutation("tool_name", {field: $binding})\ndata = Query("tool_name", {}, {rows: []})\nonSubmit = Action([@Run(result), @Run(data), @Reset($binding)])\n```'),n.push('Example — simple nav:\n```\nviewBtn = Button("View", Action([@OpenUrl("https://example.com")]))\n```');const r=['- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work'];return e.toolCalls&&r.push("- If a @Run(mutation) step fails, remaining steps are skipped (halt on failure)","- @Run(queryRef) re-fetches the query (fire-and-forget, cannot fail)"),`## Action — Button Behavior
|
|
131
|
-
|
|
132
|
-
Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.
|
|
133
|
-
Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).
|
|
134
|
-
|
|
135
|
-
Available steps:
|
|
136
|
-
${t.join(`
|
|
137
|
-
`)}
|
|
138
|
-
|
|
139
|
-
${n.join(`
|
|
140
|
-
|
|
141
|
-
`)}
|
|
142
|
-
|
|
143
|
-
${r.join(`
|
|
144
|
-
`)}`}function Id(){return`## Interactive Filters
|
|
145
|
-
|
|
146
|
-
To let the user filter data with a dropdown:
|
|
147
|
-
1. Declare a $variable with a default: \`$dateRange = "14"\`
|
|
148
|
-
2. Create a Select with name, items, and binding: \`Select("dateRange", [SelectItem("7", "Last 7 days"), ...], null, null, $dateRange)\`
|
|
149
|
-
3. Wrap in FormControl for a label: \`FormControl("Date Range", Select(...))\`
|
|
150
|
-
4. Pass $dateRange in Query args: \`Query("tool", {dateRange: $dateRange}, {defaults})\`
|
|
151
|
-
5. When the user changes the Select, $dateRange updates and the Query automatically re-fetches
|
|
152
|
-
|
|
153
|
-
FILTER WIRING RULE: If a $binding filter is visible in the UI, EVERY relevant Query MUST reference that $binding in its args. Never show a filter dropdown while hardcoding the query args.
|
|
154
|
-
|
|
155
|
-
Rules for $variables:
|
|
156
|
-
- $variables hold simple values (strings or numbers), NOT arrays or objects
|
|
157
|
-
- $variables must be bound to a Select/Input component via the value argument (last positional arg) to be interactive
|
|
158
|
-
- Queries must use regular identifiers (NOT $variables): \`metrics = Query(...)\` not \`$metrics = Query(...)\`
|
|
159
|
-
- **Auto-declare**: You do NOT need to explicitly declare $variables. If you use \`$foo\` without declaring it, the parser auto-creates \`$foo = null\`. You can still declare explicitly to set a default: \`$days = "14"\`
|
|
160
|
-
|
|
161
|
-
## Forms
|
|
162
|
-
|
|
163
|
-
Simple form — no $bindings needed. Field values are managed internally by the Form via the name prop:
|
|
164
|
-
\`\`\`
|
|
165
|
-
contactForm = Form("contact", submitBtn, [nameField, emailField])
|
|
166
|
-
nameField = FormControl("Name", Input("name", "Your name", "text", {required: true}))
|
|
167
|
-
emailField = FormControl("Email", Input("email", "your@email.com", "email", {required: true, email: true}))
|
|
168
|
-
submitBtn = Button("Submit")
|
|
169
|
-
\`\`\`
|
|
170
|
-
|
|
171
|
-
Use $bindings when you need to read field values elsewhere (in Action context, Query args, or conditionals). They are auto-declared:
|
|
172
|
-
\`\`\`
|
|
173
|
-
$role = "engineer"
|
|
174
|
-
contactForm = Form("contact", submitBtn, [nameField, emailField, roleField])
|
|
175
|
-
nameField = FormControl("Name", Input("name", "Enter your name", "text", {required: true}, $name))
|
|
176
|
-
emailField = FormControl("Email", Input("email", "Enter your email", "email", {required: true, email: true}, $email))
|
|
177
|
-
roleField = FormControl("Role", Select("role", [SelectItem("engineer", "Engineer"), SelectItem("designer", "Designer"), SelectItem("pm", "PM")], null, {required: true}, $role))
|
|
178
|
-
submitBtn = Button("Submit")
|
|
179
|
-
\`\`\`
|
|
180
|
-
|
|
181
|
-
For form + mutation patterns (create, refresh, reset), see the Action section example above.
|
|
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 Pd(){return`## Edit Mode
|
|
184
|
-
|
|
185
|
-
The runtime merges by statement name: same name = replace, new name = append.
|
|
186
|
-
Output ONLY statements that changed or are new. Everything else is kept automatically.
|
|
187
|
-
|
|
188
|
-
### Delete
|
|
189
|
-
To remove a component, update the parent to exclude it from its children array. Orphaned statements are automatically garbage-collected.
|
|
190
|
-
Example — remove chart: \`root = Stack([header, kpiRow, table])\` — chart is no longer in the children list, so it and any statements only it referenced are auto-deleted.
|
|
191
|
-
|
|
192
|
-
### Patch size guide
|
|
193
|
-
- Changing a title or label: 1 statement
|
|
194
|
-
- Adding a component: 2-3 statements (the new component + parent update)
|
|
195
|
-
- Removing a component: 1 statement (re-declare parent without the removed child)
|
|
196
|
-
- Adding a filter + wiring to query: 3-5 statements
|
|
197
|
-
- Restructuring into tabs: 5-10 statements
|
|
198
|
-
|
|
199
|
-
### Rules
|
|
200
|
-
- Reuse existing statement names exactly — do not rename
|
|
201
|
-
- Do NOT re-emit unchanged statements — the runtime keeps them
|
|
202
|
-
- A typical edit patch is 1-10 statements, not 20+
|
|
203
|
-
- If the existing code already satisfies the request, output only the root statement
|
|
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 zd(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
|
-
|
|
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
|
-
|
|
209
|
-
During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.
|
|
210
|
-
|
|
211
|
-
**Recommended statement order for optimal streaming:**
|
|
212
|
-
${n.join(`
|
|
213
|
-
`)}
|
|
214
|
-
|
|
215
|
-
Always write the root = ${e}(...) statement first so the UI shell appears immediately, even before child data has streamed in.`}function Ld(){return`## Inline Mode
|
|
216
|
-
|
|
217
|
-
You are in inline mode. You can respond in two ways:
|
|
218
|
-
|
|
219
|
-
### 1. Code response (when the user wants to CREATE or CHANGE the UI)
|
|
220
|
-
Wrap openui-lang code in triple-backtick fences. You can include explanatory text before/after:
|
|
221
|
-
|
|
222
|
-
Here's your dashboard:
|
|
223
|
-
|
|
224
|
-
\`\`\`openui-lang
|
|
225
|
-
root = RootComp([header, content])
|
|
226
|
-
header = SomeHeader("Title")
|
|
227
|
-
content = SomeContent("Hello world")
|
|
228
|
-
\`\`\`
|
|
229
|
-
|
|
230
|
-
I created a simple layout with a header.
|
|
231
|
-
|
|
232
|
-
### 2. Text-only response (when the user asks a QUESTION)
|
|
233
|
-
If the user asks "what is this?", "explain the chart", "how does this work", etc. — respond with plain text. Do NOT output any openui-lang code. The existing dashboard stays unchanged.
|
|
234
|
-
|
|
235
|
-
### Rules
|
|
236
|
-
- When the user asks for changes, output ONLY the changed/new statements in a fenced block
|
|
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 Md(){return`## Data Workflow
|
|
239
|
-
|
|
240
|
-
When tools are available, follow this workflow:
|
|
241
|
-
1. FIRST: Call the most relevant tool to inspect the real data shape before generating code
|
|
242
|
-
2. Use Query() for READ operations (data that should stay live) — NEVER hardcode tool results as literal arrays or objects
|
|
243
|
-
3. Use Mutation() for WRITE operations (create, update, delete) — triggered by button clicks via Action([@Run(mutationRef)])
|
|
244
|
-
4. Use the real data from step 1 as condensed Query defaults (3-5 rows) so the UI renders immediately
|
|
245
|
-
5. Use @-prefixed builtins (@Count, @Filter, @Sort, @Sum) on Query results for KPIs and aggregations — the runtime evaluates these live on every refresh
|
|
246
|
-
6. Hardcoded arrays are ONLY for static display data (labels, options) where no tool exists
|
|
247
|
-
|
|
248
|
-
WRONG — you called a tool and got data back, but you inlined the results:
|
|
249
|
-
\`\`\`
|
|
250
|
-
openCount = 2
|
|
251
|
-
item1 = SomeComp("first item title")
|
|
252
|
-
item2 = SomeComp("second item title")
|
|
253
|
-
list = Stack([item1, item2])
|
|
254
|
-
chart = SomeChart(["A", "B"], [12, 8])
|
|
255
|
-
\`\`\`
|
|
256
|
-
This is static — it shows stale data and won't update. Creating item1, item2, item3... manually is ALWAYS wrong when a tool exists.
|
|
257
|
-
|
|
258
|
-
RIGHT — use Query() for live data, Mutation() for writes, @builtins to derive values:
|
|
259
|
-
\`\`\`
|
|
260
|
-
data = Query("tool_name", {}, {rows: []})
|
|
261
|
-
openCount = @Count(@Filter(data.rows, "field", "==", "value"))
|
|
262
|
-
list = @Each(data.rows, "item", SomeComp(item.title, item.field))
|
|
263
|
-
createResult = Mutation("create_tool", {title: $title})
|
|
264
|
-
submitBtn = Button("Create", Action([@Run(createResult), @Run(data), @Reset($title)]))
|
|
265
|
-
\`\`\`
|
|
266
|
-
Everything derives from the Query — when data refreshes, the entire dashboard updates automatically.`}function Fd(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
|
-
- When asked about data, generate realistic/plausible data
|
|
268
|
-
- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)
|
|
269
|
-
|
|
270
|
-
## Final Verification
|
|
271
|
-
Before finishing, walk your output and verify:
|
|
272
|
-
${n.join(`
|
|
273
|
-
`)}`}function Ud(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 Dd(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(Ud(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=ai(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 Zd(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 qd(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(Zd(e,{toolCalls:r,bindings:i,usesActionExpression:o})),a&&(l.push(""),l.push(Ad())),r&&(l.push(""),l.push(Rd()),l.push(""),l.push(Td())),o&&(l.push(""),l.push(Od({toolCalls:r,bindings:i}))),r&&i&&(l.push(""),l.push(Id())),r&&(l.push(""),l.push(Md())),(g=e.tools)!=null&&g.length&&(l.push(""),l.push(Dd(e.tools))),l.push(""),l.push(zd(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(Pd())),e.inlineMode&&(l.push(""),l.push(Ld())),l.push(Fd(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 Gd=new WeakSet;function Et(e){return typeof e=="object"&&e!==null&&Gd.has(e)}const oi=new WeakMap;function Bd(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 Wd(e){return Bd(e.props,e.name),oi.set(e.props,e.name),{...e,ref:e.props}}function Je(e){var t;return(t=e==null?void 0:e._zod)==null?void 0:t.def}function as(e){var t;return(t=Je(e))==null?void 0:t.type}function li(e){const t=as(e);return t==="optional"||t==="default"||t==="nullable"}function zt(e){let t=e,n=Je(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=Je(t);return t}function ci(e){return as(zt(e))==="array"}function Vd(e){const t=Je(zt(e));if((t==null?void 0:t.type)==="array")return t.element??t.innerType}function Qd(e){const t=Je(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 Kd(e,t){try{const n=t.get(e);if(n!=null&&n.id)return n.id}catch{}if(typeof e=="object"&&e!==null)return oi.get(e)}function qs(e){const t=Je(e);if((t==null?void 0:t.type)==="union"&&Array.isArray(t.options))return t.options}function Hd(e){const t=Je(e);if((t==null?void 0:t.type)==="object"&&t.shape&&typeof t.shape=="object")return t.shape}function pt(e,t){const n=Et(e),r=Jd(zt(e),t);if(r)return n?`$binding<${r}>`:r}function Jd(e,t){var l;const n=Kd(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(ci(e)){const c=Vd(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=Je(e);return`Record<${pt(c==null?void 0:c.keyType,t)??"string"}, ${pt(c==null?void 0:c.valueType,t)??"any"}>`}const a=Qd(e);if(a)return a.map(c=>`"${c}"`).join(" | ");if(i==="literal"){const c=(l=Je(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=Hd(e);return o?`{${Object.entries(o).map(([c,d])=>{const g=li(d)?"?":"",h=pt(d,t);return h?`${c}${g}: ${h}`:`${c}${g}`}).join(", ")}}`:"any"}function Yd(e,t){return Object.entries(e).map(([n,r])=>({name:n,isOptional:li(r),isArray:ci(r),typeAnnotation:pt(r,t)}))}function Xd(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:Xd(r,Yd(i.props.shape,t)),description:i.description};return n}function ep(e){const t={},n=Yr();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 qd({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 wu(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 tp(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 np=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:np.has(e.k)}function sp(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 rp=1,Bs=2,Ws=3,Cn=4,kt=5,$n=6,qt=7,Vs=8,ip=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 rp;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 ip;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 ui(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 di(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:ui(e.n,t,"expr");case"Ph":return e;case"Comp":{const i=di(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 ui(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=di(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 tp(e)?Un(e,t):e}}function ap(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 Hs(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 Ht(e=!0){return{root:null,meta:{incomplete:e,unresolved:[],orphaned:[],statementCount:0,errors:[]},stateDeclarations:{},queryStatements:[],mutationStatements:[]}}function pi(e){if(!ht(e))return[];const t=new Set;return sp(e,n=>{n.k==="StateRef"&&t.add(n.n)}),[...t]}function Js(e,t){if(t.k==="Comp"&&t.name===Ye.Query){const n=pi(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 op(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 pi(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 lp(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=lp(e,t,n,o);if(!e.has(l))return Ht(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}=op(t,u);return{root:v,meta:{incomplete:r,unresolved:d,orphaned:[...h],statementCount:i,errors:g},stateDeclarations:y,queryStatements:w,mutationStatements:m}}function cp(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
|
-
`;)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
|
-
`);if(e.startsWith("```")){let r=3;for(;r<e.length&&e[r]!==`
|
|
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
|
-
`).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 up(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 Hs(Ks(u))){const v=Js(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
|
-
`&&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?Ht():Gt(i,[...i.values()],o,!1,a,e,t);const p=er(cp(u)).trim();if(!p)return a===0?Ht():Gt(i,[...i.values()],o,!1,a,e,t);const{text:v,wasIncomplete:y}=ap(p),w=Hs(Ks(v));if(!w.length)return a===0?Ht(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=Js(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 dp(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e.default}function pp(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:dp(a[c])}));t.set(r,{params:l})}return t}function hp(e,t){return up(pp(e),t)}function mp(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 fp(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=mp(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 gp(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 bp(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(ii.has(e.name))return vp(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&&Et(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]=hi(c,t,n,d)}return{...e,props:i}}function hi(e,t,n,r){return mi(e,t,n,r,{recurseElement:i=>cn(i,t,n),recurse:(i,a)=>hi(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 vp(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 Ee(e,t,n){switch(e.k){case"Ref":return e.n===t?Dn(n):e;case"Member":if(ht(e.obj)){const r=Ee(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)?Ee(e.obj,t,n):e.obj,index:ht(e.index)?Ee(e.index,t,n):e.index};case"BinOp":return{...e,left:Ee(e.left,t,n),right:Ee(e.right,t,n)};case"UnaryOp":return{...e,operand:Ee(e.operand,t,n)};case"Ternary":return{...e,cond:Ee(e.cond,t,n),then:Ee(e.then,t,n),else:Ee(e.else,t,n)};case"Arr":return{...e,els:e.els.map(r=>Ee(r,t,n))};case"Obj":return{...e,entries:e.entries.map(([r,i])=>[r,Ee(i,t,n)])};case"Comp":{const r={...e,args:e.args.map(i=>Ee(i,t,n))};if(e.mappedProps){const i={};for(const[a,o]of Object.entries(e.mappedProps))i[a]=Ee(o,t,n);r.mappedProps=i}return r}case"Assign":return{...e,value:Ee(e.value,t,n)};default:return e}}function bp(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=Ee(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 mi(e,t,n,r,i){if(e==null||typeof e!="object")return e;if(ht(e)){if(e.k==="StateRef"&&r&&Et(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):gp(l)&&!(r&&Et(r))?t.getState(l.target)??null:l}if(typeof e=="string"&&r&&Et(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 fi(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]=gi(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 gi(e,t,n,r){return mi(e,t.ctx,n,r,{recurseElement:i=>fi(i,t),recurse:(i,a)=>gi(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 yp(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 xp(e,t,n){const r=n!=null?"::"+tr(n):"";return e+"::"+tr(t)+r}function jp(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 _={__openui_loading:[],__openui_refetching:[],__openui_errors:[]};for(const[R,C]of t){const O=r.get(C.cacheKey);if(O&&O.data!==void 0)_[R]=O.data;else if(C.prevCacheKey){const Z=r.get(C.prevCacheKey);Z&&Z.data!==void 0?_[R]=Z.data:_[R]=C.defaults}else _[R]=C.defaults;C.loading&&(_.__openui_loading.push(R),C.everFetched&&_.__openui_refetching.push(R)),C.error&&_.__openui_errors.push(C.error)}for(const[R,C]of n)_[R]=C.result,C.error&&_.__openui_errors.push(C.error);try{const R=JSON.stringify(_);if(R===o)return!1;a=_,o=R}catch{a=_,o=""}return!0}function g(){for(const _ of[...i])_()}async function h(_,R){if(!e)return;const C=t.get(R);if(!C)return;const O=_,Z=C.toolName,$=C.args;let T=r.get(O);T?T.inFlight=!0:(T={data:void 0,inFlight:!0},r.set(O,T)),C.loading=!0,d(),g();try{const G=await e.callTool(Z,$??{});if(l)return;const P=t.get(R);if(!P||P.cacheKey!==O){T.inFlight=!1;return}if(T.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(R);P&&P.cacheKey===O&&(G instanceof qn?P.error={source:"query",code:"tool-not-found",message:`Query tool "${Z}" not found`,statementId:R,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:R,component:"Query",toolName:Z}:P.error={source:"query",code:"tool-error",message:`Query "${Z}" failed: ${G instanceof Error?G.message:String(G)}`,statementId:R,component:"Query",toolName:Z}),console.error(`Query "${Z}" failed:`,G)}finally{T.inFlight=!1;const G=t.get(R);G&&G.cacheKey===O?(G.loading=!1,d()&&g(),G.needsRefetch&&(G.needsRefetch=!1,h(G.cacheKey,R))):d()&&g()}}function u(_){for(const R of t.values())if(R.cacheKey===_||R.prevCacheKey===_)return;r.delete(_)}function p(_){if(l)return;const R=new Set(_.map(C=>C.statementId));for(const[C,O]of t)R.has(C)||(O.timer&&clearInterval(O.timer),t.delete(C),u(O.cacheKey),O.prevCacheKey&&u(O.prevCacheKey));for(const C of _){if(!C.complete)continue;const O=xp(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),T=r.get(O),G=T&&T.data!==void 0&&!T.inFlight;e&&!G&&!(T!=null&&T.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(_){const R=t.get(_);if(!R)return null;const C=r.get(R.cacheKey);if(C&&C.data!==void 0)return C.data;if(R.prevCacheKey){const O=r.get(R.prevCacheKey);if(O&&O.data!==void 0)return O.data}return R.defaults}function y(_){var R;return((R=t.get(_))==null?void 0:R.loading)??!1}function w(){for(const _ of t.values())if(_.loading)return!0;return!1}function m(_){var C;if(l||!e)return;const R=_!=null&&_.length?_.filter(O=>t.has(O)):[...t.keys()];for(const O of R){const Z=t.get(O);Z&&((C=r.get(Z.cacheKey))!=null&&C.inFlight?Z.needsRefetch=!0:h(Z.cacheKey,O))}}function b(_){const R=new Set(_.map(C=>C.statementId));for(const C of n.keys())R.has(C)||n.delete(C);for(const C of _){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(_,R,C){if(l||!e)return!1;const O=n.get(_);if(!O||O.result.status==="loading")return!1;const Z=c;O.result={status:"loading"},d(),g();let $=!1;try{const T=await e.callTool(O.toolName,R);if(l||Z!==c)return!1;O.result={status:"success",data:T},O.error=void 0,$=!0}catch(T){if(l||Z!==c)return!1;const G=T instanceof Error?T.message:String(T);O.result={status:"error",error:G},T instanceof qn?O.error={source:"mutation",code:"tool-not-found",message:`Mutation tool "${O.toolName}" not found`,statementId:_,component:"Mutation",toolName:O.toolName,hint:T.availableTools.length?`Available tools: ${T.availableTools.join(", ")}`:void 0}:T instanceof Zn?O.error={source:"mutation",code:"mcp-error",message:`Mutation "${O.toolName}" returned an error: ${T.toolErrorText}`,statementId:_,component:"Mutation",toolName:O.toolName}:O.error={source:"mutation",code:"tool-error",message:`Mutation "${O.toolName}" failed: ${G}`,statementId:_,component:"Mutation",toolName:O.toolName}}return d(),g(),$&&(C!=null&&C.length)&&m(C),$}function k(_){var R;return((R=n.get(_))==null?void 0:R.result)??null}function N(_){return i.add(_),()=>i.delete(_)}function j(){return a}function E(){l=!1}function z(){l=!0,c++,i.clear();for(const _ of t.values())_.timer&&(clearInterval(_.timer),_.timer=void 0),_.loading=!1,_.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:E,dispose:z}}function wp(){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 Wd(e)}function kp(e){return ep(e)}const vi=f.createContext(null);function bi(){const e=f.useContext(vi);if(!e)throw new Error("useOpenUI must be used within a <Renderer /> component.");return e}function Np(){return bi().renderNode}f.createContext(void 0);function _n(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e?e.value:e}function Sp({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:o,onError:l},c){const d=f.useMemo(()=>hp(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(()=>wp(),[]),p=f.useMemo(()=>jp(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=>_n(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 _n(u.get(L));const A=u.get(P);if(!(!A||typeof A!="object"||Array.isArray(A)))return _n(A[L])},[u]),j=f.useCallback((P,L,A,M,F=!0)=>{var H,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=(H=b.current).onStateUpdate)==null||X.call(H,u.getSnapshot()))},[u]),E=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 H,X,Y;const M=E(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=(H=x.current)==null?void 0:H.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,E,u]),_=f.useRef([]),R=f.useRef(n);R.current=n;const C=f.useCallback(P=>{R.current||_.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=fi(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]),T=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(...fp(h.meta.errors,t.toJSONSchema(),Object.keys(t.components))),P.push(...Z.current),P.push(..._.current),_.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 H of P)console.warn(`[openui] ${H.source}/${H.code}: ${H.message}`)}},[n,e,h,$,w,t]),{result:$,parseResult:h,contextValue:O,isQueryLoading:T}}var Cp=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 yi(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:yi(t)},n));if(typeof e=="object"&&e!==null){const t=e;if(t.type==="element")return s.jsx(xi,{node:t})}return null}function xi({node:e}){var i;const{library:t,reportError:n}=bi(),r=(i=t.components[e.typeName])==null?void 0:i.component;return r?s.jsx(Cp,{componentName:e.typeName,onError:n,children:s.jsx($p,{el:e,Comp:r})}):null}function $p({el:e,Comp:t}){const n=Np();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 Ap({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 yp(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}=Sp({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:l!=null?u.current:null,onError:d},yi);return f.useEffect(()=>{var m;(m=g.current)==null||m.call(g,v)},[v]),p!=null&&p.root?s.jsx(vi.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(xi,{node:p.root})})]})}):null}f.createContext(null);function Rp(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)]})},Op=({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]})},Ip=({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))}),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-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:Gp(t.object)})]},n))})]}),zp=({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))})]}),Lp=({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))})]}),Mp=({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})]})]}),Fp=({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:Wp(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]})]}),Up=({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]}),Dp=({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=Rp(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]}),Zp=({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]})]}),qp=({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??Bp(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 Gp(e){return os(e).replace(/\^\^<?.*$/,"").replace(/^"(.+)"$/,"$1")}function sr(e){return e?e.length<=16?e:`${e.slice(0,8)}…${e.slice(-6)}`:""}function Bp(e){return e?e.length>22?`${e.slice(0,12)}…${e.slice(-6)}`:e:""}function Wp(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}const Vp=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}),Qp=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:He(pe({label:K(),value:K(),tone:vt(["default","success","warn","danger","info"]).optional()})).max(6).optional()}),component:Op}),Kp=Le({name:"EntityStatsGrid",description:"Grid of numeric stats with labels. Use for summarising counts (files, classes, additions, deletions).",props:pe({stats:He(pe({label:K(),value:ss([K(),Be()]),hint:K().optional()})).min(1).max(8)}),component:Ip}),Hp=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:He(pe({predicate:K(),object:K()})).max(60)}),component:Pp}),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:He(pe({typeLabel:K(),icon:K().optional(),items:He(pe({label:K(),uri:K().optional(),sub:K().optional()})).max(30)})).max(8)}),component:zp}),Yp=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:He(pe({label:K(),uri:K().optional(),sub:K().optional()})).max(40)}),component:Lp}),Xp=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:Mp}),eh=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:Fp}),th=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:Up}),nh=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:Dp}),sh=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:Zp}),rh=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:He(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:He(pe({label:K(),at:K()})).max(6).optional()}),component:qp}),ji=kp({components:[Vp,Qp,Kp,Hp,Jp,Yp,Xp,eh,th,nh,sh,rh],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 En=null;function ih(){return En===null&&(En=ji.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."]})),En}async function*ah(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
|
-
|
|
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 oh=({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=ih();for await(const p of ah({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(ch,{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(Ap,{response:i,library:ji,isStreaming:o})})},lh="LLM not configured",ch=({error:e})=>{const t=Vn(r=>r.openTab);return e.includes(lh)?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 uh({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(wr(x,k))}else{const k=await kr(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?` (${sa})`:"":" (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 dh({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=ea(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[,T]of t)for(const G of T.connections)G.targetUri===e.uri&&$.push({pred:ut(G.predicate),entity:T});return $},[e.uri,t]),j=f.useMemo(()=>n.filter($=>De($.subject)===e.uri||De($.object)===e.uri),[e.uri,n]),E=f.useMemo(()=>ta(e.uri,n,1),[e.uri,n]),z=f.useMemo(()=>{const $=new Set;for(const T of t.values())na(T)&&$.add(De(T.uri));return $},[t]),_=f.useMemo(()=>new Set([De(e.uri)]),[e.uri]),R=f.useMemo(()=>Jt(E,z,{focalSubjects:_}),[E,z,_]),C=f.useMemo(()=>{const $=nt[e.trustLevel];return{labelMode:"humanized",renderer:"2d",labels:Cr({minZoomForLabels:.2}),style:{namespaceColors:Sr($),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(T=>h==null?void 0:h.forType(T)).find(T=>T==null?void 0:T.detailHint)||!(h!=null&&h.contextGraphId)?null:s.jsx("div",{className:"v10-ka-section",children:s.jsx(oh,{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(([$,T])=>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:T.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(($,T)=>{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})]},T)})]}),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(($,T)=>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})]},T))]}),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(($,T)=>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)})]},T))})]}),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:$=>R.length>0?s.jsx(f.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Kn,{data:R,format:"triples",options:C,viewConfig:O,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:T=>(T==null?void 0:T.id)&&T.id!==e.uri&&r(T.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(Fo,{contextGraphId:a,entityUri:e.uri,enabled:e.trustLevel==="verified"}),s.jsx("div",{className:"v10-ka-section-title",children:"Provenance Trail"}),s.jsx(ph,{entity:e}),s.jsx(uh,{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 ph({entity:e}){const t=It(),n=o=>{const l=ra(e,o),c=ia(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?aa(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 hh({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(E=>{j||o(E.subGraphs??[])}).catch(E=>{j||g(E instanceof Error?E.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 E of t.entityList){const z=De(E.uri);for(const _ of E.subGraphs){let R=j.get(_);R||(R=new Set,j.set(_,R)),R.add(z)}}return j},[t.entityList]),{triplesBySubGraph:w,tripleCountBySubGraph:m}=f.useMemo(()=>{const j=new Map;for(const _ of t.allTriples){if(!_.subGraph)continue;let R=j.get(_.subGraph);R||(R=[],j.set(_.subGraph,R)),R.push(_)}for(const _ of t.allTriples)if(!_.subGraph){for(const[R,C]of y)if(Tn(_,{slug:R,isRoot:!1,scopedUris:C})){let O=j.get(R);O||(O=[],j.set(R,O)),O.push(_)}}const E=new Map,z=new Map;for(const[_,R]of j){const O=ms(R,t.entities).map(Z=>({subject:Z.subject,predicate:Z.predicate,object:Z.object}));z.set(_,O.length),E.set(_,ys(O))}return{triplesBySubGraph:E,tripleCountBySubGraph:z}},[t.allTriples,t.entities,y]),b=f.useMemo(()=>{const j=new Map;for(const E of t.entityList)for(const z of E.subGraphs){let _=j.get(z);_||(_={wm:0,swm:0,vm:0},j.set(z,_)),E.trustLevel==="verified"?_.vm++:E.trustLevel==="shared"?_.swm++:_.wm++}return j},[t.entityList]),x=f.useMemo(()=>{const j=new Map;for(const E of t.entityList){const z=De(E.uri);for(const _ of E.subGraphs){let R=j.get(_);R||(R=new Map,j.set(_,R)),R.set(z,E.trustLevel),z!==E.uri&&R.set(E.uri,E.trustLevel)}}return j},[t.entityList]),k=f.useMemo(()=>a.filter(Qn).map(j=>{const E=(i==null?void 0:i.forSubGraph(j.name))??{},z=w.get(j.name)??[],_=y.get(j.name)??new Set,R=x.get(j.name)??new Map;return{slug:j.name,icon:E.icon??"•",color:E.color??"#64748b",displayName:E.displayName??j.name,description:E.description,rank:E.rank??99,entityCount:_.size>0?_.size:j.entityCount,tripleCount:m.get(j.name)??0,triples:Jt(z,_),layerCounts:b.get(j.name)??{wm:0,swm:0,vm:0},entityTrustByUri:R}}).sort((j,E)=>j.rank-E.rank),[a,i,w,m,b,y,x]),N=f.useMemo(()=>{const j=[],E=new Set,z=new Map;let _=0,R=0,C=0;for(const L of t.entityList){if(L.subGraphs.size>0)continue;j.push(L);const A=De(L.uri);E.add(A),z.set(A,L.trustLevel),A!==L.uri&&z.set(L.uri,L.trustLevel),L.trustLevel==="verified"?C++:L.trustLevel==="shared"?R++:_++}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,T=Jt(Z,E),G=ys(T),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:_,swm:R,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:Cr({minZoomForLabels:.8}),style:{classColors:ca,predicateColors:la,namespaceColors:Sr(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(wi,{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 wi({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 mh({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:oa(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 fh({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 E=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,_]=f.useState(E);f.useEffect(()=>{d==null||d(z)},[z,d]);const[R,C]=f.useState(new Map),[O,Z]=f.useState(null),[$,T]=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]),H=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]),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))),R.size>0)for(const W of p){const Q=R.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,R,p,$]),re=f.useMemo(()=>new Set(V.map(U=>U.uri)),[V]),ye=f.useMemo(()=>V.length===F.length?H:H.filter(U=>re.has(U.subject)||re.has(U.object)),[H,F,V,re]),Te=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(R.size>0)for(const Fe of p){const _e=R.get(Fe.slug);if(!_e||_e.size===0)continue;const Pe=ce.properties.get(Fe.predicate);if(!Pe||Pe.length===0||!Pe.some(ot=>_e.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||!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},[Y,t.allTriples,B,e,M,F,p,R,$])??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(R.size>0)for(const Q of p){const ie=R.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,R,$]),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=>{_(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),T(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 Nr(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,_e=U.resultColumn||"uri",Pe=new Set;for(const ot of Fe){const lt=ot[_e];if(!lt)continue;const ct=typeof lt=="string"?lt:String(lt),qe=ct.startsWith("<")&&ct.endsWith(">")?ct.slice(1,-1):ct;Pe.add(qe)}T(Pe)}catch(Q){A((Q==null?void 0:Q.message)??String(Q)),T(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,E]),f.useEffect(()=>{a||m("items")},[e,a]),f.useEffect(()=>{b!==x&&k(x)},[b,x,k]);const at=!(z.size===E.size&&[...z].every(U=>E.has(U)))||R.size>0||!!$,vn=()=>{_(new Set(E)),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(wi,{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=R.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(Rr,{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:Te,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(mh,{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 gh={wm:"items",swm:"items",vm:"items"},lr={wm:"working",swm:"shared",vm:"verified"};function Rn(e){return e==="wm"||e==="swm"||e==="vm"}function vh(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 Ch({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,E]=f.useState(null),[z,_]=f.useState(null),R=f.useRef(null),[C,O]=f.useState(null),Z=f.useCallback(D=>{R.current=D,O(D)},[]),$=f.useRef(null),T=f.useCallback(D=>{$.current=D,D===null&&(R.current=null,O(null)),E(D)},[]),[G,P]=f.useState(null),L=f.useRef(null);f.useEffect(()=>{L.current=p},[p]);const[A,M]=f.useState(gh),[F,B]=f.useState({}),H=f.useRef(null),X=f.useRef(null),Y=f.useRef(null),V=f.useRef(0),re=ba(e),ye=ya(e),Ne=Vn(D=>D.openTab),{data:Te,loading:q,error:ne}=ua(),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,H.current);return{activeLayer:d,activeSubGraph:j,layerTabs:{...A},subGraphTabs:{...F},scroll:{key:te,top:(le==null?void 0:le.scrollTop)??0},subGraphEnabledLayers:j!==null&&R.current?new Set(R.current):null}},[d,j,se,A,F]),fe=f.useCallback(D=>{const te=()=>{const le=cr(D.key,H.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=da(e,{signalErrors:!0,includeQueryCatalog:h&&(d==="wm"||d==="swm")}),bt=Bn(de).total,yt=ma({activeLayer:d,activeSubGraph:j}),Lt=$r(yt?e:void 0),Mt=!j&&d==="overview",at=qa(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?vh(ae):ae,[ae,ie]),Fe=f.useMemo(()=>ie?pa(ae):de.entities,[ae,de.entities,ie]),_e=f.useMemo(()=>p?Fe.get(p)??null:null,[p,Fe]);f.useEffect(()=>{!p||_e||de.loading||(v(null),P(null),Se())},[p,_e,de.loading,Se]);const Pe=f.useCallback((D,te)=>{const le=$.current;if(Se(),T(D),D===null)_(null);else if(te!==void 0){const ze=new Set([lr[te]]);_(ze),R.current=ze,O(ze)}else{if(le!==null&&D===le)return;if(le!==null&&R.current){const ze=new Set(R.current);_(ze),R.current=ze,O(ze)}else _(null),R.current=null,O(null)}v(null),P(null)},[Se,T]),ot=f.useCallback(D=>{Se(),g(D),v(null),P(null),T(null),_(null)},[Se,T]),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(Ai=>le??(ze?Ai:null))},[ge]),ki=f.useCallback(()=>{const D=X.current;if(X.current=null,v(null),P(null),!!D){if(g(D.activeLayer),T(D.activeSubGraph),D.activeSubGraph!==null&&D.subGraphEnabledLayers){const te=new Set(D.subGraphEnabledLayers);_(te),R.current=te,O(te)}M(D.layerTabs),B(D.subGraphTabs),Y.current=D.scroll}},[T]),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]),Ni=f.useCallback(D=>{const te=Rn(d)?d:void 0;qe(D,void 0,te)},[d,qe]),Si=f.useCallback(D=>{qe(D,"page")},[qe]),ls=f.useCallback(()=>{Ne(ha)},[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 Ci=j?re.forSubGraph(j):null,xn=!de.loading&&!de.error&&!de.partial?de.entityList:void 0,$i=_e?"entity":j?"subgraph":d,_i=y.contextGraphId===ue.id?y.list:[],Ei=y.contextGraphId===ue.id?y.status:"loading";return s.jsx(xa.Provider,{value:re,children:s.jsx(ja.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(to,{cg:ue,profile:re,activeSubGraph:Ci,onClearSubGraph:()=>Pe(null)}),s.jsx(eo,{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":$i,"data-cg-scroll-key":"page",ref:H,children:[_e&&s.jsx(dh,{entity:_e,allEntities:Fe,allTriples:ce,onNavigate:qe,onClose:ki,contextGraphId:e,onRefresh:de.refresh}),j&&!_e&&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(fh,{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:()=>{T(null),g("query")}})]}),!j&&d==="overview"&&!_e&&s.jsxs(s.Fragment,{children:[s.jsx(oo,{cg:ue,memory:de,subGraphCount:m,subGraphFetchFailed:x,participants:_i,participantsStatus:Ei,currentAgent:Te??null,currentAgentStatus:q?"loading":ne?"error":"ok",onSwitchLayer:ot,onOpenPrimer:ls}),s.jsx(lo,{contextGraphId:e,curatorStatus:io({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(wa,{entities:de.entityList,lifecycleEvents:vn,lifecycleError:U,onSelectEntity:Si,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(co,{onOpenPrimer:ls})]}),!j&&d==="graph-overview"&&!_e&&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(hh,{contextGraphId:e,memory:de,onNodeClick:bn,onSelectSubGraph:Pe})]}),!j&&d==="query"&&!_e&&s.jsx(Mo,{contextGraphId:e}),!j&&(d==="wm"||d==="swm"||d==="vm")&&!_e&&s.jsxs(s.Fragment,{children:[s.jsx(wn,{contextGraphId:e,profile:re,selected:j,entities:xn,onSelect:Pe,layer:d}),s.jsx($o,{layer:d,memory:de,onNodeClick:bn,onSelectEntity:Ni,contextGraphId:e,activeTab:A[d],onTabChange:D=>lt(d,D),swmAttribution:Lt,showQueryCatalog:h,onShowQueryCatalogChange:u})]})]}),s.jsx(Ra,{open:a,onClose:()=>o(!1),contextGraphId:ue.id,contextGraphName:ue.name}),s.jsx(Oa,{open:l,onClose:()=>c(!1),contextGraphId:ue.id,contextGraphName:ue.name})]})})})}export{Ch as ProjectView};
|