@origintrail-official/dkg-node-ui 10.0.23 → 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.
Files changed (42) hide show
  1. package/README.md +4 -0
  2. package/dist-ui/assets/ActivityFeed-vyl2XdLo.js +99 -0
  3. package/dist-ui/assets/{AgentHub-DyF5Pa70.js → AgentHub-CYfAoOWF.js} +1 -1
  4. package/dist-ui/assets/AgentProfilePage-BjQm0je4.js +1 -0
  5. package/dist-ui/assets/{ApproveWalletsModal-Dd_tHLRP.js → ApproveWalletsModal-CzWJ4KyU.js} +1 -1
  6. package/dist-ui/assets/{ContextGraphPrimitives-BXormriD.js → ContextGraphPrimitives-ecppTns4.js} +1 -1
  7. package/dist-ui/assets/{ConvictionDetailView-BsPTd17P.js → ConvictionDetailView-CuLUhbzR.js} +2 -2
  8. package/dist-ui/assets/MemoryLayerView-Dymg_Zf_.js +2 -0
  9. package/dist-ui/assets/MemoryReadStatus-D4HXCImC.js +1 -0
  10. package/dist-ui/assets/MemoryStackView-Bq8Fbh5W.js +1 -0
  11. package/dist-ui/assets/{Network-BKvJttOu.js → Network-F76S9_1V.js} +1 -1
  12. package/dist-ui/assets/{OnChainProvenanceCard-BV9-G1cT.js → OnChainProvenanceCard-CCwK3sRG.js} +1 -1
  13. package/dist-ui/assets/{Operations-LAhUQsnj.js → Operations-aVCBUh8u.js} +1 -1
  14. package/dist-ui/assets/ProjectView-Cb1PQ-jm.js +290 -0
  15. package/dist-ui/assets/{PublishingConviction-CF6352oT.js → PublishingConviction-BnAJjHL8.js} +2 -2
  16. package/dist-ui/assets/{Settings-runaZqPv.js → Settings-rEyPw1oS.js} +1 -1
  17. package/dist-ui/assets/{browserWalletTransaction-CBgx0i4w.js → browserWalletTransaction-BJBFRjXx.js} +3 -3
  18. package/dist-ui/assets/{ccip-BM07w5uU.js → ccip-DYOqJfs7.js} +1 -1
  19. package/dist-ui/assets/index-CAdbSAQK.css +1 -0
  20. package/dist-ui/assets/index-HEpqHVfE.js +1143 -0
  21. package/dist-ui/assets/index-_vQ99L0s.js +192 -0
  22. package/dist-ui/assets/{jsonld-32FQRO67-DBZOBQji.js → jsonld-32FQRO67-DVqZhSL_.js} +2 -2
  23. package/dist-ui/assets/{jsonld-DOX7dKpf.js → jsonld-Dpm03cay.js} +1 -1
  24. package/dist-ui/assets/renderer-3d-IRPVRQWX-DjW_h88e.js +5126 -0
  25. package/dist-ui/assets/{shikiHighlighter-CzU2U2Tx.js → shikiHighlighter-DL7LOds2.js} +1 -1
  26. package/dist-ui/assets/truncate-BWdqLeqV.js +22 -0
  27. package/dist-ui/assets/{useEntityOnChainReceipt-BvWQ6qdT.js → useEntityOnChainReceipt-B_uLyqZc.js} +5 -5
  28. package/dist-ui/index.html +2 -2
  29. package/package.json +4 -4
  30. package/dist-ui/assets/3d-force-graph-DbVwxMKf.js +0 -1015
  31. package/dist-ui/assets/ActivityFeed-Bfg6fmQQ.js +0 -99
  32. package/dist-ui/assets/AgentProfilePage-BPrSuKjV.js +0 -1
  33. package/dist-ui/assets/MemoryLayerView-CloJeM33.js +0 -2
  34. package/dist-ui/assets/MemoryStackView-BbUJ2uiM.js +0 -1
  35. package/dist-ui/assets/ProjectView-0zCSblAV.js +0 -290
  36. package/dist-ui/assets/index-CfVUpsfM.js +0 -192
  37. package/dist-ui/assets/index-MQh8C4aJ.js +0 -1175
  38. package/dist-ui/assets/index-xKO-U_eV.css +0 -1
  39. package/dist-ui/assets/renderer-3d-2EVDZII7-CVCpAmwB.js +0 -2
  40. package/dist-ui/assets/three.module-BXIk8GZS.js +0 -4112
  41. package/dist-ui/assets/truncate-BaiMkAOo.js +0 -1
  42. package/dist-ui/assets/useProjectActivity-Cxr4QGX1.js +0 -1
@@ -0,0 +1,290 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-_vQ99L0s.js","assets/index-HEpqHVfE.js","assets/index-CAdbSAQK.css","assets/string-DtUow4KV.js"])))=>i.map(i=>d[i]);
2
+ var Ai=Object.defineProperty;var Ri=(e,t,n)=>t in e?Ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var yt=(e,t,n)=>Ri(e,typeof t!="symbol"?t+"":t,n);import{aU as s,v as $e,bj as m,bG as st,a5 as Ti,bM as un,t as Oi,bN as dr,aK as Pi,q as dn,aZ as Ii,Z as zi,aY as pr,bm as Li,p as hr,bl as mr,R as Se,n as Ct,_ as Mi,L as Ie,bJ as fr,bU as Fi,ap as Ht,s as Ui,aJ as gr,E as vr,i as Di,u as ze,b5 as Bn,bE as Wn,aW as He,bO as Zi,bR as br,an as qi,a0 as Gi,a1 as Bi,ac as ds,x as ps,bb as Wi,V as yr,O as pn,bh as Xt,I as en,bi as xr,b7 as jr,b9 as tn,f as Vi,aL as Ki,J as wr,aV as kr,bI as Qi,N as Vn,Q as Vt,ax as Ji,bT as Kn,S as wn,M as hs,l as ms,D as fs,bn as Yi,K as Hi,Y as Nr,bY as Xi,ak as ea,aF as ta,bp as ct,b3 as na,aM as sa,T as nt,b4 as Sr,b1 as Cr,P as ra,by as ia,bz as aa,aA as oa,m as On,o as gs,az as la,a as ca,C as ua,bF as da,bL as pa,b as ha,bq as ma}from"./index-HEpqHVfE.js";import{e as Qn,R as Ve,h as et,f as Ot,a as mt,p as kt,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-vyl2XdLo.js";import{M as ka}from"./MemoryReadStatus-D4HXCImC.js";import{E as je,t as Et,S as hn}from"./ContextGraphPrimitives-ecppTns4.js";import{l as Jn,a as Na,f as Sa,t as Ca}from"./truncate-BWdqLeqV.js";import{b as $a,u as _a,a as vs,t as ut}from"./useEntityOnChainReceipt-B_uLyqZc.js";function Ea(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 Aa={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 Ra({verdict:e,accountId:t,discountBps:n,accountUntracked:r=!1,reasons:i=[],ownerPublish:a=!1,variant:o="banner",children:l,className:c=""}){const d=Aa[e],g=e==="fallthrough"||e==="fallthrough-no-funds",p=g?"alert":"status",u=g?"assertive":"polite",h=t?`PCA #${t}`:"a PCA",v=r?" (not tracked by this node)":"",y=Ea(n),j=" unless this graph’s registration escrow already covers it",f=i.length>0?` Reason: ${i.join("; ")}.`:"";if(o==="chip"){const x=e==="eligible"?`Funded by ${h}${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:p,"aria-live":u,children:x})})}let b;return e==="eligible"?b=s.jsxs(s.Fragment,{children:["This publish will use ",h,v,y?` (${y} discount)`:"",".",a?`${j}.`:""]}):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 ${h}’s ${y} discount`:"",a?j:"","; the publish fails if that TRAC is below the fee.",f]}):e==="fallthrough-no-funds"?b=s.jsxs(s.Fragment,{children:["This publish will FAIL — no signing wallet can cover it",y?`, forfeiting ${h}’s ${y} discount`:"",a?j:"",".",f]}):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:p,"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})]})}function Ta(e){const t=new Set;return e.filter(n=>{const r=`${$e(n.subject)}|${n.predicate}|${$e(n.object)}`;return t.has(r)?!1:(t.add(r),!0)})}const Pn={wm:"working",swm:"shared",vm:"verified"};function Oa(e,t,n,r){const i=new Set(t.blankGraphs),a=$e(n);return[...t.triples,...e.filter(o=>!t.partial&&(!r||o.layer===Pn[r])&&($e(o.subject)===a||$e(o.object)===a)?!1:!i.has(o.graph)||!o.subject.startsWith("_:")&&!o.object.startsWith("_:"))]}function Pa(e,t,n,r,i){var k;const a=t===null?null:$e(t),o=JSON.stringify([e,n,r]),l=(a==null?void 0:a.startsWith("_:"))??!1,c=l?null:a,[d,g]=m.useState({scope:o,preview:i.allTriples,uri:c});(d.scope!==o||d.preview!==i.allTriples||c!==null&&d.uri!==c||a===null&&d.uri!==null)&&g({scope:o,preview:i.allTriples,uri:c});const p=st(()=>Ti(e,d.uri,n??void 0,r),[d],0,{scope:d,retention:"scope",enabled:d.uri!==null}),u=!l||(k=p.data)!=null&&k.triples.some(E=>E.subject===a||E.object===a)?p.data:null,h=m.useCallback(()=>{(!l||u)&&p.refresh()},[l,u,p.refresh]);un(e,()=>{a&&h()});const v=m.useMemo(()=>{const E=u?Oa(i.allTriples,u,d.uri,n):i.allTriples;return n?E.filter(w=>w.layer===Pn[n]):E},[i.allTriples,u,d.uri,n]),y=m.useMemo(()=>Ta(v),[v]),j=m.useMemo(()=>n||u?Oi(v):i.entities,[v,n,u,i.entities]),f=u&&!u.partial&&a===d.uri,b=a&&!f?i.entities.get(a):void 0;return{entity:a?j.get(a)??(b&&(!n||b.layers.has(Pn[n]))?b:null):null,entities:j,triples:y,loading:!l&&p.loading,error:!l||u?p.error:null,partial:(u==null?void 0:u.partial)??(l&&i.partial),refresh:h}}const Ia=".md, .docx, .pdf, .txt, .csv, .json, .ttl, .rdf, .owl, .py, .ts, .js, .tsx, .jsx, .java, .go, .rs, .c, .cpp, .html, .xml, .yaml, .yml";function bs(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function za(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 La({open:e,onClose:t,contextGraphId:n,contextGraphName:r}){var I;const[i,a]=m.useState([]),[o,l]=m.useState(!0),[c,d]=m.useState(!0),[g,p]=m.useState("idle"),[u,h]=m.useState(0),[v,y]=m.useState([]),[j,f]=m.useState(null),[b,x]=m.useState(!1),k=m.useRef(null),E=m.useCallback($=>{const W=Array.from($);a(q=>{const K=new Set(q.map(ee=>`${ee.file.name}:${ee.file.size}`)),oe=W.filter(ee=>!K.has(`${ee.name}:${ee.size}`));return[...q,...oe.map(ee=>({file:ee,id:`${ee.name}-${ee.size}-${Date.now()}`}))]})},[]),w=$=>{a(W=>W.filter(q=>q.id!==$))},R=$=>{$.preventDefault(),$.stopPropagation(),x(!0)},M=$=>{$.preventDefault(),$.stopPropagation(),x(!1)},_=$=>{$.preventDefault(),$.stopPropagation(),x(!1),$.dataTransfer.files.length>0&&E($.dataTransfer.files)},O=async()=>{if(i.length===0)return;p("uploading"),h(0),y([]),f(null);const $=[];for(let q=0;q<i.length;q++){h(q);const{file:K}=i[q],oe=K.name.replace(/[^a-zA-Z0-9._-]/g,"_"),ee=`${Date.now().toString(36)}-${q}-${oe}`;try{const F=await Pi(ee,n,K),Z=F.extraction.tripleCount??F.extraction.triplesWritten;$.push({fileName:K.name,status:F.extraction.status==="completed"?"success":F.extraction.status==="skipped"?"skipped":"error",triplesWritten:Z,error:F.extraction.error})}catch(F){$.push({fileName:K.name,status:"error",error:(F==null?void 0:F.message)??"Upload failed"})}}y($),h(i.length);const W=$.some(q=>q.status==="error");p(W?"error":"done")},C=()=>{g!=="uploading"&&(a([]),y([]),p("idle"),f(null),h(0),t())},{dialogRef:P,onBackdropClick:D}=dr(e,C);if(!e)return null;const S=v.reduce(($,W)=>$+(W.triplesWritten??0),0),T=v.filter($=>$.status==="success").length,L=v.filter($=>$.status==="skipped").length,A=v.filter($=>$.status==="error").length;return s.jsx("div",{className:"v10-modal-overlay",onClick:D,role:"presentation",children:s.jsxs("div",{className:"v10-modal-box",style:{maxWidth:560},ref:P,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:[j&&s.jsx("div",{className:"v10-modal-error",children:j}),g==="idle"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`v10-import-dropzone ${b?"drag-over":""}`,onClick:()=>{var $;return($=k.current)==null?void 0:$.click()},onDragOver:R,onDragLeave:M,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: ",Ia]}),s.jsx("input",{ref:k,type:"file",multiple:!0,style:{display:"none"},onChange:$=>{$.target.files&&E($.target.files),$.target.value=""}})]}),i.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"v10-import-file-list",children:i.map($=>s.jsxs("div",{className:"v10-import-file-item",children:[s.jsx("span",{className:"v10-import-file-icon",children:za($.file.name)}),s.jsx("span",{className:"v10-import-file-name",children:$.file.name}),s.jsx("span",{className:"v10-import-file-size",children:bs($.file.size)}),s.jsx("button",{className:"v10-import-file-remove",onClick:()=>w($.id),title:"Remove",children:"×"})]},$.id))}),s.jsxs("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginBottom:12},children:[i.length," file",i.length!==1?"s":""," selected · ",bs(i.reduce(($,W)=>$+W.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:((I=i[u])==null?void 0:I.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 ${A>0?"error":"success"}`,"data-testid":"import-result","data-import-status":A>0?"error":"success","data-import-triples":S,children:A===0?s.jsxs(s.Fragment,{children:[T>0&&s.jsxs(s.Fragment,{children:["Successfully imported ",T," file",T!==1?"s":"",".",S>0&&s.jsxs(s.Fragment,{children:[" Extracted ",s.jsx("strong",{children:S.toLocaleString()})," triples into working memory."]})]}),L>0&&s.jsxs(s.Fragment,{children:[T>0?" ":"","Stored ",L," file",L!==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",L>0&&s.jsxs(s.Fragment,{children:[", ",L," stored without extraction"]}),", ",A," failed.",S>0&&s.jsxs(s.Fragment,{children:[" ",S.toLocaleString()," triples extracted."]})]})}),v.length>0&&s.jsx("div",{className:"v10-import-file-list",style:{marginTop:12},children:v.map(($,W)=>s.jsxs("div",{className:"v10-import-file-item",children:[s.jsx("span",{className:"v10-import-file-icon",children:$.status==="success"?"✓":$.status==="skipped"?"–":"✗"}),s.jsx("span",{className:"v10-import-file-name",children:$.fileName}),s.jsx("span",{className:"v10-import-file-size",style:$.status==="error"?{color:"var(--text-danger)"}:void 0,children:$.status==="success"&&$.triplesWritten!=null?`${$.triplesWritten} triples`:$.status==="skipped"?"stored (no extraction)":$.error??"failed"})]},W))})]})]}),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:O,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 Ma(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Fa({open:e,onClose:t,contextGraphId:n,contextGraphName:r}){const[i,a]=m.useState(null),[o,l]=m.useState(null),[c,d]=m.useState([]),[g,p]=m.useState(null),[u,h]=m.useState([]),[v,y]=m.useState([]),[j,f]=m.useState(null),[b,x]=m.useState("allowlist");m.useEffect(()=>{e&&(fetch("/api/status",{headers:dn()}).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([])),zi().then(C=>{const P=(C.agents??[]).filter(D=>D.connectionStatus!=="self");h(P)}).catch(()=>h([])),pr(n).then(C=>y(C.requests)).catch(()=>y([])))},[e,n]);const{dialogRef:k,onBackdropClick:E}=dr(e,t);if(!e)return null;const w=o?`${n}
3
+ ${o}`:null,R=(C,P)=>{navigator.clipboard.writeText(C).then(()=>{a(P),setTimeout(()=>a(null),2e3)}).catch(()=>{})},M=async C=>{try{await Li(n,C),d(P=>P.filter(D=>D!==C))}catch{}},_=async C=>{f(C);try{await hr(n,C),y(P=>P.filter(D=>D.agentAddress!==C)),d(P=>[...new Set([...P,C])])}catch(P){p((P==null?void 0:P.message)||"Failed to approve")}finally{f(null)}},O=async C=>{f(C);try{await mr(n,C),y(P=>P.filter(D=>D.agentAddress!==C))}catch(P){p((P==null?void 0:P.message)||"Failed to reject")}finally{f(null)}};return s.jsx("div",{className:"v10-modal-overlay",onClick:E,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 P=u.find(D=>{var S;return((S=D.agentAddress)==null?void 0:S.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:P?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontFamily:"var(--font-body)",fontWeight:500},children:P.name})," ",s.jsx("span",{style:{color:"var(--text-tertiary)",fontSize:10},children:Ma(C)})]}):C}),s.jsx("button",{onClick:()=>M(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"}),w===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:w}),s.jsx("button",{className:"v10-modal-btn primary",onClick:()=>R(w,"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:j===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:j===C.agentAddress?"…":"Approve"}),s.jsx("button",{onClick:()=>O(C.agentAddress),disabled:j===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 Nt=["#6366f1","#14b8a6","#f43f5e","#facc15","#8b5cf6","#10b981","#0ea5e9","#d946ef"],ys=1e4;function xt(e){if(e!=null)return typeof e=="string"?e.startsWith('"')?e.replace(/^"/,"").replace(/"(\^\^<[^>]*>)?$/,""):e:typeof e=="object"&&e!==null&&"value"in e?String(e.value):String(e)}function Ua(e){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 Da(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 qa(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 Ga(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t)%Nt.length}function Ba(e){const t=[...new Set(e)].sort(),n=new Set,r=new Map;for(const i of t){const a=Ga(i);let o=a;if(n.size<Nt.length){for(let l=0;l<Nt.length;l++){const c=(a+l)%Nt.length;if(!n.has(c)){o=c;break}}n.add(o)}r.set(i,Nt[o])}return r}function $r(e){const[t,n]=m.useState(new Map),[r,i]=m.useState([]),[a,o]=m.useState([]),[l,c]=m.useState(new Map),[d,g]=m.useState(null),[p,u]=m.useState(!1),[h,v]=m.useState(void 0),y=m.useRef(0);m.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 E=!1,w;const R=()=>!E&&x===y.current;return u(!0),g(null),(async()=>{var M;try{const _=new Promise(($,W)=>{w=setTimeout(()=>{k.abort(),W(new Error(`SWM attribution query timed out after ${Math.round(ys/1e3)}s`))},ys)}),O=(async()=>{const $=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...dn()},signal:k.signal,body:JSON.stringify({sparql:qa(e)})});if(!$.ok)throw new Error(`SPARQL query failed: ${$.status}`);return $.json()})(),C=await Promise.race([O,_]),D=(((M=C==null?void 0:C.result)==null?void 0:M.bindings)??[]).slice().reverse(),S=new Map,T=new Map,L=[];for(const $ of D){const W=xt($.op),q=xt($.root),K=xt($.agent),oe=xt($.publishedAt),ee=xt($.g);if(!W||!q||!K||!oe)continue;const F=Da(K),Z=ee?Za(ee,e):void 0;L.push({opUri:W,rootUri:q,agent:F,publishedAt:oe,subGraph:Z});const H={agent:F,opUri:W,publishedAt:oe,subGraph:Z},te=S.get(q);te?te.some(Te=>Te.agent===F)||te.push(H):S.set(q,[H]);let xe=T.get(F);xe||(xe=new Set,T.set(F,xe)),xe.add(q)}const A=Ba(T.keys()),I=[...T.entries()].map(([$,W])=>({agent:$,color:A.get($),label:Ua($),entityCount:W.size})).sort(($,W)=>W.entityCount-$.entityCount);if(!R())return;n(S),i(L),o(I),c(A),v(e)}catch(_){if(!R())return;g((_==null?void 0:_.message)??"Failed to load SWM attributions"),n(new Map),i([]),o([]),c(new Map),v(e)}finally{w&&clearTimeout(w),R()&&u(!1)}})(),()=>{E=!0,w&&clearTimeout(w),k.abort()}},[e]);const{nodeColors:j,conflicts:f}=m.useMemo(()=>{const x={},k=[];for(const[E,w]of t)if(w.length!==0)if(w.length===1){const R=w[0].agent,M=l.get(R);M!==void 0&&(x[E]=M)}else k.push(E),x[E]="#f59e0b";return{nodeColors:x,conflicts:k}},[t,l]);return{resultContextGraphId:h,attributions:t,events:r,palette:a,nodeColors:j,conflicts:f,loading:!!(e&&(p||h!==e)),error:d}}function Wa(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 xs=1e4,In="http://dkg.io/ontology/";function Va(e){const t=`did:dkg:context-graph:${e}/_meta`;return`PREFIX dkg: <${In}>
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 qe(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 Ka(e){return e===`${In}AssertionCreated`?"created":e===`${In}AssertionPromoted`?"promoted":null}function Qa(e){const[t,n]=m.useState([]),[r,i]=m.useState(!!e),[a,o]=m.useState(null),[l,c]=m.useState(void 0),d=m.useRef(void 0),g=m.useRef(void 0);return m.useEffect(()=>{if(!e){i(!1);return}d.current!=null&&d.current!==e&&(n([]),o(null),c(void 0),g.current=void 0);let p=!1;const u=new AbortController;let h;return d.current=e,i(!0),o(null),(async()=>{var v;try{const y=new Promise((k,E)=>{h=setTimeout(()=>{u.abort(),E(new Error(`Assertion-lifecycle query timed out after ${Math.round(xs/1e3)}s`))},xs)}),j=(async()=>{const k=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json",...dn()},signal:u.signal,body:JSON.stringify({sparql:Va(e),contextGraphId:e})});if(!k.ok)throw new Error(`SPARQL query failed: ${k.status}`);return k.json()})(),f=await Promise.race([j,y]);if(p||d.current!==e)return;const b=((v=f==null?void 0:f.result)==null?void 0:v.bindings)??[],x=[];for(const k of b){const E=qe(k.event),w=qe(k.type),R=qe(k.assertion),M=qe(k.name),_=qe(k.agent),O=qe(k.ts);if(!E||!R||!_||!O)continue;const C=Ka(w);if(!C)continue;let P;if(C==="promoted"){const T=qe(k.entityCount),L=T!=null?Number(T):NaN;if(Number.isFinite(L)&&L>0)P=L;else{const A=qe(k.subjectEntityCount),I=A!=null?Number(A):NaN;Number.isFinite(I)&&I>=0&&(P=I)}}let S=qe(k.subGraphName);if(S===void 0){const T=qe(k.assertionGraph);T&&(S=Wa(T,e))}x.push({eventUri:E,kind:C,assertionUri:R,assertionName:M??"",agentUri:_,publishedAt:O,subGraph:S,entityCount:P})}n(x),c(e),g.current=e,o(null)}catch(y){if(p||(y==null?void 0:y.name)==="AbortError")return;o(y.message??String(y)),g.current!==e&&n([]),c(e),g.current=e}finally{h&&clearTimeout(h),p||i(!1)}})(),()=>{p=!0,u.abort(),h&&clearTimeout(h)}},[e]),m.useMemo(()=>({resultContextGraphId:l,events:t,loading:r,error:a}),[l,t,r,a])}const Ja={wm:"working",swm:"shared",vm:"verified"};function Ya(e){var u,h,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,p=0;for(const j of e)if(j.types.includes(o))((u=j.properties.get(n))==null?void 0:u[0])==="proposed"&&d++;else if(j.types.includes(l)){const f=(h=j.properties.get(i))==null?void 0:h[0],b=(v=j.properties.get(r))==null?void 0:v[0];f==="p0"&&b!=="done"&&b!=="cancelled"&&g++}else j.types.includes(c)&&((y=j.properties.get(a))==null?void 0:y[0])==="open"&&p++;return d>0&&t.set("decisions",{label:`${d} proposed`,tone:"warn"}),g>0&&t.set("tasks",{label:`${g} p0`,tone:"danger"}),p>0&&t.set("github",{label:`${p} open`,tone:"info"}),t}const kn=({contextGraphId:e,profile:t,selected:n,onSelect:r,entities:i,layer:a,enabledScope:o,allTriplesTotal:l})=>{const[c,d]=Se.useState([]),[g,p]=Se.useState(!0),u=Se.useMemo(()=>Ya(i),[i]),h=Se.useRef(0),v=Se.useMemo(()=>o&&o.size>0&&o.size<3?new Set(o):o&&o.size>=3?null:a?new Set([Ja[a]]):null,[o,a]),y=Se.useMemo(()=>{if(!i)return null;const S=new Map;for(const T of i)if(!(v&&!v.has(T.trustLevel)))for(const L of T.subGraphs)S.set(L,(S.get(L)??0)+1);return S},[v,i]),j=Se.useMemo(()=>{if(!i)return null;let S=0;for(const T of i)v&&!v.has(T.trustLevel)||S++;return S},[v,i]),f=Se.useMemo(()=>{if(!i)return null;let S=0;for(const T of i)v&&!v.has(T.trustLevel)||T.subGraphs.size>0||S++;return S},[v,i]),b=Se.useCallback(()=>{const S=++h.current;p(!0),Ct.fetchSubGraphs(e).then(T=>{S===h.current&&d(T.subGraphs??[])}).catch(()=>{}).finally(()=>{S===h.current&&p(!1)})},[e]);Se.useEffect(()=>(b(),()=>{h.current++}),[b]),un(e,b);const x=Se.useMemo(()=>c.filter(Qn).map(S=>{const T=t.forSubGraph(S.name),L=y!==null?y.get(S.name)??0:S.entityCount;return{slug:S.name,icon:T.icon??"•",color:T.color??"#64748b",displayName:T.displayName??S.name,description:T.description??S.description,rank:T.rank??99,entityCount:L,tripleCount:S.tripleCount,layerScoped:y!==null}}).sort((S,T)=>S.rank-T.rank),[c,t,y]),E=f!==null&&f>0||n===Ve;if(g&&x.length===0&&!E||x.length===0&&!E)return null;const w=j??x.reduce((S,T)=>S+T.entityCount,0),R=x.reduce((S,T)=>S+T.tripleCount,0),M={working:"Working Memory",shared:"Shared Working Memory",verified:"Verifiable Memory"},_=v?[...v].map(S=>M[S]).join(" + "):null,O=_?` in ${_}`:"",P=`Total distinct entities — includes those in named subgraphs (some may belong to more than one), plus Root entities not in any subgraph · ${w} entities${O}${_?"":` · ${l??R} triples`}`,D=`All — total distinct entities. Includes those in named subgraphs (some may belong to more than one), plus Root entities not in any subgraph. ${w} entities${O}.`;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:P,"aria-label":D,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:w})]}),x.map(S=>{const T=u.get(S.slug);return s.jsxs("button",{type:"button",className:`v10-subgraph-chip${n===S.slug?" active":""}${T?" has-badge":""}`,onClick:()=>r(S.slug,a),title:`${S.displayName}${S.description?" · "+S.description:""} · ${S.entityCount} entities${O}${_?"":` · ${S.tripleCount} triples`}${T?" · "+T.label:""}`,style:{"--sg-color":S.color},children:[s.jsx("span",{className:"v10-subgraph-chip-icon",style:{color:S.color},children:S.icon}),s.jsx("span",{className:"v10-subgraph-chip-label",children:S.displayName}),s.jsx("span",{className:"v10-subgraph-chip-count",children:S.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]})]},S.slug)}),E&&(()=>{const S=f??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":S,onClick:()=>r(Ve,a),title:`Entities not in any subgraph (Context Graph root) · ${S} entities${O}`,"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:S})]})})()]})},Yn=m.lazy(()=>Mi(()=>import("./index-_vQ99L0s.js").then(e=>e.h),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.RdfGraph}))),Ha="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",Xa=new Map(Di.map((e,t)=>[e,t]));function Kt(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 Ue(e){const t=e.trim();return t.startsWith("<")&&t.endsWith(">")?t.slice(1,-1):t}function eo(e){const t=new Set,n=new Map,r=new Map,i=new Map;for(const l of e){const c=Ue(l.subject);t.add(c);const d=Xa.get(l.predicate);if(d!==void 0){const p=vr(l.object).trim();if(p){const u=i.get(c);(u===void 0||d<u)&&(r.set(c,p),i.set(c,d))}}if(Ue(l.predicate)===Ha||!Kt(l.object))continue;const g=Ue(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(Ue(l.subject))&&!o.has(Ue(l.object))),singletonItems:a}}function to(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 no({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 so=2500;function js(e,t=so){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,p]=m.useState(!1);m.useEffect(()=>{if(!g)return;const v=y=>{y.key==="Escape"&&p(!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:()=>p(!0),title:`Expand ${e}`,"aria-label":`Expand ${e}`,children:"⤢"}),h=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(no,{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&&h(!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&&p(!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:()=>p(!1),"aria-label":`Close expanded ${e}`,children:"×"})]}),s.jsx("div",{className:"v10-graph-expanded-body",children:h(!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:p}=Ie[e],u=o??p,h=fr(F=>F.theme),v=m.useMemo(()=>{if(e!=="vm")return;const F=new Set;for(const Z of t)F.add(Z.subject),Kt(Z.object)&&F.add(Z.object);return F},[t,e]),{anchors:y,decorationTriples:j}=Fi(e==="vm"&&r?r:void 0,v),f=$r(e==="swm"&&r&&!c?r:void 0),b=c??f,x=m.useMemo(()=>{if(!d||d.length===0)return t;const F=new Set;for(const Z of d)F.add($e(Z.uri));return Ht(t,F)},[t,d]),k=m.useMemo(()=>{const F=new Set,Z=[],H=te=>{const xe=`${te.subject}|${te.predicate}|${te.object}`;F.has(xe)||(F.add(xe),Z.push({subject:te.subject,predicate:te.predicate,object:te.object}))};for(const te of x)H(te);for(const te of j)H(te);return Z},[x,j]),E=k,w=m.useMemo(()=>{const F=e==="swm"?b.nodeColors:void 0;if(!(!F&&!g))return F?g?{...F,...g}:F:g},[e,b.nodeColors,g]),{canvasTriples:R,singletonItems:M}=m.useMemo(()=>eo(E),[E]),_=m.useMemo(()=>{const F=new Set;for(const Z of R)F.add(Ue(Z.subject)),Kt(Z.object)&&F.add(Ue(Z.object));return F.size},[R]),[O,C]=m.useState(null),P=JSON.stringify([r,e,i]),D=O===P,S=m.useMemo(()=>{const F=Ui(e,w);return D&&(F.focus={...F.focus,maxNodes:Math.max(3e3,_)}),F},[e,w,D,_]),T=m.useMemo(()=>{if(!l||l.length===0)return M;const F=new Set(M.map(H=>Ue(H.uri)));for(const H of R)F.add(Ue(H.subject)),Kt(H.object)&&F.add(Ue(H.object));const Z=[];for(const H of l){const te=Ue(H.uri);F.has(te)||(F.add(te),Z.push({uri:te,label:H.label||gr(void 0,te)}))}return Z.length===0?M:[...M,...Z].sort((H,te)=>H.label.localeCompare(te.label))},[M,R,l]),L=`${r??"context"}:${e}`,A=e==="swm"&&!!r&&b.loading,I=`${u} graph`,$=i??to(e),W=a===null&&!!i,q=a===null?void 0:a??e,oe=e==="vm"&&y.length>0||e==="swm"&&b.palette.length>0||_>3e3?s.jsxs(s.Fragment,{children:[_>3e3&&s.jsxs("div",{className:"v10-graph-legend",role:"status",children:[s.jsx("span",{children:D?`Showing all ${_.toLocaleString()} loaded nodes.`:"This large graph shows one connected view of up to 3,000 nodes."}),s.jsx("button",{onClick:()=>C(D?null:P),children:D?"Use smaller graph view":`Show all loaded nodes (${_.toLocaleString()})`})]}),e==="vm"&&y.length>0&&s.jsx(io,{anchors:y}),e==="swm"&&b.palette.length>0&&s.jsx(ro,{palette:b.palette,conflicts:b.conflicts.length})]}):null,ee=m.useMemo(()=>({name:`${L}:${h}`,palette:h}),[L,h]);return k.length===0&&T.length===0?s.jsx(Qt,{title:I,scopeLabel:$,tone:e,className:"v10-graph-view-fill",showScopeLabel:W,renderGraph:()=>s.jsx("div",{className:"v10-layer-empty-shell",children:s.jsx(je,{compact:!0,tone:Et(e),icon:Ie[e].icon,title:`No triples in ${u}`,description:"The graph will appear when this layer has connected triples."})})}):A?s.jsx(Qt,{title:I,scopeLabel:$,tone:"swm",className:"v10-graph-view-fill",showScopeLabel:W,renderGraph:()=>s.jsx("div",{className:"v10-layer-empty-shell",children:s.jsx(je,{compact:!0,tone:"swm",icon:Ie.swm.icon,title:"Loading Shared Working Memory attribution...",description:"Agent colors are being prepared before the graph renders."})})}):s.jsx(Qt,{title:I,scopeLabel:$,tone:e,className:"v10-graph-view-fill",overlay:oe,showScopeLabel:W,singletonItems:T,onSingletonClick:F=>n==null?void 0:n(q?{id:F,trustLayer:q}:{id:F}),renderGraph:F=>{var Z;return R.length>0?s.jsx(m.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Yn,{data:R,format:"triples",options:S,viewConfig:ee,style:{position:"absolute",inset:0,width:"100%",height:"100%"},onNodeClick:q?H=>n==null?void 0:n({...H,trustLayer:q}):n,initialFit:!0},`${L}:${F?"expanded":"inline"}:${R.length}:${(Z=S.focus)==null?void 0:Z.maxNodes}`)}):s.jsx("div",{className:"v10-graph-placeholder v10-graph-placeholder-centered",children:"Connected graph appears when this layer has linked entities."})}})}function ro({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 io({anchors:e}){var i;const t=m.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 ao({active:e,counts:t,onSwitch:n,onShare:r,onImport:i,onRefresh:a}){const[o,l]=m.useState(!1),c=m.useRef(null),d=g=>{l(!1),n(g)};return m.useEffect(()=>{if(!o)return;const g=p=>{var h;const u=p.target;u&&((h=c.current)!=null&&h.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 oo({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 lo(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(ze)),l=o.size>0;return a&&l&&o.has(ze(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(ze(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 co(e,t,n){if(Bn(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(ze)),a=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"";return a&&i.add(ze(a)),{id:"participants",value:i.size.toLocaleString(),label:"Agents with access",tooltip:"Includes the curator plus allowlisted participants reported by the node."}}function uo(e){const t=Bn(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 po({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?ze(r)===ze(o)?"curator":"not-curator":"unknown"}function ho(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(ze))}function mo({cg:e,memory:t,subGraphCount:n,subGraphFetchFailed:r=!1,participants:i,participantsStatus:a="ok",currentAgent:o,currentAgentStatus:l="ok",onSwitchLayer:c,onOpenPrimer:d}){var $,W,q;const{wm:g,swm:p,vm:u}=t.counts,h=g+p+u,v=lo(e,o??null,l,i,a),y=uo(e==null?void 0:e.accessPolicy),j=co(e,i,a),f=typeof(e==null?void 0:e.curator)=="string"?e.curator.trim():"",b=f?ze(f):"",x=Bn(e==null?void 0:e.accessPolicy)==="public",k=ho(o??null),E=Object.values(t.layerStatus??{}),w=E.filter(K=>K==="error").length,R=!t.loading&&E.length===3&&w===3,M=!t.loading&&w>0,_=t.loading?"Loading memory layers...":R||t.error?"Live memory counts are unavailable.":t.partial||M?"One or more layer counts are currently a lower bound.":"Canonical current-layer entity counts.",O=R?"Unavailable":h.toLocaleString(),{total:C}=Wn(t),P=!t.loading&&(t.partial||M),D=R?"Unavailable":t.loading&&C===0?"...":P?`${C.toLocaleString()}+`:C.toLocaleString(),S=R?"Live triple counts are unavailable.":P?"One or more layer triple counts are currently a lower bound.":"Canonical triple total across all layers.",T=n==null?r?"Unavailable":"...":n.toLocaleString(),L=n==null?r?"Sub-graph list is currently unavailable.":"Sub-graph count is loading.":"Topical partitions inside this Context Graph.",A=[{key:"wm",label:"Working Memory",desc:"Private staging area",count:g,status:(($=t.layerStatus)==null?void 0:$.wm)??"ok",color:"#64748b"},{key:"swm",label:"Shared Working Memory",desc:"Collaborative review",count:p,status:((W=t.layerStatus)==null?void 0:W.swm)??"ok",color:"#f59e0b"},{key:"vm",label:"Verifiable Memory",desc:"Published on-chain",count:u,status:((q=t.layerStatus)==null?void 0:q.vm)??"ok",color:"#22c55e"}],I=A.some(K=>K.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(hn,{className:"v10-po-stat-strip",items:[{id:"entities",value:O,label:"Entities",tooltip:_},{id:"triples",value:D,label:"Triples",tooltip:S},{id:"subgraphs",value:T,label:"Subgraphs",tooltip:L},j]})]}),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:!I&&h>0?A.map(K=>{const oe=K.count>0?K.count/h*100:0;return s.jsx("span",{className:`v10-po-pipeline-seg ${K.key}`,style:{width:`${oe}%`,background:K.color}},K.key)}):s.jsx("span",{className:"v10-po-pipeline-empty"})}),s.jsx("div",{className:"v10-po-pipeline-steps",children:A.map((K,oe)=>s.jsxs("button",{type:"button",className:`v10-po-pipeline-step ${K.key}`,onClick:()=>c==null?void 0:c(K.key),style:{"--po-layer-color":K.color},children:[s.jsx("span",{className:"v10-po-pipeline-step-index",children:oe+1}),s.jsxs("span",{className:"v10-po-pipeline-step-copy",children:[s.jsx("span",{className:"v10-po-pipeline-step-label",children:K.label}),s.jsx("span",{className:"v10-po-pipeline-step-desc",children:K.desc})]}),s.jsx("span",{className:"v10-po-pipeline-step-count",children:K.status==="error"?"Unavailable":`${K.count.toLocaleString()} ${He(K.key,K.count)}`})]},K.key))})]}),s.jsxs("div",{className:"v10-po-people","data-section":"participants",children:[s.jsx("div",{className:"v10-po-section-title",children:"Participant agents"}),(()=>{const K="did:dkg:agent:",oe=Z=>Z.toLowerCase().startsWith(K)?Z.slice(K.length):Z,ee=new Set,F=[];if(f&&a==="ok"){const Z=ze(f);ee.add(Z),F.push({display:oe(f),full:f,canonical:Z})}if(a==="ok")for(const Z of i){const H=ze(Z);ee.has(H)||(ee.add(H),F.push({display:oe(Z),full:Z,canonical:H}))}if(F.length===0){const Z=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:Z})}return s.jsx("div",{className:"v10-po-participants-list",children:F.map(({display:Z,full:H,canonical:te})=>{const xe=k.has(te),Te=!!b&&te===b,B=`${Z.slice(0,6)}…${Z.slice(-4)}`,se=[B];return xe&&se.push("you"),Te&&se.push("curator"),s.jsxs("span",{className:`v10-po-participant${xe?" is-self":""}${Te?" is-curator":""}`,title:H,"aria-label":se.join(" "),children:[s.jsx("span",{className:"v10-po-participant-name",children:B}),xe&&s.jsx("span",{className:"v10-po-participant-tag",children:"you"}),Te&&s.jsx("span",{className:"v10-po-participant-tag",children:"curator"})]},te)})})})()]})]})}function fo({contextGraphId:e,curatorStatus:t,onParticipantsChanged:n}){const[r,i]=m.useState([]),[a,o]=m.useState(null),[l,c]=m.useState("loading"),d=m.useRef(0),g=m.useCallback(()=>{if(t!=="curator"){i([]),c("idle");return}const h=++d.current;c("loading"),pr(e).then(v=>{d.current===h&&(i(v.requests.filter(y=>y.status==="pending")),c("idle"))}).catch(()=>{d.current===h&&(i([]),c("error"))})},[e,t]);if(m.useEffect(()=>(g(),()=>{d.current++}),[g]),Zi(m.useCallback(h=>{var v;h.type!=="join_request"&&h.type!=="join_approved"&&h.type!=="join_rejected"||((v=h.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 p=async h=>{o(h);try{await hr(e,h),i(v=>v.filter(y=>y.agentAddress!==h)),n==null||n()}catch{}finally{o(null)}},u=async h=>{o(h);try{await mr(e,h),i(v=>v.filter(y=>y.agentAddress!==h)),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(h=>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:h.name||`${h.agentAddress.slice(0,6)}…${h.agentAddress.slice(-4)}`}),s.jsxs("span",{className:"v10-po-join-addr",title:h.agentAddress,children:[h.agentAddress.slice(0,10),"…"]})]}),s.jsxs("div",{className:"v10-po-join-actions",children:[s.jsx("button",{className:"v10-po-join-btn approve",onClick:()=>p(h.agentAddress),disabled:a===h.agentAddress,children:a===h.agentAddress?"…":"✓ Approve"}),s.jsx("button",{className:"v10-po-join-btn reject",onClick:()=>u(h.agentAddress),disabled:a===h.agentAddress,"aria-label":"Reject join request",children:"✕"})]})]},h.agentAddress))})]})}function go({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 vo=(e,t)=>!!e&&!!t&&e.toLowerCase()===t.toLowerCase();function bo(e,t=0){const n=br(o=>o.trackedIds),r=n.join(","),{data:i,loading:a}=st(async()=>{if(n.length===0)return{wallets:[],ownerPublish:!1,resolved:!1};const o=await qi().catch(()=>null),l=(o==null?void 0:o.wallets)??[];let c=!1;try{const{contextGraphs:g}=await Gi(),p=(g??[]).find(h=>(h==null?void 0:h.id)===e),u=p==null?void 0:p.curator;if(u){const h=await Bi().catch(()=>null);c=!!(h!=null&&h.agentDid&&ze(u)===ze(h.agentDid))}}catch{c=!1}return{wallets:await Promise.all(l.map(async g=>{var k;const p=(k=o==null?void 0:o.balances)==null?void 0:k.find(E=>vo(E.address,g)),u=p==null,h=p!=null&&Number(p.eth)>0,v=p!=null&&Number(p.trac)>0;let y,j=!1,f=!1,b,x=!1;for(const E of n){const w=await ds(E,g,{extended:!0}).catch(()=>null);if(w===null){x=!0;continue}const R=ps(w);if(R.outcome==="inconclusive"){x=!0;continue}if(R.outcome!=="unregistered"){if(R.outcome==="covers"){y={accountId:E,discountBps:w.discountBps,untracked:!1};break}R.dead&&(j=!0,b||(b=E)),R.hasBudget||(f=!0)}}if(!y&&!x&&!j&&!f){const E=await Wi(g).catch(()=>{});if(E===void 0)x=!0;else if(E.accountId!=null&&!n.includes(E.accountId)){const w=E.accountId,R=await ds(w,g,{extended:!0}).catch(()=>null);if(R===null)x=!0;else{const M=ps(R);M.outcome==="covers"?y={accountId:w,discountBps:R.discountBps,untracked:!0}:M.outcome==="uncovered"?(M.dead&&(j=!0,b||(b=w)),M.hasBudget||(f=!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:h,hasTrac:v,sawExpired:j,sawInsolvent:f}})),ownerPublish:c,resolved:l.length>0}},[r,e],t);return m.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(f=>f.covered),g=o.filter(f=>!f.covered),p=g.filter(f=>!f.inconclusive&&!f.balanceUnknown),u=g.filter(f=>f.inconclusive||f.balanceUnknown),h={approved:g.length===0,gasFunded:o.every(f=>f.gasFunded),notExpired:!o.some(f=>f.sawExpired),solvent:!o.some(f=>f.sawInsolvent)};let v;const y=[];if(g.length===0)d.some(f=>f.gasFunded||f.balanceUnknown)?v="eligible":(v="fallthrough-no-funds",y.push("every approved signing wallet is out of gas"));else if(p.length===0&&u.length>0)v="unknown";else{const f=o.some(b=>(b.covered||b.hasTrac)&&b.gasFunded);!f&&u.length>0?v="unknown":(v=f?"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"),h.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 j=d.reduce((f,b)=>(b.discountBps??-1)>((f==null?void 0:f.discountBps)??-1)?b:f,void 0);return{verdict:v,loading:a,accountId:j==null?void 0:j.accountId,discountBps:j==null?void 0:j.discountBps,accountUntracked:j==null?void 0:j.coverUntracked,ownerPublish:l,anyGasFunded:o.some(f=>f.gasFunded||f.balanceUnknown),reasons:y,conditions:h,wallets:o}},[i,a,n.length])}function yo(e){return e.verdict==="fallthrough-no-funds"&&!(e.ownerPublish&&e.anyGasFunded)}function xo(e){const t=br(o=>o.trackedIds),n=bo(e,3e4),r=yo(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 jo({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(Ra,{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 wo({entities:e}){const t=et(),n=m.useMemo(()=>{const r=new Map;for(const i of e){const{icon:a,type:o}=pn(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(hn,{compact:!0,items:n.map(([r,{icon:i,count:a}])=>({id:r,label:`${i} ${r}`,value:a}))})})}function ko({entities:e,entityCount:t,triples:n,layer:r}){const i=m.useMemo(()=>e.filter(l=>l.properties.has("http://dkg.io/ontology/sourceContentType")).length,[e]),a=m.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(hn,{compact:!0,layer:r,items:[{id:"entities",label:He(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]=m.useState(!1),[i,a]=m.useState(null),[o,l]=m.useState(null),c=m.useCallback(async(d,g)=>{r(!0),l(null),a(null);try{const p=await d();a(p),e==null||e({ok:!0,text:p}),t==null||t()}catch(p){const u=g(p);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 No({count:e,contextGraphId:t,onComplete:n,onResult:r}){const{busy:i,result:a,error:o,run:l}=Er(r,n),c=m.useCallback(()=>{let g=null;l(async()=>{const p=await Jn(t,"wm",{includeCounts:!1});let u=0;for(const v of p)g=v.name,(await Xt(t,v.name,v.subGraph?{subGraphName:v.subGraph}:{})).promotedCount===0&&(u+=1);const h=p.length-u;if(h>0){const v=u>0?` (${u} already shared or still committing)`:"";return`Shared ${h} complete Knowledge Asset${h!==1?"s":""} to Shared Memory${v}`}return"No Knowledge Assets were newly shared — all were already in Shared Memory or still committing."},p=>{const u=en(g??"an assertion",p);return u?u.message:(p==null?void 0:p.message)??"Action failed"})},[t,l]);if(e===0)return null;const d="#f59e0b";return s.jsx(Ar,{title:"Share complete Knowledge Assets",footnote:"Shares each complete owning Knowledge Asset atomically to Shared Working Memory.",context:s.jsx(s.Fragment,{children:"Shares all eligible complete Working Memory Knowledge Assets in this context graph, including assets outside the loaded preview."}),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 So({count:e,contextGraphId:t,onComplete:n,onResult:r}){const[i,a]=m.useState(null),{busy:o,result:l,error:c,run:d}=Er(r,n),g=xo(t),p=m.useId(),u=m.useId(),h=[g.chipVisible?p:null,g.blocked?u:null].filter(Boolean).join(" ")||void 0,v=m.useCallback(()=>{g.blocked||d(async()=>{a(null);const y=await Jn(t,"swm",{includeCounts:!1}),j=await xr(t,y),f=jr(j),b=f?` — ⚠ ${f}`:"";if(j.published>0){const x=j.failures.length?` (${j.failures.length} assertion${j.failures.length===1?"":"s"} could not be published)`:"",k=j.partial>0?` — ⚠ ${j.partial}: ${tn(j.partialError)}`:"";return a(j.convictionCostCovered??null),`Published ${j.published} knowledge asset${j.published!==1?"s":""} to Verifiable Memory${x}${k}${b}`}if(y.length===0)return"Nothing to publish — promote assertions to Shared Memory first.";if(f&&j.failures.length===0)return`⚠ ${f}`;throw new Error(`${j.failures[0]?`${j.failures[0].name}: ${j.failures[0].error}`:"Publish failed"}${b}`)},y=>(y==null?void 0:y.message)??"Action failed")},[t,d,g.blocked]);return e===0?null:s.jsx(Ar,{title:"Publish",footnote:"Publishes all eligible complete Shared Working Memory Knowledge Assets in this context graph on-chain.",context:s.jsx(s.Fragment,{children:"Publishes all eligible complete Shared Working Memory Knowledge Assets, including assets outside the loaded preview. On-chain publishing incurs a cost."}),result:l,error:c,extras:s.jsxs(s.Fragment,{children:[s.jsx(Vi,{convictionCostCovered:i}),g.chipVisible&&s.jsx(jo,{...g.eligibility,id:p}),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":h,onClick:v,children:o?"...":"◉ Publish to Verifiable Memory"})})}function Co({layer:e,entities:t,entityCount:n,actionEntityCount:r=n,tripleCount:i,contextGraphId:a,onComplete:o}){const[l,c]=m.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(je,{compact:!0,tone:Et(e),icon:Ie[e].icon,title:`No ${He(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(ko,{entities:t,entityCount:n,triples:i,layer:e}),s.jsx(wo,{entities:t})]}),(e==="wm"||e==="swm")&&a&&r>0&&s.jsx("div",{className:"v10-layer-widgets-strip-action",children:e==="wm"?s.jsx(No,{count:r,contextGraphId:a,onComplete:o,onResult:c}):s.jsx(So,{count:r,contextGraphId:a,onComplete:o,onResult:c})})]})}function $o({contextGraphId:e,layer:t,includeQueryCatalog:n=!1,onComplete:r,scrollKey:i}){const a=JSON.stringify([e,t,n]),[o,l]=m.useState({scope:a,cursors:[void 0],index:0}),c=o.scope===a?o.cursors:[void 0],d=o.scope===a?o.index:0,g=c[d],{data:p,loading:u,error:h,refresh:v}=st(()=>Na(e,t,{includeQueryCatalog:n,cursor:g,includeCounts:!1}),[e,t,n,g],0,{scope:JSON.stringify([a,g]),retention:"scope"}),y=(p==null?void 0:p.items)??[],j=JSON.stringify([a,y.map(L=>L.graphUri)]),b=st(()=>t==="wm"?Sa(e,y):Promise.resolve({}),[j,p],0,{scope:j,retention:"scope"}).data??{},x=m.useCallback(()=>{Ki(e),v()},[e,v]);un(e,v,{layers:[t]});const[k,E]=m.useState(null),[w,R]=m.useState(null),[M,_]=m.useState(null),O=m.useCallback(async L=>{E(L.graphUri),R(null),_(null);try{if(t==="wm"){const A=await Xt(e,L.name,L.subGraph?{subGraphName:L.subGraph}:{}),I=wr(L.name,A);R(I.message)}else{const A=await kr(e,L.name,L.subGraph?{subGraphName:L.subGraph}:{});R(A.contextGraphError?`Published ${L.name} on-chain — ⚠ ${tn(A.contextGraphError)}`:`Published ${L.name} to Verifiable Memory`)}x(),r()}catch(A){const I=en(L.name,A);_(I?I.message:(A==null?void 0:A.message)??"Action failed")}finally{E(null)}},[e,t,x,r]),C=m.useCallback(async()=>{E("__all__"),R(null),_(null);let L=null;try{const A=await Jn(e,t,{includeCounts:!1});if(A.length===0){R(t==="wm"?"No user Knowledge Assets are ready to share.":"No user Knowledge Assets are ready to publish.");return}if(t==="wm"){let I=0;for(const W of A)L=W.name,(await Xt(e,W.name,W.subGraph?{subGraphName:W.subGraph}:{})).promotedCount===0&&(I+=1);const $=A.length-I;if($>0){const W=I>0?` (${I} already shared or still committing)`:"";R(`Shared ${$} complete Knowledge Asset${$!==1?"s":""}${W}`)}else R("No Knowledge Assets were newly shared — all were already in Shared Memory or still committing.")}else{const I=await xr(e,A),$=jr(I),W=$?` — ⚠ ${$}`:"";if(I.published>0){const q=I.failures.length?` (${I.failures.length} could not be published)`:"",K=I.partial>0?` — ⚠ ${I.partial}: ${tn(I.partialError)}`:"";R(`Published ${I.published} knowledge asset${I.published!==1?"s":""} to Verifiable Memory${q}${K}${W}`)}else if($&&I.failures.length===0)R(`⚠ ${$}`);else throw new Error(`${I.failures[0]?`${I.failures[0].name}: ${I.failures[0].error}`:"Publish failed"}${W}`)}x(),r()}catch(A){const I=en(L??"selected assertion",A);_(I?I.message:(A==null?void 0:A.message)??"Action failed")}finally{E(null)}},[e,t,x,r]),P={flex:1,overflow:"auto"};if(u)return s.jsx("div",{className:"v10-layer-empty-shell",style:P,"data-cg-scroll-key":i,children:s.jsx(je,{compact:!0,tone:Et(t),icon:Ie[t].icon,title:"Loading assertions..."})});if(h)return s.jsxs("div",{role:"alert",style:P,children:["Could not load assertions: ",h," ",s.jsx("button",{onClick:x,children:"Retry"})]});if(!y.length&&!(p!=null&&p.nextCursor)&&d===0)return s.jsx("div",{className:"v10-layer-empty-shell",style:P,"data-cg-scroll-key":i,children:s.jsx(je,{tone:Et(t),icon:Ie[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 D=t==="wm"?"Share Complete KA → Shared":"Publish to VM",S=t==="wm"?"Share all complete KAs → Shared":"Publish all to Verifiable Memory",T=y.filter(L=>L.subGraph!=="meta"||!L.name.startsWith("query-catalog-")).length;return s.jsxs("div",{style:P,"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:["Page ",d+1," · ",y.length," assertion",y.length!==1?"s":""]}),T>0&&s.jsx("button",{className:`v10-layer-expand-footer-btn ${t==="wm"?"promote":"publish"}`,title:"Applies to all assertions in this layer across every page. Query catalog assertions are excluded.",disabled:k!==null,onClick:C,style:{opacity:k==="__all__"?.5:1},children:k==="__all__"?"...":S})]}),w&&s.jsxs("div",{"data-testid":t==="wm"?"assertion-promote-result":"assertion-publish-result",style:{padding:"6px 16px",fontSize:11,color:"var(--text-success)"},children:["✓ ",w]}),M&&s.jsxs("div",{"data-testid":t==="wm"?"assertion-promote-result":"assertion-publish-result",style:{padding:"6px 16px",fontSize:11,color:"var(--text-danger)"},children:["✕ ",M]}),y.map(L=>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:L.name}),L.reservedUal&&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:L.reservedUal,children:L.reservedUal}),s.jsxs("div",{className:"v10-item-meta-row",children:[(L.tripleCount??b[L.graphUri])!=null&&s.jsxs("span",{className:"v10-item-count",children:[L.tripleCount??b[L.graphUri]," triples"]}),L.subGraph&&s.jsxs("span",{className:"v10-item-count v10-item-subgraph",title:`In sub-graph: ${L.subGraph}`,children:["› ",Ca(L.subGraph,18)]})]})]}),s.jsx("button",{"data-testid":"assertion-row-action",className:`v10-layer-expand-footer-btn ${t==="wm"?"promote":"publish"}`,disabled:k!==null,onClick:A=>{A.stopPropagation(),O(L)},style:{opacity:k===L.graphUri?.5:1,flexShrink:0},children:k===L.graphUri?"...":D})]},L.graphUri)),s.jsxs("nav",{"aria-label":"Assertion pages",style:{display:"flex",gap:12,padding:16},children:[s.jsx("button",{disabled:d===0||k!==null,onClick:()=>l({scope:a,cursors:c,index:d-1}),children:"Previous assertions"}),s.jsx("button",{disabled:!(p!=null&&p.nextCursor)||k!==null,onClick:()=>{l({scope:a,cursors:[...c.slice(0,d+1),p.nextCursor],index:d+1})},children:"Next assertions"}),s.jsx("button",{disabled:k!==null,onClick:x,children:"Refresh assertions"})]})]})}const _o={working:{layerKey:"wm",icon:"◇",label:"Working"},shared:{layerKey:"swm",icon:"◈",label:"Shared"},verified:{layerKey:"vm",icon:"◉",label:"Verifiable"}},Eo=new Set(["http://dkg.io/ontology/profile/QueryCatalog","http://dkg.io/ontology/profile/SavedQuery"]);function Ao(e){return e.types.some(t=>Eo.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(),p=Ot(),u=He(t,e.length).toLowerCase(),h=m.useMemo(()=>{if(a)return e;const j=[...e];return j.sort((f,b)=>{const x=f.tripleCount??0;return(b.tripleCount??0)-x}),j},[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(je,{compact:!0,tone:Et(t),icon:n,title:`No ${He(t,2).toLowerCase()} yet`,description:`This view will fill when matching ${He(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:[h.length," ",u]}),s.jsx("span",{className:"v10-entity-list-hint",children:y}),l&&s.jsx("span",{className:"v10-entity-list-extra",children:l})]}),h.map(j=>{const{icon:f,type:b}=pn(j,g),x=j.tripleCount??0,k=Vn(j),E=k?p==null?void 0:p.get(k):null,w=c?Vt(j,c):null;return s.jsxs("div",{className:"v10-entity-card",onClick:R=>{R.stopPropagation(),r(j.uri)},children:[s.jsx("span",{className:"v10-entity-card-icon",children:f}),s.jsxs("div",{className:"v10-entity-card-main",children:[s.jsx("div",{className:"v10-entity-card-title",children:j.label}),s.jsxs("div",{className:"v10-entity-card-meta",children:[(E||k)&&s.jsx(mt,{agent:E??void 0,fallbackUri:k??void 0,size:"sm",onOpenAgent:i}),b&&b!=="Entity"&&s.jsxs("span",{className:"v10-entity-type-pill",children:[f," ",b]}),w!=null&&s.jsx("span",{className:"v10-entity-card-timestamp",title:new Date(w).toLocaleString(),children:Ji(w)}),s.jsxs("span",{className:"v10-entity-card-triples",children:[x," triples"]})]})]}),d?(()=>{const R=_o[j.trustLevel];return s.jsxs("span",{className:`v10-trust-badge ${R.layerKey}`,title:`${R.label} Memory`,children:[R.icon," ",R.label]})})():s.jsxs("span",{className:`v10-trust-badge ${t}`,children:[n," ",v]})]},j.uri)})]})}function Ro({layer:e,entities:t,tripleCount:n,layerTriples:r,contextGraphId:i,memory:a,activeTab:o,onTabChange:l,onSelectEntity:c,onNodeClick:d,footer:g,swmAttribution:p,showQueryCatalog:u=!1,onShowQueryCatalogChange:h}){var R;const v=Ie[e],y=He(e,2),j=m.useMemo(()=>t.filter(M=>!Ao(M)).length,[t]),f=((R=a.layerStatus)==null?void 0:R.vm)??(a.loading?"loading":a.error?"error":"ok"),b=e==="vm"&&f==="loading"&&t.length===0,x=e==="vm"&&f==="error"&&t.length===0,k=e==="vm"&&f==="ok"&&t.length===0,E=a.counts[e],w=M=>_=>{_.stopPropagation(),l(M)};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:w("items"),children:y}),e!=="vm"&&s.jsx("button",{className:`v10-layer-expand-tab ${o==="assertions"?"active":""}`,onClick:w("assertions"),children:"Assertions"}),s.jsx("button",{className:`v10-layer-expand-tab ${o==="graph"?"active":""}`,onClick:w("graph"),children:"Graph"}),s.jsx("button",{className:`v10-layer-expand-tab ${o==="docs"?"active":""}`,onClick:w("docs"),children:"Documents"}),e!=="vm"&&h&&s.jsxs("label",{className:"v10-query-catalog-visibility",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:M=>h(M.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(To,{entities:t,tripleCount:n,contextGraphId:i}),b?s.jsx("div",{className:"v10-layer-widgets-strip empty",children:s.jsx(je,{compact:!0,tone:"vm",icon:Ie.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(je,{compact:!0,tone:"vm",icon:Ie.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(Co,{layer:e,entities:t,entityCount:E,actionEntityCount:j,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($o,{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"?p: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 To({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(je,{compact:!0,className:"v10-vm-empty-state",tone:"vm",icon:Ie.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(hn,{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 Oo({layer:e,memory:t,onNodeClick:n,onSelectEntity:r,contextGraphId:i,activeTab:a,onTabChange:o,swmAttribution:l,showQueryCatalog:c=!1,onShowQueryCatalogChange:d}){const g=Ie[e],p=m.useMemo(()=>t.entityList.filter(h=>h.trustLevel===g.trustLevel),[t.entityList,g.trustLevel]),u=Qi(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(Ro,{layer:e,entities:p,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=Kn(o=>o.openTab),i=m.useMemo(()=>e.filter(o=>o.properties.has(wn)),[e]),a=o=>{var u,h,v;const l=(u=o.connections.find(y=>y.predicate===hs))==null?void 0:u.targetUri,c=(h=o.connections.find(y=>y.predicate===ms))==null?void 0:h.targetUri,d=((v=o.properties.get(wn))==null?void 0:v[0])??"",{ref:g,contentType:p}=Yi(l,c,d);r({id:Hi(t??"",g??o.uri,p),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(je,{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 p,u,h,v;const l=((p=o.properties.get(wn))==null?void 0:p[0])??"",c=(u=o.connections.find(y=>y.predicate===hs||y.predicate===ms))==null?void 0:u.targetUri,d=c?e.find(y=>y.uri===c):void 0,g=((h=d==null?void 0:d.properties.get(fs))==null?void 0:h[0])??((v=o.properties.get(fs))==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
+ ${zn(e)}
39
+ }
40
+ LIMIT 1000`}const rn="User-created SPARQL saved in this node profile for this Context Graph.";function ws(e){return JSON.stringify(e)}function zn(e){const t=`did:dkg:context-graph:${e}`,n=`${t}/`;return`FILTER(
41
+ (
42
+ STR(?g) = ${ws(t)} ||
43
+ STRSTARTS(STR(?g), ${ws(n)})
44
+ ) &&
45
+ !CONTAINS(STR(?g), "/_private")
46
+ )`}function Po(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
+ ${zn(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
+ ${zn(e)}
55
+ }
56
+ GROUP BY ?type
57
+ ORDER BY DESC(?entities)
58
+ LIMIT 100`,resultColumn:"type",rank:3})]}}function Io(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 zo(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 ks(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 Lo(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&"value"in e?String(e.value):String(e)}function Mo(e){return e?e.length<=140?e:`${e.slice(0,110)}...${e.slice(-24)}`:"—"}function mn(e){return e.subGraph===Xe&&e.slug==="whole-context-graph"}function Fo(e){return e.subGraph===Xe?"context":"subgraph"}function Uo(e,t,n){return mn(e)?"Built-in presets":e.subGraph===Xe&&e.slug===nn?sn:t==="context"?e.name:`${n??e.subGraph}: ${e.name}`}function Do(e){return mn(e)?"UI-provided SPARQL for common Context Graph checks.":e.subGraph===Xe&&e.slug===nn?rn:e.description??""}function Zo(e,t){return mn(e)?"Preset":t==="context"?"Saved":"Subgraph"}function qo(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 Go({contextGraphId:e}){var Te;const t=et(),n=m.useMemo(()=>Or(e),[e]),[r,i]=m.useState({kind:"ad-hoc",draft:n}),[a,o]=m.useState({sparql:n}),[l,c]=m.useState([]),[d,g]=m.useState(!1),[p,u]=m.useState(""),[h,v]=m.useState(""),[y,j]=m.useState(!1),[f,b]=m.useState(null),[x,k]=m.useState(null),[E,w]=m.useState(null),R=m.useMemo(()=>Po(e),[e]),M=m.useMemo(()=>ks([R,...l,...(t==null?void 0:t.queryCatalogs)??[]]),[R,l,t==null?void 0:t.queryCatalogs]),_=m.useMemo(()=>t!=null&&t.loading||t!=null&&t.error?ks([R,...l]):M,[R,l,t==null?void 0:t.error,t==null?void 0:t.loading,M]),O=m.useMemo(()=>r.kind==="catalog"?r.query:void 0,[r]),C=r.kind==="catalog"?r.key:null,P=r.draft,D=r.kind==="catalog"?r.values:{};m.useEffect(()=>{i({kind:"ad-hoc",draft:n}),o({sparql:n}),c([]),g(!1),u(""),v(""),b(null),k(null),w(null)},[n]);const{data:S,loading:T,error:L,refresh:A}=st(()=>Nr(a.sparql,{contextGraphId:e,view:a.view,subGraphName:a.subGraphName,...a.view==="working-memory"?{includeContextGraphPartitions:!0}:{}},{timeoutMs:null,maxResponseBytes:null}),[a.sparql,a.subGraphName,a.view,e],0),I=m.useMemo(()=>{if(r.kind!=="catalog")return!0;if(a.sourceKey!==r.key)return!1;try{const B=kt(r.query,r.values);return B.sparql===a.sparql&&B.view===a.view&&B.subGraphName===a.subGraphName}catch{return!1}},[a,r]),$=I?S==null?void 0:S.result:void 0,W=$==null?void 0:$.type,q=m.useMemo(()=>W==="quads"?$.quads:W==="bindings"?$.bindings:[],[$,W]),K=W==="boolean"?$.value:void 0,oe=m.useMemo(()=>M.some(B=>!mn(B)&&B.queries.length>0),[M]),ee=m.useMemo(()=>{const B=[];for(const se of q)for(const ie of Object.keys(se))B.includes(ie)||B.push(ie);return B},[q]),F=m.useCallback(()=>{const B=r.draft.trim();if(!B)return;let se;if(r.kind==="catalog"&&B===r.query.sparql.trim())try{se={...kt(r.query,r.values),sourceKey:r.key},w(null)}catch(ie){w((ie==null?void 0:ie.message)??String(ie));return}else se={sparql:B},r.kind==="catalog"&&i({kind:"ad-hoc",draft:B}),w(null);if(k(null),b(null),se.sparql===a.sparql&&se.view===a.view&&se.subGraphName===a.subGraphName){o(se),A();return}o(se)},[a,A,r]),Z=m.useCallback(()=>{if(i({kind:"ad-hoc",draft:n}),k(null),b(null),w(null),a.sparql===n&&a.view===void 0&&a.subGraphName===void 0){A();return}o({sparql:n})},[a,n,A]),H=m.useCallback((B,se)=>{const ie=se.sparql.trim();if(!ie)return;k(null),b(null),w(null);const Ce=se.parameters??[],fe=Object.fromEntries(Ce.filter(_e=>_e.defaultValue!==void 0).map(_e=>[_e.name,String(_e.defaultValue)]));if(i({kind:"catalog",key:B,query:se,values:fe,draft:ie}),Ce.length>0)return;const ge={...kt(se,fe),sourceKey:B};if(a.sparql===ge.sparql&&a.view===ge.view&&a.subGraphName===ge.subGraphName){o(ge),A();return}o(ge)},[a,A]),te=m.useCallback(()=>{const B=P.trim().split(`
59
+ `).find(se=>se.trim());u(B?B.replace(/\s+/g," ").slice(0,60):""),v(""),b(null),k(null),g(!0)},[P]),xe=m.useCallback(async B=>{B.preventDefault();const se=p.trim(),ie=h.trim(),Ce=P.trim();if(!se){b("Name is required.");return}if(!Ce){b("Query is empty.");return}j(!0),b(null),k(null);try{const fe=O&&O.sparql.trim()===Ce?O:void 0,{query:ge,quads:_e}=Io(e,se,ie,Ce,(fe==null?void 0:fe.parameters)??[],fe==null?void 0:fe.view,(fe==null?void 0:fe.subGraph)??Xe);await Xi(e,_e),c(de=>zo(de,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 de=kt(ge,Ze);o(Oe=>Oe.sparql===de.sparql&&Oe.view===de.view&&Oe.subGraphName===de.subGraphName?{...Oe,sourceKey:be}:Oe)}catch{}u(""),v(""),g(!1),k("Saved to catalogue.")}catch(fe){b((fe==null?void 0:fe.message)??"Failed to save query.")}finally{j(!1)}},[e,P,h,p,O,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(je,{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(je,{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(B=>{const se=Fo(B),ie=se==="context"||t==null?void 0:t.forSubGraph(B.subGraph),Ce=(ie==null?void 0:ie.color)??"#38bdf8",fe=Uo(B,se,ie==null?void 0:ie.displayName),ge=Do(B),_e=Zo(B,se);return s.jsxs("div",{className:"v10-cg-query-catalog-group",style:{"--sg-color":Ce},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:_e}),s.jsx("h4",{children:fe})]}),ge&&s.jsx("p",{children:ge})]})}),s.jsx("div",{className:"v10-cg-query-list",children:B.queries.map(be=>{const Ze=`${be.subGraph}|${be.catalogSlug}|${be.slug}`,de=C===Ze,Oe=be.description?`${be.name}. ${be.description}`:be.name;return s.jsxs("button",{type:"button",className:`v10-cg-query-chip${de?" active":""}`,title:Oe,"aria-label":`Load query: ${Oe}`,onClick:()=>H(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)})})]},`${B.subGraph}|${B.slug}`)})}),!(t!=null&&t.loading)&&!(t!=null&&t.error)&&M.length>0&&!oe&&s.jsx(je,{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:[O&&(((Te=O.parameters)==null?void 0:Te.length)??0)>0&&s.jsx("div",{className:"v10-cg-query-parameters","aria-label":"Query parameters",children:(O.parameters??[]).map(B=>s.jsxs("label",{className:"v10-cg-query-parameter",children:[s.jsx("span",{children:B.label??B.name}),B.type==="boolean"?s.jsxs("select",{className:"v10-form-input","aria-label":B.label??B.name,value:D[B.name]??"",onChange:se=>i(ie=>ie.kind==="catalog"?{...ie,values:{...ie.values,[B.name]:se.target.value}}:ie),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":B.label??B.name,type:B.type==="integer"||B.type==="number"?"number":"text",step:B.type==="integer"?"1":B.type==="number"?"any":void 0,required:fa(B),value:D[B.name]??"",placeholder:B.description,onChange:se=>i(ie=>ie.kind==="catalog"?{...ie,values:{...ie.values,[B.name]:se.target.value}}:ie)}),B.description&&s.jsx("small",{children:B.description})]},B.name))}),E&&s.jsx("span",{className:"v10-cg-query-error-detail",children:E}),s.jsx("textarea",{className:"v10-cg-query-textarea","aria-label":"SPARQL editor",value:P,onChange:B=>{i({kind:"ad-hoc",draft:B.target.value}),w(null)},spellCheck:!1}),s.jsxs("div",{className:"v10-cg-query-actions",children:[s.jsx("button",{className:"v10-mlv-run-btn",type:"button",onClick:F,children:"Run"}),s.jsx("button",{className:"v10-mlv-save-btn",type:"button",onClick:te,children:"Save"}),s.jsx("button",{className:"v10-mlv-clear-btn",type:"button",onClick:Z,children:"Reset"})]})]}),d&&s.jsxs("form",{className:"v10-cg-query-save-panel",onSubmit:xe,children:[s.jsxs("label",{className:"v10-cg-query-save-field",children:[s.jsx("span",{children:"Name"}),s.jsx("input",{type:"text",value:p,onChange:B=>u(B.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:h,onChange:B=>v(B.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}),f&&s.jsx("p",{className:"v10-mlv-status",style:{color:"var(--text-danger)"},children:f}),s.jsxs("div",{className:"v10-cg-query-results",children:[!I&&s.jsx(je,{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."}),I&&T&&s.jsx(je,{compact:!0,tone:"query",icon:"?",title:"Loading query results..."}),I&&L&&s.jsx(je,{compact:!0,tone:"danger",icon:"!",title:"Query could not run.",description:qo(L)}),I&&!T&&!L&&K===void 0&&q.length===0&&s.jsx(je,{compact:!0,tone:"query",icon:"?",title:"No results for this query.",description:"Adjust the query or run a saved query against this Context Graph."}),I&&!T&&!L&&K!==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(K)})]}),I&&!T&&!L&&K===void 0&&q.length>0&&s.jsxs("div",{className:"v10-mlv-table-wrap",children:[s.jsxs("div",{className:"v10-mlv-result-count",children:[q.length," ",W==="quads"?`quad${q.length===1?"":"s"}`:`result${q.length===1?"":"s"}`]}),s.jsxs("table",{className:"v10-mlv-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:ee.map(B=>s.jsx("th",{children:B},B))})}),s.jsx("tbody",{children:q.map((B,se)=>s.jsx("tr",{children:ee.map(ie=>{const Ce=Lo(B[ie]);return s.jsx("td",{className:"v10-mlv-cell",title:Ce,children:Mo(Ce)},ie)})},se))})]})]})]})]})]})}const Bo=({contextGraphId:e,entityUri:t,enabled:n})=>{const r=Ot(),i=$a(e,t,n),a=_a(e,t,n),{data:o}=st(ea,[],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?Wo(i.publishedAt):null,p=i.publisherPeerId&&r?vs(i.publisherPeerId,r.agents):null,u=p?(r==null?void 0:r.get(p))??null:null,h=i.owner&&r?vs(i.owner,r.agents):null,v=h?(r==null?void 0:r.get(h))??null:null,y=j=>{var f;(f=navigator.clipboard)==null||f.writeText(j).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:[ut(a.txHash,10,8)," ↗"]}):s.jsx("span",{className:"v10-vm-identity-val mono",title:a.txHash,children:ut(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:ut(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(mt,{agent:v,size:"sm"}),v.walletAddress&&s.jsx("span",{className:"v10-vm-identity-wallet mono",title:v.walletAddress,children:ut(v.walletAddress,6,4)})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"v10-vm-identity-val mono",title:i.owner??"",children:ut(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(mt,{agent:u,size:"sm"}):s.jsx("span",{className:"v10-vm-identity-val mono",title:i.publisherPeerId??"",children:ut(i.publisherPeerId,8,6)})]})]})};function Wo(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 z(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 At extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Pr={};function rt(e){return Pr}function Ir(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function Vo(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 Xn(e){return e==null}function es(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ko(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 ts(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jt(e){return JSON.stringify(e)}const Lr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ln(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 Mn(e){if(Ln(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Ln(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const Jo=new Set(["string","number","symbol"]);function fn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function Y(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Yo(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Ho={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 Xo(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 at(e,{...e._zod.def,shape:n,checks:[]})}function el(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 at(e,{...e._zod.def,shape:n,checks:[]})}function tl(e,t){if(!Mn(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 ts(this,"shape",r),r},checks:[]};return at(e,n)}function nl(e,t){return at(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ts(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function sl(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 at(t,{...t._zod.def,shape:i,checks:[]})}function rl(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 at(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 ns(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 it(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 ss(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Rt(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const 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,Vo,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fr=z("$ZodError",Mr),Ur=z("$ZodError",Mr,{Parent:Error});function il(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 al(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 ol=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 At;if(o.issues.length){const l=new((i==null?void 0:i.Err)??e)(o.issues.map(c=>it(c,a,rt())));throw Lr(l,i==null?void 0:i.callee),l}return o.value},ll=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=>it(c,a,rt())));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 At;return a.issues.length?{success:!1,error:new(e??Fr)(a.issues.map(o=>it(o,i,rt())))}:{success:!0,data:a.value}},cl=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=>it(o,i,rt())))}:{success:!0,data:a.value}},ul=Zr(Ur),dl=/^[cC][^\s-]{8,}$/,pl=/^[0-9a-z]+$/,hl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ml=/^[0-9a-vA-V]{20}$/,fl=/^[A-Za-z0-9]{27}$/,gl=/^[a-zA-Z0-9_-]{21}$/,vl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bl=/^([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})$/,Ns=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)$/,yl=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,xl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jl(){return new RegExp(xl,"u")}const wl=/^(?:(?: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])$/,kl=/^(([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})$/,Nl=/^((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])$/,Sl=/^(([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])$/,Cl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qr=/^[A-Za-z0-9_-]*$/,$l=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,_l=/^\+(?:[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])))",El=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 Al(e){return new RegExp(`^${Br(e)}$`)}function Rl(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 Tl=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}$`)},Ol=/^\d+$/,Pl=/^-?\d+(?:\.\d+)?/i,Il=/^[^A-Z]*$/,zl=/^[^a-z]*$/,Re=z("$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=z("$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})}}),Kr=z("$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})}}),Ll=z("$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):Ko(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})}}),Ml=z("$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]=Ho[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=Ol)}),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})}}),Fl=z("$ZodCheckMaxLength",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Xn(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=ss(i);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ul=z("$ZodCheckMinLength",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Xn(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=ss(i);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Dl=z("$ZodCheckLengthEquals",(e,t)=>{var n;Re.init(e,t),(n=e._zod.def).when??(n.when=r=>{const i=r.value;return!Xn(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=ss(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})}}),gn=z("$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=z("$ZodCheckRegex",(e,t)=>{gn.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})}}),ql=z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Il),gn.init(e,t)}),Gl=z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=zl),gn.init(e,t)}),Bl=z("$ZodCheckIncludes",(e,t)=>{Re.init(e,t);const n=fn(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})}}),Wl=z("$ZodCheckStartsWith",(e,t)=>{Re.init(e,t);const n=new RegExp(`^${fn(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})}}),Vl=z("$ZodCheckEndsWith",(e,t)=>{Re.init(e,t);const n=new RegExp(`.*${fn(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})}}),Kl=z("$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 Jl={major:4,minor:0,patch:0},we=z("$ZodType",(e,t)=>{var i;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jl;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 p of l){if(p._zod.def.when){if(!p._zod.def.when(o))continue}else if(d)continue;const u=o.issues.length,h=p._zod.check(o);if(h instanceof Promise&&(c==null?void 0:c.async)===!1)throw new At;if(g||h instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await h,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 At;return c.then(d=>a(d,r,l))}return a(c,r,l)}}e["~standard"]={validate:a=>{var o;try{const l=cl(e,a);return l.success?{value:l.data}:{issues:(o=l.error)==null?void 0:o.issues}}catch{return ul(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}}),rs=z("$ZodString",(e,t)=>{var n;we.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??Tl(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=z("$ZodStringFormat",(e,t)=>{gn.init(e,t),rs.init(e,t)}),Yl=z("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=bl),me.init(e,t)}),Hl=z("$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=Ns(r))}else t.pattern??(t.pattern=Ns());me.init(e,t)}),Xl=z("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yl),me.init(e,t)}),ec=z("$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:$l.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})}}}),tc=z("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jl()),me.init(e,t)}),nc=z("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=gl),me.init(e,t)}),sc=z("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=dl),me.init(e,t)}),rc=z("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=pl),me.init(e,t)}),ic=z("$ZodULID",(e,t)=>{t.pattern??(t.pattern=hl),me.init(e,t)}),ac=z("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ml),me.init(e,t)}),oc=z("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=fl),me.init(e,t)}),lc=z("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Rl(t)),me.init(e,t)}),cc=z("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=El),me.init(e,t)}),uc=z("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Al(t)),me.init(e,t)}),dc=z("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=vl),me.init(e,t)}),pc=z("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=wl),me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),hc=z("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=kl),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})}}}),mc=z("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Nl),me.init(e,t)}),fc=z("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Sl),me.init(e,t),e._zod.check=n=>{const[r,i]=n.value.split("/");try{if(!i)throw new Error;const a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Qr(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const gc=z("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Cl),me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Qr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function vc(e){if(!qr.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Qr(n)}const bc=z("$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=>{vc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),yc=z("$ZodE164",(e,t)=>{t.pattern??(t.pattern=_l),me.init(e,t)});function xc(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 jc=z("$ZodJWT",(e,t)=>{me.init(e,t),e._zod.check=n=>{xc(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Jr=z("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??Pl,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}}),wc=z("$ZodNumber",(e,t)=>{Ml.init(e,t),Jr.init(e,t)}),kc=z("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=n=>n}),Nc=z("$ZodNever",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Ss(e,t,n){e.issues.length&&t.issues.push(...ns(n,e.issues)),t.value[n]=e.value}const Sc=z("$ZodArray",(e,t)=>{we.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=>Ss(d,n,o))):Ss(c,n,o)}return a.length?Promise.all(a).then(()=>n):n}});function Ut(e,t,n){e.issues.length&&t.issues.push(...ns(n,e.issues)),t.value[n]=e.value}function Cs(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(...ns(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Cc=z("$ZodObject",(e,t)=>{we.init(e,t);const n=zr(()=>{const p=Object.keys(t.shape);for(const h of p)if(!(t.shape[h]instanceof we))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const u=Yo(t.shape);return{shape:t.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(u)}});he(e._zod,"propValues",()=>{const p=t.shape,u={};for(const h in p){const v=p[h]._zod;if(v.values){u[h]??(u[h]=new Set);for(const y of v.values)u[h].add(y)}}return u});const r=p=>{const u=new Ql(["shape","payload","ctx"]),h=n.value,v=b=>{const x=jt(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};u.write("const input = payload.value;");const y=Object.create(null);let j=0;for(const b of h.keys)y[b]=`key_${j++}`;u.write("const newResult = {}");for(const b of h.keys)if(h.optionalKeys.has(b)){const x=y[b];u.write(`const ${x} = ${v(b)};`);const k=jt(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 ? [${jt(b)}, ...iss.path] : [${jt(b)}]
84
+ })));`),u.write(`newResult[${jt(b)}] = ${x}.value`)}u.write("payload.value = newResult;"),u.write("return payload;");const f=u.compile();return(b,x)=>f(p,b,x)};let i;const a=Ln,o=!Pr.jitless,c=o&&Qo.value,d=t.catchall;let g;e._zod.parse=(p,u)=>{g??(g=n.value);const h=p.value;if(!a(h))return p.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),p;const v=[];if(o&&c&&(u==null?void 0:u.async)===!1&&u.jitless!==!0)i||(i=r(t.shape)),p=i(p,u);else{p.value={};const x=g.shape;for(const k of g.keys){const E=x[k],w=E._zod.run({value:h[k],issues:[]},u),R=E._zod.optin==="optional"&&E._zod.optout==="optional";w instanceof Promise?v.push(w.then(M=>R?Cs(M,p,k,h):Ut(M,p,k))):R?Cs(w,p,k,h):Ut(w,p,k)}}if(!d)return v.length?Promise.all(v).then(()=>p):p;const y=[],j=g.keySet,f=d._zod,b=f.def.type;for(const x of Object.keys(h)){if(j.has(x))continue;if(b==="never"){y.push(x);continue}const k=f.run({value:h[x],issues:[]},u);k instanceof Promise?v.push(k.then(E=>Ut(E,p,x))):Ut(k,p,x)}return y.length&&p.issues.push({code:"unrecognized_keys",keys:y,input:h,inst:e}),v.length?Promise.all(v).then(()=>p):p}});function $s(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=>it(a,r,rt())))}),t}const $c=z("$ZodUnion",(e,t)=>{we.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=>es(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=>$s(o,n,e,r)):$s(a,n,e,r)}}),_c=z("$ZodIntersection",(e,t)=>{we.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])=>_s(n,c,d)):_s(n,a,o)}});function Fn(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(Mn(e)&&Mn(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=Fn(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=Fn(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 _s(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=Fn(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 Ec=z("$ZodEnum",(e,t)=>{we.init(e,t);const n=Ir(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>Jo.has(typeof r)).map(r=>typeof r=="string"?fn(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}}),Ac=z("$ZodTransform",(e,t)=>{we.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 At;return n.value=i,n}}),Rc=z("$ZodOptional",(e,t)=>{we.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(`^(${es(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)}),Tc=z("$ZodNullable",(e,t)=>{we.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(`^(${es(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)}),Oc=z("$ZodDefault",(e,t)=>{we.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=>Es(a,t)):Es(i,t)}});function Es(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Pc=z("$ZodPrefault",(e,t)=>{we.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))}),Ic=z("$ZodNonOptional",(e,t)=>{we.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=>As(a,e)):As(i,e)}});function As(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 zc=z("$ZodCatch",(e,t)=>{we.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=>it(o,r,rt()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(a=>it(a,r,rt()))},input:n.value}),n.issues=[]),n)}}),Lc=z("$ZodPipe",(e,t)=>{we.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=>Rs(a,t,r)):Rs(i,t,r)}});function Rs(e,t,n){return $t(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Mc=z("$ZodReadonly",(e,t)=>{we.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(Ts):Ts(i)}});function Ts(e){return e.value=Object.freeze(e.value),e}const Fc=z("$ZodCustom",(e,t)=>{Re.init(e,t),we.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=>Os(a,n,r,e));Os(i,n,r,e)}});function Os(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Rt(i))}}class Yr{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function Hr(){return new Yr}const St=Hr();function Uc(e,t){return new e({type:"string",...Y(t)})}function Dc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Y(t)})}function Ps(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Y(t)})}function Zc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Y(t)})}function qc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y(t)})}function Gc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y(t)})}function Bc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y(t)})}function Wc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Y(t)})}function Vc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Y(t)})}function Kc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y(t)})}function Qc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Y(t)})}function Jc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y(t)})}function Yc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Y(t)})}function Hc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Y(t)})}function Xc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y(t)})}function eu(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y(t)})}function tu(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y(t)})}function nu(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y(t)})}function su(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y(t)})}function ru(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Y(t)})}function iu(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Y(t)})}function au(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Y(t)})}function ou(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Y(t)})}function lu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y(t)})}function cu(e,t){return new e({type:"string",format:"date",check:"string_format",...Y(t)})}function uu(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Y(t)})}function du(e,t){return new e({type:"string",format:"duration",check:"string_format",...Y(t)})}function pu(e,t){return new e({type:"number",checks:[],...Y(t)})}function hu(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Y(t)})}function mu(e){return new e({type:"unknown"})}function fu(e,t){return new e({type:"never",...Y(t)})}function Is(e,t){return new Vr({check:"less_than",...Y(t),value:e,inclusive:!1})}function Nn(e,t){return new Vr({check:"less_than",...Y(t),value:e,inclusive:!0})}function zs(e,t){return new Kr({check:"greater_than",...Y(t),value:e,inclusive:!1})}function Sn(e,t){return new Kr({check:"greater_than",...Y(t),value:e,inclusive:!0})}function Ls(e,t){return new Ll({check:"multiple_of",...Y(t),value:e})}function Xr(e,t){return new Fl({check:"max_length",...Y(t),maximum:e})}function an(e,t){return new Ul({check:"min_length",...Y(t),minimum:e})}function ei(e,t){return new Dl({check:"length_equals",...Y(t),length:e})}function gu(e,t){return new Zl({check:"string_format",format:"regex",...Y(t),pattern:e})}function vu(e){return new ql({check:"string_format",format:"lowercase",...Y(e)})}function bu(e){return new Gl({check:"string_format",format:"uppercase",...Y(e)})}function yu(e,t){return new Bl({check:"string_format",format:"includes",...Y(t),includes:e})}function xu(e,t){return new Wl({check:"string_format",format:"starts_with",...Y(t),prefix:e})}function ju(e,t){return new Vl({check:"string_format",format:"ends_with",...Y(t),suffix:e})}function Pt(e){return new Kl({check:"overwrite",tx:e})}function wu(e){return Pt(t=>t.normalize(e))}function ku(){return Pt(e=>e.trim())}function Nu(){return Pt(e=>e.toLowerCase())}function Su(){return Pt(e=>e.toUpperCase())}function Cu(e,t,n){return new e({type:"array",element:t,...Y(n)})}function $u(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Y(n)})}class Ms{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??St,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 p,u,h;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=(p=t._zod).toJSONSchema)==null?void 0:u.call(p);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 j=l.schema;switch(i.type){case"string":{const f=j;f.type="string";const{minimum:b,maximum:x,format:k,patterns:E,contentEncoding:w}=t._zod.bag;if(typeof b=="number"&&(f.minLength=b),typeof x=="number"&&(f.maxLength=x),k&&(f.format=a[k]??k,f.format===""&&delete f.format),w&&(f.contentEncoding=w),E&&E.size>0){const R=[...E];R.length===1?f.pattern=R[0].source:R.length>1&&(l.schema.allOf=[...R.map(M=>({...this.target==="draft-7"?{type:"string"}:{},pattern:M.source}))])}break}case"number":{const f=j,{minimum:b,maximum:x,format:k,multipleOf:E,exclusiveMaximum:w,exclusiveMinimum:R}=t._zod.bag;typeof k=="string"&&k.includes("int")?f.type="integer":f.type="number",typeof R=="number"&&(f.exclusiveMinimum=R),typeof b=="number"&&(f.minimum=b,typeof R=="number"&&(R>=b?delete f.minimum:delete f.exclusiveMinimum)),typeof w=="number"&&(f.exclusiveMaximum=w),typeof x=="number"&&(f.maximum=x,typeof w=="number"&&(w<=x?delete f.maximum:delete f.exclusiveMaximum)),typeof E=="number"&&(f.multipleOf=E);break}case"boolean":{const f=j;f.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":{j.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":{j.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=j,{minimum:b,maximum:x}=t._zod.bag;typeof b=="number"&&(f.minItems=b),typeof x=="number"&&(f.maxItems=x),f.type="array",f.items=this.process(i.element,{...v,path:[...v.path,"items"]});break}case"object":{const f=j;f.type="object",f.properties={};const b=i.shape;for(const E in b)f.properties[E]=this.process(b[E],{...v,path:[...v.path,"properties",E]});const x=new Set(Object.keys(b)),k=new Set([...x].filter(E=>{const w=i.shape[E]._zod;return this.io==="input"?w.optin===void 0:w.optout===void 0}));k.size>0&&(f.required=Array.from(k)),((h=i.catchall)==null?void 0:h._zod.def.type)==="never"?f.additionalProperties=!1:i.catchall?i.catchall&&(f.additionalProperties=this.process(i.catchall,{...v,path:[...v.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=j;f.anyOf=i.options.map((b,x)=>this.process(b,{...v,path:[...v.path,"anyOf",x]}));break}case"intersection":{const f=j,b=this.process(i.left,{...v,path:[...v.path,"allOf",0]}),x=this.process(i.right,{...v,path:[...v.path,"allOf",1]}),k=w=>"allOf"in w&&Object.keys(w).length===1,E=[...k(b)?b.allOf:[b],...k(x)?x.allOf:[x]];f.allOf=E;break}case"tuple":{const f=j;f.type="array";const b=i.items.map((E,w)=>this.process(E,{...v,path:[...v.path,"prefixItems",w]}));if(this.target==="draft-2020-12"?f.prefixItems=b:f.items=b,i.rest){const E=this.process(i.rest,{...v,path:[...v.path,"items"]});this.target==="draft-2020-12"?f.items=E:f.additionalItems=E}i.rest&&(f.items=this.process(i.rest,{...v,path:[...v.path,"items"]}));const{minimum:x,maximum:k}=t._zod.bag;typeof x=="number"&&(f.minItems=x),typeof k=="number"&&(f.maxItems=k);break}case"record":{const f=j;f.type="object",f.propertyNames=this.process(i.keyType,{...v,path:[...v.path,"propertyNames"]}),f.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 f=j,b=Ir(i.entries);b.every(x=>typeof x=="number")&&(f.type="number"),b.every(x=>typeof x=="string")&&(f.type="string"),f.enum=b;break}case"literal":{const f=j,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];f.type=x===null?"null":typeof x,f.const=x}else b.every(x=>typeof x=="number")&&(f.type="number"),b.every(x=>typeof x=="string")&&(f.type="string"),b.every(x=>typeof x=="boolean")&&(f.type="string"),b.every(x=>x===null)&&(f.type="null"),f.enum=b;break}case"file":{const f=j,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:x,maximum:k,mime:E}=t._zod.bag;x!==void 0&&(b.minLength=x),k!==void 0&&(b.maxLength=k),E?E.length===1?(b.contentMediaType=E[0],Object.assign(f,b)):f.anyOf=E.map(w=>({...b,contentMediaType:w})):Object.assign(f,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(i.innerType,v);j.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,v),l.ref=i.innerType;break}case"success":{const f=j;f.type="boolean";break}case"default":{this.process(i.innerType,v),l.ref=i.innerType,j.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,v),l.ref=i.innerType,this.io==="input"&&(j._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,v),l.ref=i.innerType;let f;try{f=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}j.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=j,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=b.source;break}case"pipe":{const f=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(f,v),l.ref=f;break}case"readonly":{this.process(i.innerType,v),l.ref=i.innerType,j.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 f=t._zod.innerType;this.process(f,v),l.ref=f;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"&&ke(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,p,u,h,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=j=>{var E;const f=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const w=(E=r.external.registry.get(j[0]))==null?void 0:E.id,R=r.external.uri??(_=>_);if(w)return{ref:R(w)};const M=j[1].defId??j[1].schema.id??`schema${this.counter++}`;return j[1].defId=M,{defId:M,ref:`${R("__shared")}#/${f}/${M}`}}if(j[1]===i)return{ref:"#"};const x=`#/${f}/`,k=j[1].schema.id??`__schema${this.counter++}`;return{defId:k,ref:x+k}},o=j=>{if(j[1].schema.$ref)return;const f=j[1],{ref:b,defId:x}=a(j);f.def={...f.schema},x&&(f.defId=x);const k=f.schema;for(const E in k)delete k[E];k.$ref=b};if(r.cycles==="throw")for(const j of this.seen.entries()){const f=j[1];if(f.cycle)throw new Error(`Cycle detected: #/${(g=f.cycle)==null?void 0:g.join("/")}/<root>
85
+
86
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const j of this.seen.entries()){const f=j[1];if(t===j[0]){o(j);continue}if(r.external){const x=(p=r.external.registry.get(j[0]))==null?void 0:p.id;if(t!==j[0]&&x){o(j);continue}}if((u=this.metadataRegistry.get(j[0]))==null?void 0:u.id){o(j);continue}if(f.cycle){o(j);continue}if(f.count>1&&r.reused==="ref"){o(j);continue}}const l=(j,f)=>{const b=this.seen.get(j),x=b.def??b.schema,k={...x};if(b.ref===null)return;const E=b.ref;if(b.ref=null,E){l(E,f);const w=this.seen.get(E).schema;w.$ref&&f.target==="draft-7"?(x.allOf=x.allOf??[],x.allOf.push(w)):(Object.assign(x,w),Object.assign(x,k))}b.isParent||this.override({zodSchema:j,jsonSchema:x,path:b.path??[]})};for(const j of[...this.seen.entries()].reverse())l(j[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}`),(h=r.external)!=null&&h.uri){const j=(v=r.external.registry.get(t))==null?void 0:v.id;if(!j)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(j)}Object.assign(c,i.def);const d=((y=r.external)==null?void 0:y.defs)??{};for(const j of this.seen.entries()){const f=j[1];f.def&&f.defId&&(d[f.defId]=f.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 _u(e,t){if(e instanceof Yr){const r=new Ms(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 Ms(t);return n.process(e),n.emit(e,t)}function ke(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 ke(i.element,n);case"object":{for(const a in i.shape)if(ke(i.shape[a],n))return!0;return!1}case"union":{for(const a of i.options)if(ke(a,n))return!0;return!1}case"intersection":return ke(i.left,n)||ke(i.right,n);case"tuple":{for(const a of i.items)if(ke(a,n))return!0;return!!(i.rest&&ke(i.rest,n))}case"record":return ke(i.keyType,n)||ke(i.valueType,n);case"map":return ke(i.keyType,n)||ke(i.valueType,n);case"set":return ke(i.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ke(i.innerType,n);case"lazy":return ke(i.getter(),n);case"default":return ke(i.innerType,n);case"prefault":return ke(i.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return ke(i.in,n)||ke(i.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${i.type}`)}const Eu=z("ZodISODateTime",(e,t)=>{lc.init(e,t),ve.init(e,t)});function Au(e){return lu(Eu,e)}const Ru=z("ZodISODate",(e,t)=>{cc.init(e,t),ve.init(e,t)});function Tu(e){return cu(Ru,e)}const Ou=z("ZodISOTime",(e,t)=>{uc.init(e,t),ve.init(e,t)});function Pu(e){return uu(Ou,e)}const Iu=z("ZodISODuration",(e,t)=>{dc.init(e,t),ve.init(e,t)});function zu(e){return du(Iu,e)}const Lu=(e,t)=>{Fr.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>al(e,n)},flatten:{value:n=>il(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},vn=z("ZodError",Lu,{Parent:Error}),Mu=ol(vn),Fu=ll(vn),Uu=Dr(vn),Du=Zr(vn),Ne=z("ZodType",(e,t)=>(we.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)=>at(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>Mu(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Uu(e,n,r),e.parseAsync=async(n,r)=>Fu(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Du(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(Ad(n,r)),e.superRefine=n=>e.check(Rd(n)),e.overwrite=n=>e.check(Pt(n)),e.optional=()=>Zs(e),e.nullable=()=>qs(e),e.nullish=()=>Zs(qs(e)),e.nonoptional=n=>wd(e,n),e.array=()=>Qe(e),e.or=n=>is([e,n]),e.and=n=>md(e,n),e.transform=n=>Gs(e,gd(n)),e.default=n=>yd(e,n),e.prefault=n=>jd(e,n),e.catch=n=>Nd(e,n),e.pipe=n=>Gs(e,n),e.readonly=()=>$d(e),e.describe=n=>{const r=e.clone();return St.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=St.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return St.get(e);const r=e.clone();return St.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ti=z("_ZodString",(e,t)=>{rs.init(e,t),Ne.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(gu(...r)),e.includes=(...r)=>e.check(yu(...r)),e.startsWith=(...r)=>e.check(xu(...r)),e.endsWith=(...r)=>e.check(ju(...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(vu(r)),e.uppercase=r=>e.check(bu(r)),e.trim=()=>e.check(ku()),e.normalize=(...r)=>e.check(wu(...r)),e.toLowerCase=()=>e.check(Nu()),e.toUpperCase=()=>e.check(Su())}),Zu=z("ZodString",(e,t)=>{rs.init(e,t),ti.init(e,t),e.email=n=>e.check(Dc(qu,n)),e.url=n=>e.check(Wc(Gu,n)),e.jwt=n=>e.check(ou(id,n)),e.emoji=n=>e.check(Vc(Bu,n)),e.guid=n=>e.check(Ps(Fs,n)),e.uuid=n=>e.check(Zc(Dt,n)),e.uuidv4=n=>e.check(qc(Dt,n)),e.uuidv6=n=>e.check(Gc(Dt,n)),e.uuidv7=n=>e.check(Bc(Dt,n)),e.nanoid=n=>e.check(Kc(Wu,n)),e.guid=n=>e.check(Ps(Fs,n)),e.cuid=n=>e.check(Qc(Vu,n)),e.cuid2=n=>e.check(Jc(Ku,n)),e.ulid=n=>e.check(Yc(Qu,n)),e.base64=n=>e.check(ru(nd,n)),e.base64url=n=>e.check(iu(sd,n)),e.xid=n=>e.check(Hc(Ju,n)),e.ksuid=n=>e.check(Xc(Yu,n)),e.ipv4=n=>e.check(eu(Hu,n)),e.ipv6=n=>e.check(tu(Xu,n)),e.cidrv4=n=>e.check(nu(ed,n)),e.cidrv6=n=>e.check(su(td,n)),e.e164=n=>e.check(au(rd,n)),e.datetime=n=>e.check(Au(n)),e.date=n=>e.check(Tu(n)),e.time=n=>e.check(Pu(n)),e.duration=n=>e.check(zu(n))});function J(e){return Uc(Zu,e)}const ve=z("ZodStringFormat",(e,t)=>{me.init(e,t),ti.init(e,t)}),qu=z("ZodEmail",(e,t)=>{Xl.init(e,t),ve.init(e,t)}),Fs=z("ZodGUID",(e,t)=>{Yl.init(e,t),ve.init(e,t)}),Dt=z("ZodUUID",(e,t)=>{Hl.init(e,t),ve.init(e,t)}),Gu=z("ZodURL",(e,t)=>{ec.init(e,t),ve.init(e,t)}),Bu=z("ZodEmoji",(e,t)=>{tc.init(e,t),ve.init(e,t)}),Wu=z("ZodNanoID",(e,t)=>{nc.init(e,t),ve.init(e,t)}),Vu=z("ZodCUID",(e,t)=>{sc.init(e,t),ve.init(e,t)}),Ku=z("ZodCUID2",(e,t)=>{rc.init(e,t),ve.init(e,t)}),Qu=z("ZodULID",(e,t)=>{ic.init(e,t),ve.init(e,t)}),Ju=z("ZodXID",(e,t)=>{ac.init(e,t),ve.init(e,t)}),Yu=z("ZodKSUID",(e,t)=>{oc.init(e,t),ve.init(e,t)}),Hu=z("ZodIPv4",(e,t)=>{pc.init(e,t),ve.init(e,t)}),Xu=z("ZodIPv6",(e,t)=>{hc.init(e,t),ve.init(e,t)}),ed=z("ZodCIDRv4",(e,t)=>{mc.init(e,t),ve.init(e,t)}),td=z("ZodCIDRv6",(e,t)=>{fc.init(e,t),ve.init(e,t)}),nd=z("ZodBase64",(e,t)=>{gc.init(e,t),ve.init(e,t)}),sd=z("ZodBase64URL",(e,t)=>{bc.init(e,t),ve.init(e,t)}),rd=z("ZodE164",(e,t)=>{yc.init(e,t),ve.init(e,t)}),id=z("ZodJWT",(e,t)=>{jc.init(e,t),ve.init(e,t)}),ni=z("ZodNumber",(e,t)=>{Jr.init(e,t),Ne.init(e,t),e.gt=(r,i)=>e.check(zs(r,i)),e.gte=(r,i)=>e.check(Sn(r,i)),e.min=(r,i)=>e.check(Sn(r,i)),e.lt=(r,i)=>e.check(Is(r,i)),e.lte=(r,i)=>e.check(Nn(r,i)),e.max=(r,i)=>e.check(Nn(r,i)),e.int=r=>e.check(Us(r)),e.safe=r=>e.check(Us(r)),e.positive=r=>e.check(zs(0,r)),e.nonnegative=r=>e.check(Sn(0,r)),e.negative=r=>e.check(Is(0,r)),e.nonpositive=r=>e.check(Nn(0,r)),e.multipleOf=(r,i)=>e.check(Ls(r,i)),e.step=(r,i)=>e.check(Ls(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 Ge(e){return pu(ni,e)}const ad=z("ZodNumberFormat",(e,t)=>{wc.init(e,t),ni.init(e,t)});function Us(e){return hu(ad,e)}const od=z("ZodUnknown",(e,t)=>{kc.init(e,t),Ne.init(e,t)});function Ds(){return mu(od)}const ld=z("ZodNever",(e,t)=>{Nc.init(e,t),Ne.init(e,t)});function cd(e){return fu(ld,e)}const ud=z("ZodArray",(e,t)=>{Sc.init(e,t),Ne.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 Qe(e,t){return Cu(ud,e,t)}const dd=z("ZodObject",(e,t)=>{Cc.init(e,t),Ne.init(e,t),he(e,"shape",()=>t.shape),e.keyof=()=>ft(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ds()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ds()}),e.strict=()=>e.clone({...e._zod.def,catchall:cd()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>tl(e,n),e.merge=n=>nl(e,n),e.pick=n=>Xo(e,n),e.omit=n=>el(e,n),e.partial=(...n)=>sl(si,e,n[0]),e.required=(...n)=>rl(ri,e,n[0])});function pe(e,t){const n={type:"object",get shape(){return ts(this,"shape",{...e}),this.shape},...Y(t)};return new dd(n)}const pd=z("ZodUnion",(e,t)=>{$c.init(e,t),Ne.init(e,t),e.options=t.options});function is(e,t){return new pd({type:"union",options:e,...Y(t)})}const hd=z("ZodIntersection",(e,t)=>{_c.init(e,t),Ne.init(e,t)});function md(e,t){return new hd({type:"intersection",left:e,right:t})}const Un=z("ZodEnum",(e,t)=>{Ec.init(e,t),Ne.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 Un({...t,checks:[],...Y(i),entries:a})},e.exclude=(r,i)=>{const a={...t.entries};for(const o of r)if(n.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Un({...t,checks:[],...Y(i),entries:a})}});function ft(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Un({type:"enum",entries:n,...Y(t)})}const fd=z("ZodTransform",(e,t)=>{Ac.init(e,t),Ne.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(Rt(a,n.value,t));else{const o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),n.issues.push(Rt(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(a=>(n.value=a,n)):(n.value=i,n)}});function gd(e){return new fd({type:"transform",transform:e})}const si=z("ZodOptional",(e,t)=>{Rc.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Zs(e){return new si({type:"optional",innerType:e})}const vd=z("ZodNullable",(e,t)=>{Tc.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function qs(e){return new vd({type:"nullable",innerType:e})}const bd=z("ZodDefault",(e,t)=>{Oc.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function yd(e,t){return new bd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const xd=z("ZodPrefault",(e,t)=>{Pc.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function jd(e,t){return new xd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ri=z("ZodNonOptional",(e,t)=>{Ic.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wd(e,t){return new ri({type:"nonoptional",innerType:e,...Y(t)})}const kd=z("ZodCatch",(e,t)=>{zc.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Nd(e,t){return new kd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Sd=z("ZodPipe",(e,t)=>{Lc.init(e,t),Ne.init(e,t),e.in=t.in,e.out=t.out});function Gs(e,t){return new Sd({type:"pipe",in:e,out:t})}const Cd=z("ZodReadonly",(e,t)=>{Mc.init(e,t),Ne.init(e,t)});function $d(e){return new Cd({type:"readonly",innerType:e})}const _d=z("ZodCustom",(e,t)=>{Fc.init(e,t),Ne.init(e,t)});function Ed(e){const t=new Re({check:"custom"});return t._zod.check=e,t}function Ad(e,t={}){return $u(_d,e,t)}function Rd(e){const t=Ed(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Rt(r,n.value,t._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Rt(i))}},e(n.value,n)));return t}function Cn(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 X(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 as={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+X(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+X(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,X(n)),X(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,X(n)),X(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?Cn(a,r):a,c=r?Cn(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=X(l)-X(c);return i?-u:u}const p=String(l??"").localeCompare(String(c??""));return i?-p:p})}},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?Cn(o,i):o;switch(a){case"==":return l==r;case"!=":return l!=r;case">":return X(l)>X(r);case"<":return X(l)<X(r);case">=":return X(l)>=X(r);case"<=":return X(l)<=X(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=X(e),r=t!=null?X(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(X(e))},Floor:{name:"Floor",signature:"Floor(number) → number",description:"Round down to nearest integer",fn:e=>Math.floor(X(e))},Ceil:{name:"Ceil",signature:"Ceil(number) → number",description:"Round up to nearest integer",fn:e=>Math.ceil(X(e))}},os=new Set(["Each"]),Td={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."}},De={Run:"run",ToAssistant:"continue_conversation",OpenUrl:"open_url",Set:"set",Reset:"reset"},ii=new Set(["Action",...Object.keys(De)]),Od=new Set([...Object.keys(as),...os,...ii]);function Tt(e){return Od.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 Pd="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 Id(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 zd(){const e=Object.values(as).map(n=>`@${n.signature} — ${n.description}`),t=Object.values(Td).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 Ld(){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 Md(){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 Fd(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 Ud(){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 Dd(){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 qd(){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 Gd(){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 Bd(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 Wd(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 Vd(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(Wd(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 Kd(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,p;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 h;return(h=u.signature)==null?void 0:h.includes("ActionExpression")}),l=[];l.push(e.preamble??Pd),l.push(""),l.push(Id(t,{supportsExpressions:a,bindings:i})),l.push(""),l.push(Kd(e,{toolCalls:r,bindings:i,usesActionExpression:o})),a&&(l.push(""),l.push(zd())),r&&(l.push(""),l.push(Ld()),l.push(""),l.push(Md())),o&&(l.push(""),l.push(Fd({toolCalls:r,bindings:i}))),r&&i&&(l.push(""),l.push(Ud())),r&&(l.push(""),l.push(Gd())),(g=e.tools)!=null&&g.length&&(l.push(""),l.push(Vd(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(Dd())),e.inlineMode&&(l.push(""),l.push(qd())),l.push(Bd(t,{toolCalls:r,bindings:i})),(p=e.additionalRules)!=null&&p.length){l.push("");for(const u of e.additionalRules)l.push(`- ${u}`)}return l.join(`
277
+ `)}const Jd=new WeakSet;function _t(e){return typeof e=="object"&&e!==null&&Jd.has(e)}const oi=new WeakMap;function Yd(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 Hd(e){return Yd(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 ls(e){var t;return(t=Je(e))==null?void 0:t.type}function li(e){const t=ls(e);return t==="optional"||t==="default"||t==="nullable"}function It(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 ls(It(e))==="array"}function Xd(e){const t=Je(It(e));if((t==null?void 0:t.type)==="array")return t.element??t.innerType}function ep(e){const t=Je(It(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 tp(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 Bs(e){const t=Je(e);if((t==null?void 0:t.type)==="union"&&Array.isArray(t.options))return t.options}function np(e){const t=Je(e);if((t==null?void 0:t.type)==="object"&&t.shape&&typeof t.shape=="object")return t.shape}function dt(e,t){const n=_t(e),r=sp(It(e),t);if(r)return n?`$binding<${r}>`:r}function sp(e,t){var l;const n=tp(e,t);if(n)return n;const r=Bs(e);if(r){const c=r.map(d=>dt(d,t)).filter(Boolean);if(c.length>0)return c.join(" | ")}if(ci(e)){const c=Xd(e);if(!c)return;const d=dt(c,t);return d?Bs(It(c))!==void 0?`(${d})[]`:`${d}[]`:void 0}const i=ls(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<${dt(c==null?void 0:c.keyType,t)??"string"}, ${dt(c==null?void 0:c.valueType,t)??"any"}>`}const a=ep(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=np(e);return o?`{${Object.entries(o).map(([c,d])=>{const g=li(d)?"?":"",p=dt(d,t);return p?`${c}${g}: ${p}`:`${c}${g}`}).join(", ")}}`:"any"}function rp(e,t){return Object.entries(e).map(([n,r])=>({name:n,isOptional:li(r),isArray:ci(r),typeAnnotation:dt(r,t)}))}function ip(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 Ws(e,t){const n={};for(const[r,i]of Object.entries(e))n[r]={signature:ip(r,rp(i.props.shape,t)),description:i.description};return n}function ap(e){const t={},n=Hr();for(const r of e.components)n.add(r.props,{id:r.name}),t[r.name]=r;if(e.root&&!t[e.root]){const r=Object.keys(t).join(", ");throw new Error(`[createLibrary] Root component "${e.root}" was not found in components. Available components: ${r}`)}return{components:t,componentGroups:e.componentGroups,root:e.root,prompt(r){return Qd({root:e.root,components:Ws(t,n),componentGroups:e.componentGroups,...r})},toSpec(){return{root:e.root,components:Ws(t,n),componentGroups:e.componentGroups}},toJSONSchema(){const r=pe(Object.fromEntries(Object.entries(t).map(([i,a])=>[i,a.props])));return _u(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 op(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 lp=new Set(["Comp","Ref","StateRef","RuntimeRef","BinOp","UnaryOp","Ternary","Member","Index","Assign","Str","Num","Bool","Null","Arr","Obj","Ph"]);function pt(e){return!e||typeof e!="object"||Array.isArray(e)?!1:lp.has(e.k)}function cp(e,t){const n=r=>{switch(t(r),r.k){case"Comp":r.args.forEach(n),Object.values(r.mappedProps??{}).forEach(n);break;case"Arr":r.els.forEach(n);break;case"Obj":r.entries.forEach(([,i])=>n(i));break;case"BinOp":n(r.left),n(r.right);break;case"UnaryOp":n(r.operand);break;case"Ternary":n(r.cond),n(r.then),n(r.else);break;case"Member":n(r.obj);break;case"Index":n(r.obj),n(r.index);break;case"Assign":n(r.value);break}};n(e)}let N=(function(e){return e[e.Newline=0]="Newline",e[e.LParen=1]="LParen",e[e.RParen=2]="RParen",e[e.LBrack=3]="LBrack",e[e.RBrack=4]="RBrack",e[e.LBrace=5]="LBrace",e[e.RBrace=6]="RBrace",e[e.Comma=7]="Comma",e[e.Colon=8]="Colon",e[e.Equals=9]="Equals",e[e.True=10]="True",e[e.False=11]="False",e[e.Null=12]="Null",e[e.EOF=13]="EOF",e[e.Str=14]="Str",e[e.Num=15]="Num",e[e.Ident=16]="Ident",e[e.Type=17]="Type",e[e.StateVar=18]="StateVar",e[e.Dot=19]="Dot",e[e.Plus=20]="Plus",e[e.Minus=21]="Minus",e[e.Star=22]="Star",e[e.Slash=23]="Slash",e[e.Percent=24]="Percent",e[e.EqEq=25]="EqEq",e[e.NotEq=26]="NotEq",e[e.Greater=27]="Greater",e[e.Less=28]="Less",e[e.GreaterEq=29]="GreaterEq",e[e.LessEq=30]="LessEq",e[e.And=31]="And",e[e.Or=32]="Or",e[e.Not=33]="Not",e[e.Question=34]="Question",e[e.BuiltinCall=35]="BuiltinCall",e})({});const up=1,Vs=2,Ks=3,$n=4,wt=5,_n=6,qt=7,Qs=8,dp=9;function Js(e){let t=0;const n=()=>e[t]??{t:N.EOF},r=()=>{const u=n();return t++,u},i=u=>{n().t===u&&t++};function a(u){switch(u.t){case N.Question:return up;case N.Or:return Vs;case N.And:return Ks;case N.EqEq:case N.NotEq:return $n;case N.Greater:case N.Less:case N.GreaterEq:case N.LessEq:return wt;case N.Plus:case N.Minus:return _n;case N.Star:case N.Slash:case N.Percent:return qt;case N.Dot:case N.LBrack:return dp;default:return 0}}function o(u=0){let h=l();for(;a(n())>u;)h=c(h);return h}function l(){var h,v;const u=n();if(u.t===N.Str)return r(),{k:"Str",v:u.v};if(u.t===N.Num)return r(),{k:"Num",v:u.v};if(u.t===N.True)return r(),{k:"Bool",v:!0};if(u.t===N.False)return r(),{k:"Bool",v:!1};if(u.t===N.Null)return r(),{k:"Null"};if(u.t===N.LBrack)return g();if(u.t===N.LBrace)return p();if(u.t===N.StateVar){const y=u.v;return r(),n().t===N.Equals?(r(),{k:"Assign",target:y,value:o(0)}):{k:"StateRef",n:y}}if(u.t===N.Type){const y=u.v;return((h=e[t+1])==null?void 0:h.t)===N.LParen&&(!Tt(y)||y==="Action")?d():(r(),{k:"Ref",n:y})}if(u.t===N.BuiltinCall)return((v=e[t+1])==null?void 0:v.t)===N.LParen?d():(r(),{k:"Ref",n:u.v});if(u.t===N.Ident)return r(),{k:"Ref",n:u.v};if(u.t===N.Not)return r(),{k:"UnaryOp",op:"!",operand:o(Qs)};if(u.t===N.Minus)return r(),{k:"UnaryOp",op:"-",operand:o(Qs)};if(u.t===N.LParen){r();const y=o(0);return i(N.RParen),y}return r(),{k:"Null"}}function c(u){const h=n();if(h.t===N.Plus)return r(),{k:"BinOp",op:"+",left:u,right:o(_n)};if(h.t===N.Minus)return r(),{k:"BinOp",op:"-",left:u,right:o(_n)};if(h.t===N.Star)return r(),{k:"BinOp",op:"*",left:u,right:o(qt)};if(h.t===N.Slash)return r(),{k:"BinOp",op:"/",left:u,right:o(qt)};if(h.t===N.Percent)return r(),{k:"BinOp",op:"%",left:u,right:o(qt)};if(h.t===N.EqEq)return r(),{k:"BinOp",op:"==",left:u,right:o($n)};if(h.t===N.NotEq)return r(),{k:"BinOp",op:"!=",left:u,right:o($n)};if(h.t===N.Greater)return r(),{k:"BinOp",op:">",left:u,right:o(wt)};if(h.t===N.Less)return r(),{k:"BinOp",op:"<",left:u,right:o(wt)};if(h.t===N.GreaterEq)return r(),{k:"BinOp",op:">=",left:u,right:o(wt)};if(h.t===N.LessEq)return r(),{k:"BinOp",op:"<=",left:u,right:o(wt)};if(h.t===N.And)return r(),{k:"BinOp",op:"&&",left:u,right:o(Ks)};if(h.t===N.Or)return r(),{k:"BinOp",op:"||",left:u,right:o(Vs)};if(h.t===N.Question){r();const v=o(0);return i(N.Colon),{k:"Ternary",cond:u,then:v,else:o(0)}}if(h.t===N.Dot){r();const v=n();return{k:"Member",obj:u,field:v.t===N.Ident||v.t===N.Type||v.t===N.Str||v.t===N.Num?(r(),String(v.v)):v.t===N.StateVar?(r(),v.v.replace(/^\$/,"")):(r(),"?")}}if(h.t===N.LBrack){r();const v=o(0);return i(N.RBrack),{k:"Index",obj:u,index:v}}return u}function d(){const u=n().v;r(),i(N.LParen);const h=[];for(;n().t!==N.RParen&&n().t!==N.EOF;)h.push(o(0)),n().t===N.Comma&&r();return i(N.RParen),{k:"Comp",name:u,args:h}}function g(){r();const u=[];for(;n().t!==N.RBrack&&n().t!==N.EOF;)u.push(o(0)),n().t===N.Comma&&r();return i(N.RBrack),{k:"Arr",els:u}}function p(){r();const u=[];for(;n().t!==N.RBrace&&n().t!==N.EOF;){const h=n(),v=h.t===N.Ident||h.t===N.Str||h.t===N.Type||h.t===N.Num?(r(),String(h.v)):h.t===N.StateVar?(r(),h.v.replace(/^\$/,"")):(r(),"?");i(N.Colon),u.push([v,o(0)]),n().t===N.Comma&&r()}return i(N.RBrace),{k:"Obj",entries:u}}return o(0)}function Ys(e){const t=[];let n=0;const r=e.length;for(;n<r;){for(;n<r&&(e[n]===" "||e[n]===" "||e[n]==="\r");)n++;if(n>=r)break;const i=e[n];if(i===`
278
+ `){t.push({t:N.Newline}),n++;continue}if(i==="("){t.push({t:N.LParen}),n++;continue}if(i===")"){t.push({t:N.RParen}),n++;continue}if(i==="["){t.push({t:N.LBrack}),n++;continue}if(i==="]"){t.push({t:N.RBrack}),n++;continue}if(i==="{"){t.push({t:N.LBrace}),n++;continue}if(i==="}"){t.push({t:N.RBrace}),n++;continue}if(i===","){t.push({t:N.Comma}),n++;continue}if(i===":"){t.push({t:N.Colon}),n++;continue}if(i==="="){n+1<r&&e[n+1]==="="?(t.push({t:N.EqEq}),n+=2):(t.push({t:N.Equals}),n++);continue}if(i==="!"){n+1<r&&e[n+1]==="="?(t.push({t:N.NotEq}),n+=2):(t.push({t:N.Not}),n++);continue}if(i===">"){n+1<r&&e[n+1]==="="?(t.push({t:N.GreaterEq}),n+=2):(t.push({t:N.Greater}),n++);continue}if(i==="<"){n+1<r&&e[n+1]==="="?(t.push({t:N.LessEq}),n+=2):(t.push({t:N.Less}),n++);continue}if(i==="&"){n+1<r&&e[n+1]==="&"?(t.push({t:N.And}),n+=2):(t.push({t:N.And}),n++);continue}if(i==="|"){n+1<r&&e[n+1]==="|"?(t.push({t:N.Or}),n+=2):(t.push({t:N.Or}),n++);continue}if(i==="."){t.push({t:N.Dot}),n++;continue}if(i==="?"){t.push({t:N.Question}),n++;continue}if(i==="+"){t.push({t:N.Plus}),n++;continue}if(i==="*"){t.push({t:N.Star}),n++;continue}if(i==="/"){t.push({t:N.Slash}),n++;continue}if(i==="%"){t.push({t:N.Percent}),n++;continue}if(i==='"'){const l=n;n++;let c=!1;for(;n<r;)if(e[n]==="\\")n+=2;else if(e[n]==='"'){n++,c=!0;break}else n++;const d=e.slice(l,n);try{const g=c?d:d+'"';t.push({t:N.Str,v:JSON.parse(g)})}catch{const g=d.replace(/^"|"$/g,"");t.push({t:N.Str,v:g})}continue}if(i==="'"){n++;let l="";for(;n<r;)if(e[n]==="\\"){if(n++,n<r){const c=e[n];c==="'"?l+="'":c==="\\"?l+="\\":c==="n"?l+=`
279
+ `:c==="t"?l+=" ":l+=c,n++}}else if(e[n]==="'"){n++;break}else l+=e[n],n++;t.push({t:N.Str,v:l});continue}if(i==="-"){const l=t.length>0?t[t.length-1]:null;if(!(!(l!=null&&(l.t===N.Num||l.t===N.Str||l.t===N.Ident||l.t===N.Type||l.t===N.RParen||l.t===N.RBrack||l.t===N.True||l.t===N.False||l.t===N.Null||l.t===N.StateVar||l.t===N.BuiltinCall))&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9")){t.push({t:N.Minus}),n++;continue}}const a=i>="0"&&i<="9",o=i==="-"&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9";if(a||o){const l=n;for(e[n]==="-"&&n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;if(n<r&&e[n]==="."&&n+1<r&&e[n+1]>="0"&&e[n+1]<="9")for(n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;if(n<r&&(e[n]==="e"||e[n]==="E"))for(n++,n<r&&(e[n]==="+"||e[n]==="-")&&n++;n<r&&e[n]>="0"&&e[n]<="9";)n++;t.push({t:N.Num,v:+e.slice(l,n)});continue}if(i==="$"&&n+1<r&&(e[n+1]>="a"&&e[n+1]<="z"||e[n+1]>="A"&&e[n+1]<="Z"||e[n+1]==="_")){const l=n;for(n++;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;t.push({t:N.StateVar,v:e.slice(l,n)});continue}if(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="_"){const l=n;for(;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;const c=e.slice(l,n);if(c==="true"){t.push({t:N.True});continue}if(c==="false"){t.push({t:N.False});continue}if(c==="null"){t.push({t:N.Null});continue}const d=i>="A"&&i<="Z"?N.Type:N.Ident;t.push({t:d,v:c});continue}if(i==="@"&&n+1<r&&(e[n+1]>="a"&&e[n+1]<="z"||e[n+1]>="A"&&e[n+1]<="Z"||e[n+1]==="_")){n++;const l=n;for(;n<r&&(e[n]>="a"&&e[n]<="z"||e[n]>="A"&&e[n]<="Z"||e[n]>="0"&&e[n]<="9"||e[n]==="_");)n++;t.push({t:N.BuiltinCall,v:e.slice(l,n)});continue}n++}return t.push({t:N.EOF}),t}function Jt(e){return e==null||typeof e!="object"?!1:pt(e)?!0:Array.isArray(e)?e.some(Jt):Ke(e)?Object.values(e.props).some(Jt):Object.values(e).some(Jt)}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"?ht(r,t):Dn(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(!os.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(Tt(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 Dn(e,t){return Ae(e,t,new Set)}function ht(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=ht(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]=ht(a,t);return r}case"Comp":{const{name:r,args:i}=e;if(Tt(r)){const c=di(e,t,new Set);return c||{...e,args:i.map(d=>Dn(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]=ht(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 p=g.name in o;t.errors.push({code:p?"null-required":"missing-required",component:r,path:`/${g.name}`,message:p?`required field "${g.name}" cannot be null`:`missing required field "${g.name}"`,statementId:t.currentStatementId})}return null}}}else if(!Tt(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=>Jt(c));return{type:"element",typeName:r,props:o,partial:t.partial,hasDynamicProps:l}}default:return op(e)?Dn(e,t):e}}function pp(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===N.Newline;)n++;if(n>=e.length||e[n].t===N.EOF)break;const r=e[n];if(r.t!==N.Ident&&r.t!==N.Type&&r.t!==N.StateVar){for(;n<e.length&&e[n].t!==N.Newline&&e[n].t!==N.EOF;)n++;continue}const i=r.v,a=r.t;if(n++,n>=e.length||e[n].t!==N.Equals){for(;n<e.length&&e[n].t!==N.Newline&&e[n].t!==N.EOF;)n++;continue}n++;const o=[];let l=0,c=0;for(;n<e.length&&e[n].t!==N.EOF;){const d=e[n].t;if(d===N.Newline&&l<=0&&c<=0){let g=n+1;for(;g<e.length&&e[g].t===N.Newline;)g++;const p=g<e.length?e[g].t:N.EOF;if(p===N.Question||p===N.Colon&&c>0){n++;continue}break}if(d===N.Newline){n++;continue}d===N.LParen||d===N.LBrack||d===N.LBrace?l++:(d===N.RParen||d===N.RBrack||d===N.RBrace)&&l>0?l--:d===N.Question&&l===0?c++:d===N.Colon&&l===0&&c>0&&c--,o.push(e[n++])}o.length&&t.push({id:i,idTokenType:a,tokens:o})}return t}function Yt(e=!0){return{root:null,meta:{incomplete:e,unresolved:[],orphaned:[],statementCount:0,errors:[]},stateDeclarations:{},queryStatements:[],mutationStatements:[]}}function pi(e){if(!pt(e))return[];const t=new Set;return cp(e,n=>{n.k==="StateRef"&&t.add(n.n)}),[...t]}function Xs(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===N.StateVar?{kind:"state",id:e.id,init:t}:{kind:"value",id:e.id,expr:t}}function hp(e,t){const n={},r=[],i=[];for(const a of e)switch(a.kind){case"state":n[a.id]=ht(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 er="root";function tr(e){return e.kind==="value"&&e.expr.k==="Comp"&&!Tt(e.expr.name)&&e.expr.name!==Ye.Query&&e.expr.name!==Ye.Mutation}function mp(e,t,n,r){var a;if(e.has(er))return er;if(r&&e.has(r))return r;const i=r?t.find(o=>tr(o)&&o.expr.name===r):void 0;return i?i.id:((a=t.find(tr))==null?void 0:a.id)??n}function Gt(e,t,n,r,i,a,o){const l=mp(e,t,n,o);if(!e.has(l))return Yt(r);const c=new Map;for(const[b,x]of e)c.set(b,x.kind==="state"?x.init:x.expr);const d=[],g=[],p=new Set;for(const[b,x]of e)b!==l&&(x.kind==="state"||x.kind==="query"||x.kind==="mutation"||p.add(b));const u={syms:c,cat:a,errors:g,unres:d,visited:new Set,partial:r,currentStatementId:l,unreached:p},h=ht(c.get(l),u),v=Ke(h)?h:null;v&&(v.statementId=l);const{stateDeclarations:y,queryStatements:j,mutationStatements:f}=hp(t,u);return{root:v,meta:{incomplete:r,unresolved:d,orphaned:[...p],statementCount:i,errors:g},stateDeclarations:y,queryStatements:j,mutationStatements:f}}function fp(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 nr(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 gp(e,t){let n="",r=0;const i=new Map;let a=0,o="";function l(p){const u=nr(p).trim();if(!(!u||/^```/.test(u)))for(const h of Hs(Ys(u))){const v=Xs(h,Js(h.tokens));i.set(h.id,v),a++,o||(o=h.id)}}function c(){let p=0,u=0,h=!1,v=!1,y=r;for(let j=r;j<n.length;j++){const f=n[j];if(v){v=!1;continue}if(f==="\\"&&h){v=!0;continue}if(h){f===h&&(h=!1);continue}if(f==='"'||f==="'"){h=f;continue}if(f==="("||f==="["||f==="{")p++;else if(f===")"||f==="]"||f==="}")p=Math.max(0,p-1);else if(f==="?"&&p===0)u++;else if(f===":"&&p===0&&u>0)u--;else if(f===`
285
+ `&&p<=0&&u<=0){let b=j+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,j).trim();x&&l(x),y=j+1,r=j+1}}return y}function d(){const p=c(),u=n.slice(p).trim();if(!u)return a===0?Yt():Gt(i,[...i.values()],o,!1,a,e,t);const h=nr(fp(u)).trim();if(!h)return a===0?Yt():Gt(i,[...i.values()],o,!1,a,e,t);const{text:v,wasIncomplete:y}=pp(h),j=Hs(Ys(v));if(!j.length)return a===0?Yt(y):Gt(i,[...i.values()],o,y,a,e,t);const f=new Map(i);for(const b of j){if(i.has(b.id))continue;const x=Xs(b,Js(b.tokens));f.set(b.id,x)}return Gt(f,[...f.values()],o||j[0].id,y,a+j.length,e,t)}function g(){n="",r=0,i.clear(),a=0,o=""}return{push(p){return n+=p,d()},set(p){(p.length<n.length||!p.startsWith(n))&&g();const u=p.slice(n.length);return u&&(n+=u),d()},getResult:d}}function vp(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e.default}function bp(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:vp(a[c])}));t.set(r,{params:l})}return t}function yp(e,t){return gp(bp(e),t)}function xp(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 jp(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=xp(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 wp(e){return typeof e=="object"&&e!==null&&e.__reactive==="assign"}function le(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=>le(o,t));case"Obj":return Object.fromEntries(e.entries.map(([o,l])=>[o,le(l,t)]));case"Comp":{if(os.has(e.name))return Np(e.name,e.args,t,n);const o=as[e.name];if(o){const l=e.args.map(c=>le(c,t));return o.fn(...l)}if(ii.has(e.name))return kp(e.name,e.args,t);if(e.mappedProps){const l=n==null?void 0:n.library.components[e.name],c={};for(const[g,p]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];p.k==="StateRef"&&u&&_t(u)?c[g]={__reactive:"assign",target:p.n,expr:{k:"StateRef",n:"$value"}}:p.k==="StateRef"?c[g]=n?t.getState(p.n):p:c[g]=le(p,t,n)}const d={type:"element",typeName:e.name,props:c,partial:!1,hasDynamicProps:!0};if(n)for(const[g,p]of Object.entries(c))Ke(p)?c[g]=cn(p,t,n):Array.isArray(p)&&(c[g]=p.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=le(e.left,t);return c&&le(e.right,t)}if(e.op==="||"){const c=le(e.left,t);return c||le(e.right,t)}const o=le(e.left,t),l=le(e.right,t);switch(e.op){case"+":return typeof o=="string"||typeof l=="string"?String(o??"")+String(l??""):X(o)+X(l);case"-":return X(o)-X(l);case"*":return X(o)*X(l);case"/":return X(l)===0?0:X(o)/X(l);case"%":return X(l)===0?0:X(o)%X(l);case"==":return o==l;case"!=":return o!=l;case">":return X(o)>X(l);case"<":return X(o)<X(l);case">=":return X(o)>=X(l);case"<=":return X(o)<=X(l);default:return null}}case"UnaryOp":return e.op==="!"?!le(e.operand,t):e.op==="-"?-X(le(e.operand,t)):null;case"Ternary":return le(e.cond,t)?le(e.then,t):le(e.else,t);case"Member":{const o=le(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=le(e.obj,t),l=le(e.index,t);return o==null||l==null?null:Array.isArray(o)?o[X(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 Zn(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(Zn)}:typeof e=="object"?{k:"Obj",entries:Object.entries(e).map(([t,n])=>[t,Zn(n)])}:{k:"Null"}}function kp(e,t,n){switch(e){case"Action":{const r=t.length>0?le(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:De.Run,statementId:r.n,refType:r.refType}:null}case"ToAssistant":{const r=t.length>0?String(le(t[0],n)??""):"",i=t.length>1?String(le(t[1],n)??""):void 0;return{type:De.ToAssistant,message:r,context:i}}case"OpenUrl":{const r=t.length>0?String(le(t[0],n)??""):"";return{type:De.OpenUrl,url:r}}case"Set":{if(t.length<2)return null;const r=t[0];return r.k!=="StateRef"?null:{type:De.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:De.Reset,targets:r}}default:return null}}function Ee(e,t,n){switch(e.k){case"Ref":return e.n===t?Zn(n):e;case"Member":if(pt(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:pt(e.obj)?Ee(e.obj,t,n):e.obj,index:pt(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 Np(e,t,n,r){if(e==="Each"){if(t.length<3)return[];const i=le(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)},p=le(d,g,r);return r&&Ke(p)?cn(p,g,r):p})}return null}function mi(e,t,n,r,i){if(e==null||typeof e!="object")return e;if(pt(e)){if(e.k==="StateRef"&&r&&_t(r))return{__reactive:"assign",target:e.n,expr:{k:"StateRef",n:"$value"}};const l=le(e,t,n);return Ke(l)?i.recurseElement(l):Array.isArray(l)?l.map(c=>Ke(c)?i.recurseElement(c):c):wp(l)&&!(r&&_t(r))?t.getState(l.target)??null:l}if(typeof e=="string"&&r&&_t(r))return e;if(Array.isArray(e))return e.map(l=>i.recurse(l,r));if(Ke(e))return i.recurseElement(e);const a=e;if("steps"in a&&Array.isArray(a.steps)||"type"in a&&"valueAST"in a)return e;let o=!1;for(const l of Object.values(a))if(typeof l=="object"&&l!==null){o=!0;break}if(o){const l={};for(const[c,d]of Object.entries(a))l[c]=i.recurse(d,r);return l}return e}function 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(p){i[c]=d;const u=p instanceof Error?p.message:String(p);(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 qn=class extends Error{constructor(t){super(`MCP tool error: ${t||"Unknown error"}`);yt(this,"toolErrorText");this.name="McpToolError",this.toolErrorText=t}};function Sp(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 qn(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 Gn=class extends Error{constructor(t,n=[]){super(`[openui] No handler for tool "${t}". Available: ${n.join(", ")||"(none)"}`);yt(this,"toolName");yt(this,"availableTools");this.name="ToolNotFoundError",this.toolName=t,this.availableTools=n}};function sr(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 Cp(e,t,n){const r=n!=null?"::"+sr(n):"";return e+"::"+sr(t)+r}function $p(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[O,C]of t){const P=r.get(C.cacheKey);if(P&&P.data!==void 0)_[O]=P.data;else if(C.prevCacheKey){const D=r.get(C.prevCacheKey);D&&D.data!==void 0?_[O]=D.data:_[O]=C.defaults}else _[O]=C.defaults;C.loading&&(_.__openui_loading.push(O),C.everFetched&&_.__openui_refetching.push(O)),C.error&&_.__openui_errors.push(C.error)}for(const[O,C]of n)_[O]=C.result,C.error&&_.__openui_errors.push(C.error);try{const O=JSON.stringify(_);if(O===o)return!1;a=_,o=O}catch{a=_,o=""}return!0}function g(){for(const _ of[...i])_()}async function p(_,O){if(!e)return;const C=t.get(O);if(!C)return;const P=_,D=C.toolName,S=C.args;let T=r.get(P);T?T.inFlight=!0:(T={data:void 0,inFlight:!0},r.set(P,T)),C.loading=!0,d(),g();try{const L=await e.callTool(D,S??{});if(l)return;const A=t.get(O);if(!A||A.cacheKey!==P){T.inFlight=!1;return}if(T.data=L??null,A.everFetched=!0,A.error=void 0,A.prevCacheKey&&A.prevCacheKey!==P){const I=A.prevCacheKey;A.prevCacheKey=void 0,u(I)}}catch(L){const A=t.get(O);A&&A.cacheKey===P&&(L instanceof Gn?A.error={source:"query",code:"tool-not-found",message:`Query tool "${D}" not found`,statementId:O,component:"Query",toolName:D,hint:L.availableTools.length?`Available tools: ${L.availableTools.join(", ")}`:void 0}:L instanceof qn?A.error={source:"query",code:"mcp-error",message:`Query "${D}" returned an error: ${L.toolErrorText}`,statementId:O,component:"Query",toolName:D}:A.error={source:"query",code:"tool-error",message:`Query "${D}" failed: ${L instanceof Error?L.message:String(L)}`,statementId:O,component:"Query",toolName:D}),console.error(`Query "${D}" failed:`,L)}finally{T.inFlight=!1;const L=t.get(O);L&&L.cacheKey===P?(L.loading=!1,d()&&g(),L.needsRefetch&&(L.needsRefetch=!1,p(L.cacheKey,O))):d()&&g()}}function u(_){for(const O of t.values())if(O.cacheKey===_||O.prevCacheKey===_)return;r.delete(_)}function h(_){if(l)return;const O=new Set(_.map(C=>C.statementId));for(const[C,P]of t)O.has(C)||(P.timer&&clearInterval(P.timer),t.delete(C),u(P.cacheKey),P.prevCacheKey&&u(P.prevCacheKey));for(const C of _){if(!C.complete)continue;const P=Cp(C.toolName,C.args,C.deps),D=t.get(C.statementId);D?(D.cacheKey!==P&&(D.prevCacheKey=D.cacheKey),D.toolName=C.toolName,D.args=C.args,D.defaults=C.defaults,D.cacheKey=P):t.set(C.statementId,{toolName:C.toolName,args:C.args,defaults:C.defaults,cacheKey:P,loading:!1,everFetched:!1,refreshInterval:0,needsRefetch:!1});const S=t.get(C.statementId),T=r.get(P),L=T&&T.data!==void 0&&!T.inFlight;e&&!L&&!(T!=null&&T.inFlight)&&p(P,C.statementId);const A=C.refreshInterval??0;A!==S.refreshInterval&&(S.timer&&(clearInterval(S.timer),S.timer=void 0),A>0&&(S.timer=setInterval(()=>{var I;l||!e||(I=r.get(S.cacheKey))!=null&&I.inFlight||p(S.cacheKey,C.statementId)},A*1e3)),S.refreshInterval=A)}d()&&g()}function v(_){const O=t.get(_);if(!O)return null;const C=r.get(O.cacheKey);if(C&&C.data!==void 0)return C.data;if(O.prevCacheKey){const P=r.get(O.prevCacheKey);if(P&&P.data!==void 0)return P.data}return O.defaults}function y(_){var O;return((O=t.get(_))==null?void 0:O.loading)??!1}function j(){for(const _ of t.values())if(_.loading)return!0;return!1}function f(_){var C;if(l||!e)return;const O=_!=null&&_.length?_.filter(P=>t.has(P)):[...t.keys()];for(const P of O){const D=t.get(P);D&&((C=r.get(D.cacheKey))!=null&&C.inFlight?D.needsRefetch=!0:p(D.cacheKey,P))}}function b(_){const O=new Set(_.map(C=>C.statementId));for(const C of n.keys())O.has(C)||n.delete(C);for(const C of _){const P=n.get(C.statementId);P?P.toolName!==C.toolName&&(P.toolName=C.toolName,P.result={status:"idle",data:null,error:null},P.error=void 0):n.set(C.statementId,{toolName:C.toolName,result:{status:"idle"}})}d()&&g()}async function x(_,O,C){if(l||!e)return!1;const P=n.get(_);if(!P||P.result.status==="loading")return!1;const D=c;P.result={status:"loading"},d(),g();let S=!1;try{const T=await e.callTool(P.toolName,O);if(l||D!==c)return!1;P.result={status:"success",data:T},P.error=void 0,S=!0}catch(T){if(l||D!==c)return!1;const L=T instanceof Error?T.message:String(T);P.result={status:"error",error:L},T instanceof Gn?P.error={source:"mutation",code:"tool-not-found",message:`Mutation tool "${P.toolName}" not found`,statementId:_,component:"Mutation",toolName:P.toolName,hint:T.availableTools.length?`Available tools: ${T.availableTools.join(", ")}`:void 0}:T instanceof qn?P.error={source:"mutation",code:"mcp-error",message:`Mutation "${P.toolName}" returned an error: ${T.toolErrorText}`,statementId:_,component:"Mutation",toolName:P.toolName}:P.error={source:"mutation",code:"tool-error",message:`Mutation "${P.toolName}" failed: ${L}`,statementId:_,component:"Mutation",toolName:P.toolName}}return d(),g(),S&&(C!=null&&C.length)&&f(C),S}function k(_){var O;return((O=n.get(_))==null?void 0:O.result)??null}function E(_){return i.add(_),()=>i.delete(_)}function w(){return a}function R(){l=!1}function M(){l=!0,c++,i.clear();for(const _ of t.values())_.timer&&(clearInterval(_.timer),_.timer=void 0),_.loading=!1,_.needsRefetch=!1;n.clear()}return{evaluateQueries:h,getResult:v,isLoading:y,isAnyLoading:j,invalidate:f,registerMutations:b,fireMutation:x,getMutationResult:k,subscribe:E,getSnapshot:w,activate:R,dispose:M}}function _p(){const e=new Map,t=new Set;let n={};function r(){const p=[...t];for(const u of p)u()}function i(){n=Object.fromEntries(e)}function a(p){return e.get(p)}function o(p,u){const h=e.get(p);if(!Object.is(h,u)){if(u&&h&&typeof u=="object"&&typeof h=="object"&&!Array.isArray(u)&&!Array.isArray(h)){const v=Object.keys(u),y=Object.keys(h);if(v.length===y.length&&v.every(j=>Object.is(u[j],h[j])))return}e.set(p,u),i(),r()}}function l(p){return t.add(p),()=>{t.delete(p)}}function c(){return n}function d(p,u){for(const h of Object.keys(u))e.set(h,u[h]);for(const h of Object.keys(p))e.has(h)||e.set(h,p[h]);i(),r()}function g(){e.clear(),t.clear(),n={}}return{get:a,set:o,subscribe:l,getSnapshot:c,initialize:d,dispose:g}}function Me(e){return Hd(e)}function Ep(e){return ap(e)}const vi=m.createContext(null);function bi(){const e=m.useContext(vi);if(!e)throw new Error("useOpenUI must be used within a <Renderer /> component.");return e}function Ap(){return bi().renderNode}m.createContext(void 0);function En(e){return e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e?e.value:e}function Rp({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:o,onError:l},c){const d=m.useMemo(()=>yp(t.toJSONSchema(),t.root),[t]),g=m.useRef(null),p=m.useMemo(()=>{if(g.current=null,!e)return null;try{return d.set(e)}catch(A){return g.current={source:"parser",code:"parse-exception",message:`Parser crashed: ${A instanceof Error?A.message:String(A)}`,hint:"The response may contain syntax the parser cannot handle"},null}},[d,e]),u=m.useMemo(()=>_p(),[]),h=m.useMemo(()=>$p(o??null),[o]);m.useEffect(()=>(h.activate(),()=>h.dispose()),[h]);const v=m.useRef(Symbol());m.useEffect(()=>{if(!(p!=null&&p.stateDeclarations)&&!a)return;const A=`${JSON.stringify(p==null?void 0:p.stateDeclarations)}::${JSON.stringify(a)}`;if(v.current===A)return;v.current=A;const I={};if(a)for(const[$,W]of Object.entries(a))$.startsWith("$")?I[$]=W:u.set($,W);u.initialize((p==null?void 0:p.stateDeclarations)??{},I)},[p==null?void 0:p.stateDeclarations,u,a]);const y=m.useSyncExternalStore(u.subscribe,u.getSnapshot,u.getSnapshot),j=m.useSyncExternalStore(h.subscribe,h.getSnapshot,h.getSnapshot),f=m.useMemo(()=>({getState:A=>En(u.get(A)),resolveRef:A=>{const I=h.getMutationResult(A);return I||h.getResult(A)}}),[u,h]);m.useEffect(()=>{if(n)return;const A=((p==null?void 0:p.queryStatements)??[]).map(I=>{const $={};if(I.deps)for(const W of I.deps)$[W]=y[W];return{statementId:I.statementId,toolName:I.toolAST?le(I.toolAST,f):"",args:I.argsAST?le(I.argsAST,f):null,defaults:I.defaultsAST?le(I.defaultsAST,f):null,refreshInterval:I.refreshAST?le(I.refreshAST,f):void 0,deps:Object.keys($).length>0?$:void 0,complete:I.complete}});h.evaluateQueries(A)},[n,p==null?void 0:p.queryStatements,f,h,y]),m.useEffect(()=>{if(n)return;const A=((p==null?void 0:p.mutationStatements)??[]).map(I=>({statementId:I.statementId,toolName:I.toolAST?le(I.toolAST,f):""}));h.registerMutations(A)},[n,p==null?void 0:p.mutationStatements,f,h]);const b=m.useRef({onAction:r,onStateUpdate:i,onError:l});b.current={onAction:r,onStateUpdate:i,onError:l};const x=m.useRef(p);x.current=p;const k=m.useRef(null);m.useEffect(()=>(k.current=u.getSnapshot(),u.subscribe(()=>{var I,$;const A=u.getSnapshot();A!==k.current&&(k.current=null,($=(I=b.current).onStateUpdate)==null||$.call(I,A))})),[u]);const E=m.useCallback((A,I)=>{if(!A)return En(u.get(I));const $=u.get(A);if(!(!$||typeof $!="object"||Array.isArray($)))return En($[I])},[u]),w=m.useCallback((A,I,$,W,q=!0)=>{var oe,ee;const K={value:W,componentType:I};if(!A)u.set($,K);else{const F=u.get(A),Z=F&&typeof F=="object"&&!Array.isArray(F)?F:{};u.set(A,{...Z,[$]:K})}q&&((ee=(oe=b.current).onStateUpdate)==null||ee.call(oe,u.getSnapshot()))},[u]),R=m.useCallback(A=>{if(A){const I=u.get(A);if(I&&typeof I=="object"&&!Array.isArray(I))return{[A]:I}}return u.getSnapshot()},[u]),M=m.useCallback(async(A,I,$)=>{var oe,ee,F;const W=R(I),{onAction:q}=b.current;if($&&!("steps"in $)){const Z=$.type||Zt.ContinueConversation,H={...$.params||{}};$.url&&(H.url=$.url),$.context&&(H.context=$.context),q==null||q({type:Z,params:H,humanFriendlyMessage:A,formState:W,formName:I});return}const K=$;if(K!=null&&K.steps){for(const Z of K.steps)switch(Z.type){case De.Run:if(Z.refType==="mutation"){const H=(ee=(oe=x.current)==null?void 0:oe.mutationStatements)==null?void 0:ee.find(xe=>xe.statementId===Z.statementId),te=H!=null&&H.argsAST?le(H.argsAST,f):{};if(!await h.fireMutation(Z.statementId,te))return}else h.invalidate([Z.statementId]);break;case De.ToAssistant:q==null||q({type:Zt.ContinueConversation,params:Z.context?{context:Z.context}:{},humanFriendlyMessage:Z.message,formState:W,formName:I});break;case De.OpenUrl:q==null||q({type:Zt.OpenUrl,params:{url:Z.url},humanFriendlyMessage:"",formState:W,formName:I});break;case De.Set:{if(!Z.valueAST){console.warn(`[openui] Set action for ${Z.target} has no valueAST — skipping`);break}const H=le(Z.valueAST,f);u.set(Z.target,H);break}case De.Reset:{const H=((F=x.current)==null?void 0:F.stateDeclarations)??{};for(const te of Z.targets)u.set(te,H[te]??null);break}}return}q==null||q({type:Zt.ContinueConversation,params:{},humanFriendlyMessage:A,formState:W,formName:I})},[h,f,R,u]),_=m.useRef([]),O=m.useRef(n);O.current=n;const C=m.useCallback(A=>{O.current||_.current.push(A)},[]),P=m.useMemo(()=>({library:t,renderNode:c,triggerAction:M,isStreaming:n,getFieldValue:E,setFieldValue:w,store:u,evaluationContext:f,reportError:C}),[t,c,n,M,E,w,u,f,C]),D=m.useRef([]),S=m.useMemo(()=>{if(!(p!=null&&p.root))return p;const A=[],I={ctx:f,library:t,store:u,errors:A};try{const $=fi(p.root,I);return D.current=A,{...p,root:$}}catch($){const W=$ instanceof Error?$.message:String($);return A.push({source:"runtime",code:"runtime-error",message:`Prop evaluation failed: ${W}`}),D.current=A,p}},[p,f,t,u,y,j]),T=j.__openui_loading.length>0,L=m.useRef("");return m.useEffect(()=>{var $,W,q,K;if(n){L.current!==""&&(L.current="",(W=($=b.current).onError)==null||W.call($,[]));return}const A=[];g.current&&A.push(g.current),e&&!(p!=null&&p.root)&&!g.current&&A.push({source:"parser",code:"parse-failed",message:p?"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"}(...)`}),(K=(q=p==null?void 0:p.meta)==null?void 0:q.errors)!=null&&K.length&&A.push(...jp(p.meta.errors,t.toJSONSchema(),Object.keys(t.components))),A.push(...D.current),A.push(..._.current),_.current=[],A.push(...j.__openui_errors??[]);const I=JSON.stringify(A);if(I!==L.current){if(L.current=I,b.current.onError)b.current.onError(A);else if(A.length>0)for(const oe of A)console.warn(`[openui] ${oe.source}/${oe.code}: ${oe.message}`)}},[n,e,p,S,j,t]),{result:S,parseResult:p,contextValue:P,isQueryLoading:T}}var Tp=class extends m.Component{constructor(t){super(t);yt(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(m.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(Tp,{componentName:e.typeName,onError:n,children:s.jsx(Op,{el:e,Comp:r})}):null}function Op({el:e,Comp:t}){const n=Ap();return s.jsx(t,{props:e.props,renderNode:n})}let rr=!1;function Pp(){if(rr||typeof document>"u")return;rr=!0;const e=document.createElement("style");e.textContent="@keyframes openui-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }",document.head.appendChild(e)}const Ip=()=>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 zp({response:e,library:t,isStreaming:n=!1,onAction:r,onStateUpdate:i,initialState:a,onParseResult:o,toolProvider:l,queryLoader:c,onError:d}){m.useInsertionEffect(()=>{Pp()},[]);const g=m.useRef(o);g.current=o;const p=m.useRef(l);p.current=l;const u=m.useRef({async callTool(f,b){const x=p.current??null;if(x==null)throw new Error("[openui] toolProvider is null");if(typeof x.callTool=="function")return Sp(await x.callTool({name:f,arguments:b}));const k=x,E=k[f];if(!E)throw new Gn(f,Object.keys(k));return E(b)}}),{result:h,parseResult:v,contextValue:y,isQueryLoading:j}=Rp({response:e,library:t,isStreaming:n,onAction:r,onStateUpdate:i,initialState:a,toolProvider:l!=null?u.current:null,onError:d},yi);return m.useEffect(()=>{var f;(f=g.current)==null||f.call(g,v)},[v]),h!=null&&h.root?s.jsx(vi.Provider,{value:y,children:s.jsxs("div",{style:{position:"relative"},children:[j&&(c??s.jsx(Ip,{})),s.jsx("div",{style:{opacity:j?.7:1,transition:"opacity 0.2s ease"},children:s.jsx(xi,{node:h.root})})]})}):null}m.createContext(null);function Lp(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 Mp=({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(Se.Fragment,{children:t(r)},i)):t(n)]})},Fp=({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]})},Up=({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))}),Dp=({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:cs(t.predicate)}),s.jsx("div",{className:"v10-genui-triple-object",children:Jp(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))})]}),qp=({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:["· ",cs(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))})]}),Gp=({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})]})]}),Bp=({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:Hp(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]})]}),Wp=({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]}),Vp=({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=Lp(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]}),Kp=({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:ir(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??Yp(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:ir(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 cs(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 Jp(e){return cs(e).replace(/\^\^<?.*$/,"").replace(/^"(.+)"$/,"$1")}function ir(e){return e?e.length<=16?e:`${e.slice(0,8)}…${e.slice(-6)}`:""}function Yp(e){return e?e.length>22?`${e.slice(0,12)}…${e.slice(-6)}`:e:""}function Hp(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}const Xp=Me({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:J().optional().describe("Optional top-of-panel title override (defaults to the entity rdfs:label)")}),component:Mp}),eh=Me({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:J().describe("Display name / label of the entity"),typeLabel:J().optional().describe('Human-readable rdf:type label (e.g. "Package", "Pull Request")'),subtitle:J().optional().describe("Short supporting text (e.g. path, author, date)"),chips:Qe(pe({label:J(),value:J(),tone:ft(["default","success","warn","danger","info"]).optional()})).max(6).optional()}),component:Fp}),th=Me({name:"EntityStatsGrid",description:"Grid of numeric stats with labels. Use for summarising counts (files, classes, additions, deletions).",props:pe({stats:Qe(pe({label:J(),value:is([J(),Ge()]),hint:J().optional()})).min(1).max(8)}),component:Up}),nh=Me({name:"TripleTable",description:"Fallback raw-triples table. Use sparingly — only when the entity has no better structured components in this library.",props:pe({heading:J().optional(),rows:Qe(pe({predicate:J(),object:J()})).max(60)}),component:Dp}),sh=Me({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:J().optional(),groups:Qe(pe({typeLabel:J(),icon:J().optional(),items:Qe(pe({label:J(),uri:J().optional(),sub:J().optional()})).max(30)})).max(8)}),component:Zp}),rh=Me({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:J().describe('Human-readable heading (e.g. "Imports", "Affected files")'),predicate:J().optional(),items:Qe(pe({label:J(),uri:J().optional(),sub:J().optional()})).max(40)}),component:qp}),ih=Me({name:"PackageCard",description:"Specialised card for a code:Package entity: name, folder, description, and a mini-stats strip.",props:pe({name:J(),folder:J().optional(),description:J().optional(),fileCount:Ge().optional(),classCount:Ge().optional(),functionCount:Ge().optional(),interfaceCount:Ge().optional()}),component:Gp}),ah=Me({name:"FileCard",description:"Specialised card for a code:File entity: path, language, line count, owning package.",props:pe({path:J(),language:J().optional(),lineCount:Ge().optional(),packageName:J().optional()}),component:Bp}),oh=Me({name:"DecisionCard",description:"Specialised card for a decisions:Decision entity: title, status badge, date, context/outcome quoted sections.",props:pe({title:J(),status:ft(["proposed","accepted","rejected","superseded"]).optional(),date:J().optional(),context:J().optional(),outcome:J().optional(),consequences:J().optional(),alternatives:J().optional()}),component:Wp}),lh=Me({name:"PRCard",description:"Specialised card for a github:PullRequest entity: title + #number, state, author, merged badge, body preview.",props:pe({title:J(),number:Ge().optional(),state:ft(["open","closed","merged"]).optional(),author:J().optional(),mergedAt:J().optional(),body:J().optional(),url:J().optional()}),component:Vp}),ch=Me({name:"TaskCard",description:"Specialised card for a tasks:Task entity: title, status chip, priority, assignee, estimate.",props:pe({title:J(),status:ft(["todo","in_progress","blocked","done","cancelled"]).optional(),priority:ft(["p0","p1","p2","p3"]).optional(),assignee:J().optional(),estimate:Ge().optional()}),component:Kp}),uh=Me({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:J().optional(),blockNumber:is([J(),Ge()]).optional(),chain:J().optional()}).optional(),consensus:pe({signers:Qe(pe({did:J(),label:J().optional(),reputation:Ge().optional(),signature:J().optional()})).max(10).optional(),quorum:J().optional().describe('e.g. "3 of 5"')}).optional(),knowledgeAsset:pe({ual:J().optional(),contentHash:J().optional(),tracLocked:J().optional(),tokenId:J().optional()}).optional(),timeline:Qe(pe({label:J(),at:J()})).max(6).optional()}),component:Qp}),ji=Ep({components:[Xp,eh,th,nh,sh,rh,ih,ah,oh,lh,ch,uh],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 An=null;function dh(){return An===null&&(An=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."]})),An}async function*ph(e){const t=await fetch("/api/genui/render",{method:"POST",headers:{"Content-Type":"application/json",...dn()},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=ar(c);d&&(yield d)}}if(i.trim()){const a=ar(i);a&&(yield a)}}finally{n.releaseLock()}}function ar(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 hh=({contextGraphId:e,entityUri:t,placeholder:n,fallback:r})=>{const[i,a]=Se.useState(""),[o,l]=Se.useState(!0),[c,d]=Se.useState(null);return Se.useEffect(()=>{const g=new AbortController;let p="";return a(""),d(null),l(!0),(async()=>{try{const u=dh();for await(const h of ph({contextGraphId:e,entityUri:t,libraryPrompt:u,signal:g.signal}))if(h.type==="delta")p+=h.text,a(p);else if(h.type==="final")h.content&&(p=h.content,a(h.content));else if(h.type==="error"){d(h.error);break}else if(h.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(fh,{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(zp,{response:i,library:ji,isStreaming:o})})},mh="LLM not configured",fh=({error:e})=>{const t=Kn(r=>r.openTab);return e.includes(mh)?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 or({entity:e,profile:t}){const n=m.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 gh({entity:e,contextGraphId:t,onVerified:n}){const r=et(),[i,a]=m.useState(!1),[o,l]=m.useState(null),[c,d]=m.useState(null),[g,p]=m.useState(null),u=e.trustLevel,h=m.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=m.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"||!h)return null;const y=u==="working"?{kind:"promote",label:h.promoteLabel??"Promote to Shared Memory",hint:h.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:h.publishLabel??"Verify on DKG",hint:h.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."},j=async()=>{if(y.disabled)return;a(!0),p(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 E=y.kind==="promote"?en(x,k):null,w=E?E.message:(k==null?void 0:k.message)??"Action failed";p(w)}finally{a(!1)}},f=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:j,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"&&f(o)&&(()=>{var E,w;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?` (${ra})`:"":" (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]})]}),((w=(E=o.kas)==null?void 0:E[0])==null?void 0:w.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 vh({entity:e,allEntities:t,allTriples:n,onNavigate:r,onClose:i,contextGraphId:a,onRefresh:o,onOpenAgent:l}){const[c,d]=m.useState("content"),g=fr(S=>S.theme),p=et(),u=Ot(),{icon:h,type:v}=pn(e,p),y=ta(e),j=Vn(e),f=j?(u==null?void 0:u.get(j))??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=He(e.trustLevel,1),E=m.useMemo(()=>{const S=[];for(const[,T]of t)for(const L of T.connections)L.targetUri===e.uri&&S.push({pred:ct(L.predicate),entity:T});return S},[e.uri,t]),w=m.useMemo(()=>n.filter(S=>$e(S.subject)===e.uri||$e(S.object)===e.uri),[e.uri,n]),R=m.useMemo(()=>na(e.uri,n,1),[e.uri,n]),M=m.useMemo(()=>{const S=new Set;for(const T of t.values())sa(T)&&S.add($e(T.uri));return S},[t]),_=m.useMemo(()=>new Set([$e(e.uri)]),[e.uri]),O=m.useMemo(()=>Ht(R,M,{focalSubjects:_}),[R,M,_]),C=m.useMemo(()=>{const S=nt[e.trustLevel];return{labelMode:"humanized",renderer:"2d",labels:Cr({minZoomForLabels:.2}),style:{namespaceColors:Sr(S),defaultNodeColor:S,defaultEdgeColor:"#475569",edgeWidth:1,fontSize:11},hexagon:{baseSize:7,minSize:4,maxSize:10,scaleWithDegree:!0},focus:{maxNodes:500,hops:999}}},[e.trustLevel]),P=m.useMemo(()=>({name:`entity-${e.uri}-${g}`,palette:g,focal:{uri:e.uri,sizeMultiplier:2.4}}),[e.uri,g]),D=w.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:[h," ",e.label,s.jsx("span",{className:`v10-trust-badge ${b}`,children:x})]}),s.jsxs("div",{className:"v10-ka-ual",children:[e.uri," · ",v," · ",D," triples"]})]}),(f||j)&&s.jsxs("div",{className:"v10-ka-header-author",children:[s.jsx("div",{className:"v10-ka-header-author-label",children:"Proposed by"}),s.jsx(mt,{agent:f??void 0,fallbackUri:j??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=>p==null?void 0:p.forType(T)).find(T=>T==null?void 0:T.detailHint)||!(p!=null&&p.contextGraphId)?null:s.jsx("div",{className:"v10-ka-section",children:s.jsx(hh,{contextGraphId:p.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(([S,T])=>s.jsxs("div",{className:"v10-ka-prop",children:[s.jsx("span",{className:"v10-ka-prop-key",children:ct(S)}),s.jsx("span",{className:"v10-ka-prop-val",children:T.join(", ")})]},S))]}),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((S,T)=>{const L=t.get(S.targetUri);return s.jsxs("button",{className:"v10-ka-conn",onClick:()=>r(S.targetUri),children:[s.jsx("span",{className:"v10-ka-conn-pred",children:ct(S.predicate)}),s.jsx("span",{className:"v10-ka-conn-arrow",children:"→"}),s.jsx("span",{className:"v10-ka-conn-target",children:S.targetLabel}),L&&s.jsx(or,{entity:L,profile:p})]},T)})]}),E.length>0&&s.jsxs("div",{className:"v10-ka-section",children:[s.jsxs("div",{className:"v10-ka-section-title",children:["Referenced by (",E.length,")"]}),E.map((S,T)=>s.jsxs("button",{className:"v10-ka-conn",onClick:()=>r(S.entity.uri),children:[s.jsx("span",{className:"v10-ka-conn-target",children:S.entity.label}),s.jsx(or,{entity:S.entity,profile:p}),s.jsx("span",{className:"v10-ka-conn-arrow",children:"→"}),s.jsx("span",{className:"v10-ka-conn-pred",children:S.pred})]},T))]}),s.jsxs("div",{className:"v10-ka-meta",children:[s.jsxs("span",{className:"v10-ka-meta-item",children:[h," ",v]}),s.jsxs("span",{className:"v10-ka-meta-item",children:[D," 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:w.slice(0,50).map((S,T)=>s.jsxs("tr",{children:[s.jsx("td",{title:S.subject,children:ct(S.subject)}),s.jsx("td",{title:S.predicate,children:ct(S.predicate)}),s.jsx("td",{title:S.object,children:S.object.startsWith('"')?vr(S.object).slice(0,60):ct(S.object)})]},T))})]}),s.jsxs("div",{style:{fontSize:10,color:"var(--text-tertiary)",fontFamily:"var(--font-mono)",padding:"6px 8px"},children:[Math.min(w.length,50)," of ",w.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:S=>O.length>0?s.jsx(m.Suspense,{fallback:s.jsx("span",{className:"v10-graph-placeholder",children:"Loading graph..."}),children:s.jsx(Yn,{data:O,format:"triples",options:C,viewConfig:P,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}:${S?"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(Bo,{contextGraphId:a,entityUri:e.uri,enabled:e.trustLevel==="verified"}),s.jsx("div",{className:"v10-ka-section-title",children:"Provenance Trail"}),s.jsx(bh,{entity:e}),s.jsx(gh,{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:D})]}),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 bh({entity:e}){const t=Ot(),n=o=>{const l=ia(e,o),c=aa(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(Rn,{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(Rn,{toneClass:"shared",title:"Promoted to Shared Working Memory",actionWord:"Promoted",agent:i.agent,agentUri:i.uri,at:i.at}),s.jsx(Rn,{toneClass:"created",title:"Created in Working Memory",actionWord:"Created",agent:r.agent,agentUri:r.uri,at:r.at})]})}function Rn({toneClass:e,title:t,actionWord:n,agent:r,agentUri:i,at:a}){const o=a?oa(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(mt,{agent:r??void 0,fallbackUri:i??void 0,size:"sm"})]})]})}function lr(){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 yh({contextGraphId:e,memory:t,onNodeClick:n,onSelectSubGraph:r}){const i=et(),[a,o]=m.useState([]),[l,c]=m.useState(!0),[d,g]=m.useState(null);m.useEffect(()=>{let w=!1;return c(!0),g(null),Ct.fetchSubGraphs(e).then(R=>{w||o(R.subGraphs??[])}).catch(R=>{w||g(R instanceof Error?R.message:"Failed to load subgraphs")}).finally(()=>{w||c(!1)}),()=>{w=!0}},[e]);const{total:p}=Wn(t),u=Object.values(t.layerStatus??{}),h=t.loading||u.some(w=>w==="loading"),v=t.error!==null||t.partial||u.some(w=>w==="error"),y=m.useMemo(()=>{const w=new Map;for(const R of t.entityList){const M=$e(R.uri);for(const _ of R.subGraphs){let O=w.get(_);O||(O=new Set,w.set(_,O)),O.add(M)}}return w},[t.entityList]),{triplesBySubGraph:j,tripleCountBySubGraph:f}=m.useMemo(()=>{const w=new Map;for(const _ of t.allTriples){if(!_.subGraph)continue;let O=w.get(_.subGraph);O||(O=[],w.set(_.subGraph,O)),O.push(_)}for(const _ of t.allTriples)if(!_.subGraph){for(const[O,C]of y)if(On(_,{slug:O,isRoot:!1,scopedUris:C})){let P=w.get(O);P||(P=[],w.set(O,P)),P.push(_)}}const R=new Map,M=new Map;for(const[_,O]of w){const P=gs(O,t.entities).map(D=>({subject:D.subject,predicate:D.predicate,object:D.object}));M.set(_,P.length),R.set(_,js(P))}return{triplesBySubGraph:R,tripleCountBySubGraph:M}},[t.allTriples,t.entities,y]),b=m.useMemo(()=>{const w=new Map;for(const R of t.entityList)for(const M of R.subGraphs){let _=w.get(M);_||(_={wm:0,swm:0,vm:0},w.set(M,_)),R.trustLevel==="verified"?_.vm++:R.trustLevel==="shared"?_.swm++:_.wm++}return w},[t.entityList]),x=m.useMemo(()=>{const w=new Map;for(const R of t.entityList){const M=$e(R.uri);for(const _ of R.subGraphs){let O=w.get(_);O||(O=new Map,w.set(_,O)),O.set(M,R.trustLevel),M!==R.uri&&O.set(R.uri,R.trustLevel)}}return w},[t.entityList]),k=m.useMemo(()=>a.filter(Qn).map(w=>{const R=(i==null?void 0:i.forSubGraph(w.name))??{},M=j.get(w.name)??[],_=y.get(w.name)??new Set,O=x.get(w.name)??new Map;return{slug:w.name,icon:R.icon??"•",color:R.color??"#64748b",displayName:R.displayName??w.name,description:R.description,rank:R.rank??99,entityCount:_.size>0?_.size:w.entityCount,tripleCount:f.get(w.name)??0,triples:Ht(M,_),layerCounts:b.get(w.name)??{wm:0,swm:0,vm:0},entityTrustByUri:O}}).sort((w,R)=>w.rank-R.rank),[a,i,j,f,b,y,x]),E=m.useMemo(()=>{const w=[],R=new Set,M=new Map;let _=0,O=0,C=0;for(const I of t.entityList){if(I.subGraphs.size>0)continue;w.push(I);const $=$e(I.uri);R.add($),M.set($,I.trustLevel),$!==I.uri&&M.set(I.uri,I.trustLevel),I.trustLevel==="verified"?C++:I.trustLevel==="shared"?O++:_++}const P=t.allTriples.filter(I=>!I.subGraph),D=gs(P,t.entities).map(I=>({subject:I.subject,predicate:I.predicate,object:I.object})),S=D.length,T=Ht(D,R),L=js(T),A=(i==null?void 0:i.forSubGraph(Ve))??{};return{slug:Ve,icon:A.icon??"⊘",color:A.color??"#64748b",displayName:A.displayName??"Root",description:A.description,rank:999,entityCount:w.length,tripleCount:S,triples:L,layerCounts:{wm:_,swm:O,vm:C},entityTrustByUri:M}},[t.entityList,t.allTriples,t.entities,i]);return l&&k.length===0?s.jsx(je,{compact:!0,icon:"#",title:"Loading subgraphs...",className:"v10-sgov-state"}):d&&k.length===0?s.jsx(je,{icon:"!",title:"Couldn't load subgraphs.",description:"Refresh the page to try again.",tone:"danger",className:"v10-sgov-state"}):k.length===0&&E.entityCount===0?s.jsx(je,{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 · ",p," triples"]})]}),s.jsxs("div",{className:"v10-sgov-grid",children:[k.map(w=>s.jsx(cr,{card:w,isHydrating:h,isFailedOrPartial:v,onNodeClick:n,onOpen:()=>r(w.slug)},w.slug)),s.jsx(cr,{card:E,isHydrating:h,isFailedOrPartial:v,onNodeClick:n,onOpen:()=>r(Ve),variant:"root"},Ve)]})]})}function cr({card:e,isHydrating:t=!1,isFailedOrPartial:n=!1,onNodeClick:r,onOpen:i,variant:a}){const o=m.useMemo(()=>{const d={};for(const[g,p]of e.entityTrustByUri)d[g]=nt[p];return d},[e.entityTrustByUri]),l=m.useMemo(()=>({labelMode:"humanized",renderer:"2d",labels:Cr({minZoomForLabels:.8}),style:{classColors:ua,predicateColors:ca,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(m.Suspense,{fallback:s.jsx("div",{className:"v10-sgov-card-empty",children:"Loading…"}),children:s.jsx(Yn,{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 xh({items:e,color:t,onSelectEntity:n,scrollKey:r}){const i=et(),a=Ot(),o=m.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(je,{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:la(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:p}=pn(d,i),u=Vn(d),h=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:p}),s.jsx("span",{className:"v10-subgraph-timeline-item-label",children:d.label}),(h||u)&&s.jsx(mt,{agent:h??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 jh({slug:e,rawMemory:t,contextGraphId:n,onNodeClick:r,onSelectEntity:i,activeTab:a,onTabChange:o,initialLayer:l,initialEnabledLayers:c,onEnabledLayersChange:d,onOpenQueryCatalog:g}){const p=et(),u=p==null?void 0:p.forSubGraph(e),h=(p==null?void 0:p.chipsFor(e))??[],v=(p==null?void 0:p.savedQueryCatalogsFor(e))??[],y=u==null?void 0:u.timelinePredicate,[j,f]=m.useState("items"),b=a??j,x=b==="timeline"&&!y?"items":b,k=o??f,[E,w]=m.useState(u!=null&&u.timelinePredicate?"created-desc":"triples");m.useEffect(()=>{w(u!=null&&u.timelinePredicate?"created-desc":"triples")},[e,u==null?void 0:u.timelinePredicate]);const R=m.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]),[M,_]=m.useState(R);m.useEffect(()=>{d==null||d(M)},[M,d]);const[O,C]=m.useState(new Map),[P,D]=m.useState(null),[S,T]=m.useState(null),[L,A]=m.useState(!1),[I,$]=m.useState(null),W=e===Ve,q=m.useMemo(()=>{const U=[];for(const V of t.entityList)(W?V.subGraphs.size===0:V.subGraphs.has(e))&&U.push(V);return U},[t.entityList,e,W]),K=m.useMemo(()=>new Set(q.map(U=>U.uri)),[q]),oe=m.useMemo(()=>t.graphTriples.filter(U=>On(U,{slug:e,isRoot:W,scopedUris:K})),[t.graphTriples,K,e,W]),ee=m.useMemo(()=>{let U=0,V=0,Q=0;for(const ae of q)ae.trustLevel==="verified"?Q++:ae.trustLevel==="shared"?V++:U++;return{wm:U,swm:V,vm:Q,total:q.length}},[q]),F=m.useMemo(()=>{if(M.size!==1)return null;const U=M.values().next().value;return U==="verified"?"vm":U==="shared"?"swm":U==="working"?"wm":null},[M]),Z=m.useMemo(()=>{let U=q;if(M.size<3&&(U=U.filter(V=>M.has(V.trustLevel))),O.size>0)for(const V of h){const Q=O.get(V.slug);!Q||Q.size===0||(U=U.filter(ae=>{const re=ae.properties.get(V.predicate);return!re||re.length===0?!1:re.some(ue=>Q.has(ue))}))}return S&&(U=U.filter(V=>S.has(V.uri))),U},[q,M,O,h,S]),H=m.useMemo(()=>new Set(Z.map(U=>U.uri)),[Z]),te=m.useMemo(()=>Z.length===q.length?oe:oe.filter(U=>H.has(U.subject)||H.has(U.object)),[oe,q,Z,H]),Te=m.useMemo(()=>{if(!F)return null;const U=F==="vm"?"verified":F==="swm"?"shared":"working",V=q.filter(ue=>{if(!ue.layers.has(U))return!1;if(O.size>0)for(const Be of h){const Fe=O.get(Be.slug);if(!Fe||Fe.size===0)continue;const We=ue.properties.get(Be.predicate);if(!We||We.length===0||!We.some(bt=>Fe.has(bt)))return!1}return!(S&&!S.has(ue.uri))}),Q=new Set(V.map(ue=>ue.uri)),ae=new Set,re=[];for(const ue of t.allTriples){if(ue.layer!==U||!On(ue,{slug:e,isRoot:W,scopedUris:K,requireResourceObject:!0})||!(Q.has(ue.subject)||Q.has(ue.object)))continue;const Be=`${ue.subject}|${ue.predicate}|${ue.object}`;ae.has(Be)||(ae.add(Be),re.push({subject:ue.subject,predicate:ue.predicate,object:ue.object,subGraph:ue.subGraph}))}return re},[F,t.allTriples,K,e,W,q,h,O,S])??te,B=m.useMemo(()=>{if(F){const U=F==="vm"?"verified":F==="swm"?"shared":"working";return q.filter(V=>{if(!V.layers.has(U))return!1;if(O.size>0)for(const Q of h){const ae=O.get(Q.slug);if(!ae||ae.size===0)continue;const re=V.properties.get(Q.predicate);if(!re||re.length===0||!re.some(ue=>ae.has(ue)))return!1}return!(S&&!S.has(V.uri))})}return Z},[F,q,Z,h,O,S]),se=m.useMemo(()=>B.map(U=>({uri:U.uri,label:U.label})),[B]),ie=m.useMemo(()=>{if(F)return;const U={};for(const V of B){U[V.uri]=nt[V.trustLevel];const Q=$e(V.uri);Q!==V.uri&&(U[Q]=nt[V.trustLevel])}return U},[F,B]),Ce=M.size===3?"All layers":F?Ie[F].title:Array.from(M).map(U=>Ie[U==="verified"?"vm":U==="shared"?"swm":"wm"].trustLabel).join(" + "),fe=m.useMemo(()=>{if(!y)return[];const U=[];for(const V of Z){const Q=Vt(V,y);Q!=null&&U.push({entity:V,date:new Date(Q)})}return U.sort((V,Q)=>V.date.getTime()-Q.date.getTime()),U},[Z,y]),ge=m.useMemo(()=>{const U=[...Z];if((E==="created-desc"||E==="created-asc")&&y){const V=E==="created-desc"?-1:1;return U.sort((Q,ae)=>{const re=Vt(Q,y),ue=Vt(ae,y);return re==null&&ue==null?0:re==null?1:ue==null?-1:(re-ue)*V}),U}return E==="label"?(U.sort((V,Q)=>(V.label??"").localeCompare(Q.label??"")),U):(U.sort((V,Q)=>{const ae=V.tripleCount??0;return(Q.tripleCount??0)-ae}),U)},[Z,E,y]),_e=E==="created-desc"?"newest first · click to open":E==="created-asc"?"oldest first · click to open":E==="label"?"A → Z · click to open":"sorted by triples · click to open",be=m.useCallback(U=>{_(V=>{const Q=new Set(V);return Q.has(U)?Q.size>1&&Q.delete(U):Q.add(U),Q})},[]),Ze=m.useCallback((U,V)=>{C(Q=>{const ae=new Map(Q),re=new Set(ae.get(U)??[]);return re.has(V)?re.delete(V):re.add(V),re.size===0?ae.delete(U):ae.set(U,re),ae})},[]),de=m.useCallback(()=>{D(null),T(null),$(null)},[]),Oe=m.useCallback(async U=>{var V;if((((V=U.parameters)==null?void 0:V.length)??0)>0){g==null||g();return}A(!0),$(null),D(U.slug);try{const Q=kt(U),re=(await Nr(Q.sparql,{contextGraphId:n,view:Q.view,subGraphName:Q.subGraphName,...Q.view==="working-memory"?{includeContextGraphPartitions:!0}:{}},{timeoutMs:null,maxResponseBytes:null})).result,ue=re.type;if(ue!=="bindings")throw new Error(`${U.name} returns ${ue==="boolean"?"an ASK result":"graph quads"} and cannot be used as an entity filter. Open it in Query Catalogue instead.`);const Be=re.bindings,Fe=U.resultColumn||"uri",We=new Set;for(const bt of Be){const lt=bt[Fe];if(!lt)continue;const Pe=typeof lt=="string"?lt:String(lt),Mt=Pe.startsWith("<")&&Pe.endsWith(">")?Pe.slice(1,-1):Pe;We.add(Mt)}T(We)}catch(Q){$((Q==null?void 0:Q.message)??String(Q)),T(null),D(null)}finally{A(!1)}},[n,g]),ye=(u==null?void 0:u.color)??(W?"var(--text-tertiary)":"#64748b"),gt=(u==null?void 0:u.icon)??"•",vt=(u==null?void 0:u.displayName)??e,zt=u==null?void 0:u.description;m.useEffect(()=>{_(R),C(new Map),de()},[e,de,R]),m.useEffect(()=>{a||f("items")},[e,a]),m.useEffect(()=>{b!==x&&k(x)},[b,x,k]);const ot=!(M.size===R.size&&[...M].every(U=>R.has(U)))||O.size>0||!!S,bn=()=>{_(new Set(R)),C(new Map),de()};return s.jsxs("div",{className:"v10-layer-detail v10-subgraph-detail",style:{"--sg-color":ye},children:[s.jsxs("div",{className:"v10-subgraph-detail-header",children:[s.jsx("span",{className:"v10-subgraph-detail-icon",style:{color:ye},children:gt}),s.jsxs("div",{className:"v10-subgraph-detail-title-wrap",children:[s.jsx("div",{className:"v10-subgraph-detail-title",children:vt}),zt&&s.jsx("div",{className:"v10-subgraph-detail-desc",children:zt})]}),s.jsx(wi,{counts:{wm:ee.wm,swm:ee.swm,vm:ee.vm},activeLayers:M,onClickLayer:be,compact:!0})]}),s.jsxs("div",{className:"v10-subgraph-cross-layer",children:[s.jsx("div",{className:"v10-subgraph-cross-layer-lede",children:W?"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":M.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:ee.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":M.has("shared"),onClick:()=>be("shared"),title:F==="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:ee.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":M.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:ee.vm})]})]}),s.jsxs("span",{className:`v10-subgraph-active-layer-pill${M.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:Ce})]})]}),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(Se.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(V=>{var re;const Q=P===V.slug,ae=(((re=V.parameters)==null?void 0:re.length)??0)>0;return s.jsxs("button",{type:"button",className:`v10-subgraph-savedquery${Q?" active":""}`,onClick:()=>Q?de():Oe(V),title:ae?`${V.description||V.name} Open Query Catalogue to enter parameters.`:V.description||V.name,disabled:L&&!Q,children:[s.jsx("span",{className:"v10-subgraph-savedquery-glyph",children:ae?"↗":L&&Q?"…":Q?"✓":"◎"}),V.name]},V.slug)})]},U.slug)),I&&s.jsx("span",{className:"v10-subgraph-savedquery-error",title:I,children:"✕ query failed"}),S&&P&&s.jsxs("span",{className:"v10-subgraph-savedquery-count",children:[S.size," match",S.size===1?"":"es"]})]}),h.length>0&&s.jsxs("div",{className:"v10-subgraph-filters",children:[h.map(U=>{const V=O.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 ae=V.has(Q);return s.jsx("button",{type:"button",className:`v10-subgraph-filter-chip${ae?" active":""}`,onClick:()=>Ze(U.slug,Q),children:Q},Q)})})]},U.slug)}),ot&&s.jsx("button",{type:"button",className:"v10-subgraph-filter-reset",onClick:bn,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 (",Z.length,Z.length!==q.length?` / ${q.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:gt,onSelectEntity:i,externallySorted:!0,sortLabel:_e,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:E,onChange:U=>w(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:F??"wm",triples:Te,onNodeClick:r,contextGraphId:n,title:vt,scopeLabel:`Subgraph graph: ${vt} entities and entity-to-entity triples from loaded subgraph data.`,trustLegendActiveLayer:F,scopeEntities:se,layerEntities:B,nodeColorsOverride:ie})}),x==="timeline"&&y&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(xh,{items:fe,color:ye,onSelectEntity:i,scrollKey:`subgraph:${e}:timeline`})}),x==="docs"&&s.jsx("div",{className:"v10-layer-expand-body full-width",children:s.jsx(Tr,{entities:Z,contextGraphId:n,scrollKey:`subgraph:${e}:docs`})})]})]})}const wh={wm:"items",swm:"items",vm:"items"},kh={wm:"working",swm:"shared",vm:"verified"};function Tn(e){return e==="wm"||e==="swm"||e==="vm"}function ur(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 Th({contextGraphId:e}){const{data:t,error:n,loading:r,refresh:i}=st(Ct.fetchContextGraphs,[],3e4),[a,o]=m.useState(!1),[l,c]=m.useState(!1),[d,g]=m.useState("overview"),[p,u]=m.useState(!1),[h,v]=m.useState(null);m.useEffect(()=>{u(!1)},[e]);const[y,j]=m.useState({contextGraphId:null,list:[],status:"loading"}),[f,b]=m.useState(null),[x,k]=m.useState(!1),E=m.useRef(0),[w,R]=m.useState(null),[M,_]=m.useState(null),O=m.useRef(null),[C,P]=m.useState(null),D=m.useCallback(G=>{O.current=G,P(G)},[]),S=m.useRef(null),T=m.useCallback(G=>{S.current=G,G===null&&(O.current=null,P(null)),R(G)},[]),[L,A]=m.useState(null),I=m.useRef(null);m.useEffect(()=>{I.current=h},[h]);const[$,W]=m.useState(wh),[q,K]=m.useState({}),oe=m.useRef(null),ee=m.useRef(null),F=m.useRef(null),Z=m.useRef(0),H=ba(e),te=ya(e),xe=Kn(G=>G.openTab),{data:Te,loading:B,error:se}=da(),ie=m.useCallback(()=>w?`subgraph:${w}:${q[w]??"items"}`:Tn(d)?`layer:${d}:${$[d]}`:"page",[d,w,$,q]),Ce=m.useCallback(G=>{const ne=G??ie(),ce=ur(ne,oe.current);return{activeLayer:d,activeSubGraph:w,layerTabs:{...$},subGraphTabs:{...q},scroll:{key:ne,top:(ce==null?void 0:ce.scrollTop)??0},subGraphEnabledLayers:w!==null&&O.current?new Set(O.current):null}},[d,w,ie,$,q]),fe=m.useCallback(G=>{const ne=()=>{const ce=ur(G.key,oe.current);ce&&(ce.scrollTop=G.top)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(ne):setTimeout(ne,0)},[]),ge=m.useCallback((G,ne)=>{(!I.current||!ee.current)&&(ee.current=Ce(ne)),v($e(G))},[Ce]),_e=m.useCallback(()=>{ee.current=null},[]);m.useEffect(()=>{if(h)return;const G=F.current;G&&(F.current=null,fe(G))},[h,d,w,$,q,fe]),m.useEffect(()=>{const G=ne=>{const ce=ne.detail;ce&&ce.contextGraphId===e&&typeof ce.entityUri=="string"&&(A(null),ge(ce.entityUri))};return window.addEventListener("v10:open-entity",G),()=>window.removeEventListener("v10:open-entity",G)},[e,ge]);const be=m.useCallback(G=>{var Le;const ne=G.startsWith("urn:dkg:agent:")?G.slice(14):G,ce=((Le=te.get(G))==null?void 0:Le.name)??ne;xe({id:`agent:${e}|${ne}`,label:`@ ${ce}`,closable:!0})},[te,e,xe]),Ze=m.useMemo(()=>({...te,openAgent:be}),[te,be]),de=m.useMemo(()=>{var G;return(G=t==null?void 0:t.contextGraphs)==null?void 0:G.find(ne=>ne.id===e)},[t,e]),Oe=p&&(d==="wm"||d==="swm"),ye=pa(e,{signalErrors:!0,includeQueryCatalog:Oe}),gt=Wn(ye).total,vt=ma({activeLayer:d,activeSubGraph:w}),zt=$r(vt?e:void 0),Lt=!w&&d==="overview",ot=Qa(Lt?e:void 0),bn=Lt?ot.resultContextGraphId===e?ot.events:[]:void 0,U=Lt&&ot.resultContextGraphId===e?ot.error:null,V=m.useCallback(()=>{const G=de==null?void 0:de.id;if(!G)return;const ne=Z.current+1;Z.current=ne,j({contextGraphId:G,list:[],status:"loading"}),Ct.listParticipants(G).then(ce=>{Z.current===ne&&j({contextGraphId:G,list:ce.allowedAgents,status:"ok"})}).catch(()=>{Z.current===ne&&j({contextGraphId:G,list:[],status:"error"})})},[de==null?void 0:de.id]);m.useEffect(()=>{V()},[V]);const Q=m.useCallback(()=>{const G=++E.current;Ct.fetchSubGraphs(e).then(ne=>{if(E.current!==G)return;const ce=(ne.subGraphs??[]).filter(Qn).length;b(ce),k(!1)}).catch(()=>{E.current===G&&(b(null),k(!0))})},[e]);m.useEffect(()=>{b(null),k(!1),Q()},[Q]),un(e,Q);const ae=Pa(e,h,L,Oe,ye),{entity:re,entities:ue,triples:Be}=ae,Fe=m.useCallback((G,ne)=>{const ce=S.current;if(_e(),T(G),G===null)_(null);else if(ne!==void 0){const Le=new Set([kh[ne]]);_(Le),O.current=Le,P(Le)}else{if(ce!==null&&G===ce)return;if(ce!==null&&O.current){const Le=new Set(O.current);_(Le),O.current=Le,P(Le)}else _(null),O.current=null,P(null)}v(null),A(null)},[_e,T]),We=m.useCallback(G=>{_e(),g(G),v(null),A(null),T(null),_(null)},[_e,T]),bt=m.useCallback((G,ne)=>{W(ce=>ce[G]===ne?ce:{...ce,[G]:ne})},[]),lt=m.useCallback((G,ne)=>{K(ce=>ce[G]===ne?ce:{...ce,[G]:ne})},[]),Pe=m.useCallback((G,ne,ce)=>{const Le=I.current!=null;ge(G,ne),A(Ei=>ce??(Le?Ei:null))},[ge]),Mt=m.useCallback(()=>{const G=ee.current;if(ee.current=null,v(null),A(null),!!G){if(g(G.activeLayer),T(G.activeSubGraph),G.activeSubGraph!==null&&G.subGraphEnabledLayers){const ne=new Set(G.subGraphEnabledLayers);_(ne),O.current=ne,P(ne)}W(G.layerTabs),K(G.subGraphTabs),F.current=G.scroll}},[T]),yn=m.useCallback(G=>{if(!(G!=null&&G.id))return;const ne=Tn(G.trustLayer)?G.trustLayer:void 0;Pe(G.id,void 0,ne)},[Pe]),ki=m.useCallback(G=>{const ne=Tn(d)?d:void 0;Pe(G,void 0,ne)},[d,Pe]),Ni=m.useCallback(G=>{Pe(G,"page")},[Pe]),us=m.useCallback(()=>{xe(ha)},[xe]),xn=!!n&&/authentication|unauthor|expired|sign in|log in/i.test(n);if(!de)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?xn?n:"Failed to load context graph.":"Context graph not found."}),xn?s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:()=>window.location.reload(),children:"Refresh page"}):s.jsx("button",{type:"button",className:"v10-retry-btn",onClick:i,children:"Retry"})]}):s.jsx("div",{className:"v10-view-placeholder",children:s.jsx("p",{style:{color:"var(--text-tertiary)",fontSize:12},children:"Loading context graph..."})});const Si=w?H.forSubGraph(w):null,jn=!ye.loading&&!ye.error&&!ye.partial?ye.entityList:void 0,Ci=re?"entity":w?"subgraph":d,$i=y.contextGraphId===de.id?y.list:[],_i=y.contextGraphId===de.id?y.status:"loading";return s.jsx(xa.Provider,{value:H,children:s.jsx(ja.Provider,{value:Ze,children:s.jsxs("div",{className:"v10-memory-explorer",children:[s.jsx(ka,{memory:ye}),n&&s.jsx("div",{className:"v10-stale-banner",role:"status",children:xn?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(oo,{cg:de,profile:H,activeSubGraph:Si,onClearSubGraph:()=>Fe(null)}),s.jsx(ao,{active:d,counts:ye.counts,onSwitch:We,onShare:()=>c(!0),onImport:()=>o(!0),onRefresh:ye.refresh}),s.jsxs("main",{className:"v10-memory-explorer-page","data-view":Ci,"data-cg-scroll-key":"page",ref:oe,children:[h&&(ae.loading||ae.error||ae.partial||!re)&&s.jsxs("div",{className:"v10-layer-action-note",role:"status",children:[ae.loading?"Loading resource details…":ae.error??(ae.partial?"The resource detail read reached its limit. Some relationships may be missing. Use a narrower query to inspect them.":"This resource is referenced here, but has no details in this view."),ae.error&&s.jsx("button",{onClick:ae.refresh,children:"Retry resource details"}),!re&&s.jsx("button",{onClick:Mt,children:"Close resource"})]}),re&&s.jsx(vh,{entity:re,allEntities:ue,allTriples:Be,onNavigate:Pe,onClose:Mt,contextGraphId:e,onRefresh:()=>{ye.refresh(),ae.refresh()}}),w&&!re&&s.jsxs(s.Fragment,{children:[s.jsx(lr,{}),s.jsx(kn,{contextGraphId:e,profile:H,selected:w,entities:jn,onSelect:Fe,enabledScope:C??void 0,allTriplesTotal:gt}),s.jsx(jh,{slug:w,rawMemory:ye,contextGraphId:e,onNodeClick:yn,onSelectEntity:Pe,activeTab:q[w]??"items",onTabChange:G=>lt(w,G),initialEnabledLayers:M??void 0,onEnabledLayersChange:D,onOpenQueryCatalog:()=>{T(null),g("query")}})]}),!w&&d==="overview"&&!re&&s.jsxs(s.Fragment,{children:[s.jsx(mo,{cg:de,memory:ye,subGraphCount:f,subGraphFetchFailed:x,participants:$i,participantsStatus:_i,currentAgent:Te??null,currentAgentStatus:B?"loading":se?"error":"ok",onSwitchLayer:We,onOpenPrimer:us}),s.jsx(fo,{contextGraphId:e,curatorStatus:po({cg:de,currentAgent:Te??null,currentAgentStatus:B?"loading":se?"error":"ok"}),onParticipantsChanged:V}),ye.loading&&s.jsx("div",{className:"v10-me-loading",children:s.jsx("div",{className:"v10-me-loading-text",children:"Loading memory..."})}),ye.error&&s.jsxs("div",{className:"v10-me-error",children:["Error: ",ye.error]}),s.jsx("div",{"data-section":"activity",children:s.jsx(wa,{entities:ye.entityList,lifecycleEvents:bn,lifecycleError:U,onSelectEntity:Ni,title:"Recent activity",limit:40,includeUndated:!1,emptyHint:"Once knowledge starts being added and managed in this context graph, activities will show up here as a live feed.",className:"v10-overview-activity"})}),s.jsx(go,{onOpenPrimer:us})]}),!w&&d==="graph-overview"&&!re&&s.jsxs(s.Fragment,{children:[s.jsx(lr,{}),s.jsx(kn,{contextGraphId:e,profile:H,selected:null,entities:jn,onSelect:Fe,allTriplesTotal:gt}),s.jsx(yh,{contextGraphId:e,memory:ye,onNodeClick:yn,onSelectSubGraph:Fe})]}),!w&&d==="query"&&!re&&s.jsx(Go,{contextGraphId:e}),!w&&(d==="wm"||d==="swm"||d==="vm")&&!re&&s.jsxs(s.Fragment,{children:[s.jsx(kn,{contextGraphId:e,profile:H,selected:w,entities:jn,onSelect:Fe,layer:d}),s.jsx(Oo,{layer:d,memory:ye,onNodeClick:yn,onSelectEntity:ki,contextGraphId:e,activeTab:$[d],onTabChange:G=>bt(d,G),swmAttribution:zt,showQueryCatalog:p,onShowQueryCatalogChange:u})]})]}),s.jsx(La,{open:a,onClose:()=>o(!1),contextGraphId:de.id,contextGraphName:de.name}),s.jsx(Fa,{open:l,onClose:()=>c(!1),contextGraphId:de.id,contextGraphName:de.name})]})})})}export{Th as ProjectView};