pmx-canvas 0.6.2 → 0.6.3

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.
@@ -1,70 +1,70 @@
1
- var Ow=Object.create;var{getPrototypeOf:Lw,defineProperty:Ud,getOwnPropertyNames:Dw}=Object;var Wd=Object.prototype.hasOwnProperty;function Fw(e){return this[e]}var jw,Zw,Hw=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var r=t?jw??=new WeakMap:Zw??=new WeakMap,s=r.get(e);if(s)return s}n=e!=null?Ow(Lw(e)):{};let a=t||!e||!e.__esModule||!Wd.call(e,"default")?Ud(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of Dw(e))if(!Wd.call(a,c))Ud(a,c,{get:Fw.bind(e,c),enumerable:!0})}if(o)r.set(e,a);return a};var Bw=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var rm=Bw(function(om){Object.defineProperty(om,"__esModule",{value:!0});var Bf=/highlight-(?:text|source)-([a-z0-9]+)/;function Wf(e){e.addRule("highlightedCodeBlock",{filter:function(t){var n=t.firstChild;return t.nodeName==="DIV"&&Bf.test(t.className)&&n&&n.nodeName==="PRE"},replacement:function(t,n,o){var r=n.className||"",s=(r.match(Bf)||[null,""])[1];return`
1
+ var Dw=Object.create;var{getPrototypeOf:Fw,defineProperty:qd,getOwnPropertyNames:jw}=Object;var Vd=Object.prototype.hasOwnProperty;function Zw(e){return this[e]}var Hw,Bw,Uw=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var r=t?Hw??=new WeakMap:Bw??=new WeakMap,s=r.get(e);if(s)return s}n=e!=null?Dw(Fw(e)):{};let a=t||!e||!e.__esModule||!Vd.call(e,"default")?qd(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of jw(e))if(!Vd.call(a,c))qd(a,c,{get:Zw.bind(e,c),enumerable:!0})}if(o)r.set(e,a);return a};var Ww=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var im=Ww(function(rm){Object.defineProperty(rm,"__esModule",{value:!0});var Uf=/highlight-(?:text|source)-([a-z0-9]+)/;function qf(e){e.addRule("highlightedCodeBlock",{filter:function(t){var n=t.firstChild;return t.nodeName==="DIV"&&Uf.test(t.className)&&n&&n.nodeName==="PRE"},replacement:function(t,n,o){var r=n.className||"",s=(r.match(Uf)||[null,""])[1];return`
2
2
 
3
3
  `+o.fence+s+`
4
4
  `+n.firstChild.textContent+`
5
5
  `+o.fence+`
6
6
 
7
- `}})}function qf(e){e.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(t){return"~~"+t+"~~"}})}var xS=Array.prototype.indexOf,bS=Array.prototype.every,Mn={},wS={left:":---",right:"---:",center:":---:"},al=null,Vf=null,Uf=new WeakMap;function _S(e){return e?(e.getAttribute("align")||e.style.textAlign||"").toLowerCase():""}function Gf(e){return e?wS[e]:"---"}function Xf(e,t){var n={left:0,right:0,center:0,"":0},o="";for(var r=0;r<e.rows.length;++r){var s=e.rows[r];if(t<s.childNodes.length){var a=_S(s.childNodes[t]);if(++n[a],n[a]>n[o])o=a}}return o}Mn.tableCell={filter:["th","td"],replacement:function(e,t){if(ll(Qf(t)))return e;return Kf(e,t)}};Mn.tableRow={filter:"tr",replacement:function(e,t){let n=Qf(t);if(ll(n))return e;var o="";if(SS(t)){let a=em(n);for(var r=0;r<a;r++){let c=r<t.childNodes.length?t.childNodes[r]:null;var s=Gf(Xf(n,r));o+=Kf(s,c,r)}}return`
7
+ `}})}function Vf(e){e.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(t){return"~~"+t+"~~"}})}var wS=Array.prototype.indexOf,_S=Array.prototype.every,Mn={},SS={left:":---",right:"---:",center:":---:"},ul=null,Gf=null,Wf=new WeakMap;function kS(e){return e?(e.getAttribute("align")||e.style.textAlign||"").toLowerCase():""}function Xf(e){return e?SS[e]:"---"}function Kf(e,t){var n={left:0,right:0,center:0,"":0},o="";for(var r=0;r<e.rows.length;++r){var s=e.rows[r];if(t<s.childNodes.length){var a=kS(s.childNodes[t]);if(++n[a],n[a]>n[o])o=a}}return o}Mn.tableCell={filter:["th","td"],replacement:function(e,t){if(pl(em(t)))return e;return Jf(e,t)}};Mn.tableRow={filter:"tr",replacement:function(e,t){let n=em(t);if(pl(n))return e;var o="";if(CS(t)){let a=tm(n);for(var r=0;r<a;r++){let c=r<t.childNodes.length?t.childNodes[r]:null;var s=Xf(Kf(n,r));o+=Jf(s,c,r)}}return`
8
8
  `+e+(o?`
9
- `+o:"")}};Mn.table={filter:function(e,t){return e.nodeName==="TABLE"},replacement:function(e,t){if(Yf(t,Vf)){let c=t.outerHTML,l=TS(t);if(l===null||!l.classList.contains("joplin-table-wrapper"))return`
9
+ `+o:"")}};Mn.table={filter:function(e,t){return e.nodeName==="TABLE"},replacement:function(e,t){if(Qf(t,Gf)){let c=t.outerHTML,l=IS(t);if(l===null||!l.classList.contains("joplin-table-wrapper"))return`
10
10
 
11
11
  <div class="joplin-table-wrapper">${c}</div>
12
12
 
13
- `;else return c}else{if(ll(t))return e;e=e.replace(/\n+/g,`
13
+ `;else return c}else{if(pl(t))return e;e=e.replace(/\n+/g,`
14
14
  `);var n=e.trim().split(`
15
- `);if(n.length>=2)n=n[1];var o=/\| :?---/.test(n),r=em(t),s="";if(r&&!o){s="|"+" |".repeat(r)+`
16
- |`;for(var a=0;a<r;++a)s+=" "+Gf(Xf(t,a))+" |"}let c=t.caption?t.caption.textContent||"":"",l=c?`${c}
15
+ `);if(n.length>=2)n=n[1];var o=/\| :?---/.test(n),r=tm(t),s="";if(r&&!o){s="|"+" |".repeat(r)+`
16
+ |`;for(var a=0;a<r;++a)s+=" "+Xf(Kf(t,a))+" |"}let c=t.caption?t.caption.textContent||"":"",l=c?`${c}
17
17
 
18
18
  `:"",u=`${s}${e}`.trimStart();return`
19
19
 
20
20
  ${l}${u}
21
21
 
22
- `}}};Mn.tableCaption={filter:["caption"],replacement:()=>""};Mn.tableColgroup={filter:["colgroup","col"],replacement:()=>""};Mn.tableSection={filter:["thead","tbody","tfoot"],replacement:function(e){return e}};function SS(e){var t=e.parentNode;return t.nodeName==="THEAD"||t.firstChild===e&&(t.nodeName==="TABLE"||kS(t))&&bS.call(e.childNodes,function(n){return n.nodeName==="TH"})}function kS(e){var t=e.previousSibling;return e.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function Kf(e,t=null,n=null){if(n===null)n=xS.call(t.parentNode.childNodes,t);var o=" ";if(n===0)o="| ";let r=e.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");r=r.replace(/\|+/g,"\\|");while(r.length<3)r+=" ";if(t)r=ES(r,t," ");return o+r+" |"}function Jf(e){if(!e.childNodes)return!1;for(let t=0;t<e.childNodes.length;t++){let n=e.childNodes[t];if(n.nodeName==="TABLE")return!0;if(Jf(n))return!0}return!1}var cl=(e,t)=>{if(!e.childNodes)return!1;for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(t==="code"&&al&&al(o))return!0;if(t.includes(o.nodeName))return!0;if(cl(o,t))return!0}return!1},Yf=(e,t)=>{let n=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];if(t.preserveNestedTables)n.push("TABLE");return cl(e,"code")||cl(e,n)};function ll(e){let t=Uf.get(e);if(t!==void 0)return t;let n=CS(e);return Uf.set(e,n),n}function CS(e){if(!e)return!0;if(!e.rows)return!0;if(e.rows.length===1&&e.rows[0].childNodes.length<=1)return!0;if(Jf(e))return!0;return!1}function TS(e){let t=e.parentNode;while(t.nodeName!=="DIV")if(t=t.parentNode,!t)return null;return t}function Qf(e){let t=e.parentNode;while(t.nodeName!=="TABLE")if(t=t.parentNode,!t)return null;return t}function ES(e,t,n){let o=t.getAttribute("colspan")||1;for(let r=1;r<o;r++)e+=" | "+n.repeat(3);return e}function em(e){let t=0;for(let n=0;n<e.rows.length;n++){let r=e.rows[n].childNodes.length;if(r>t)t=r}return t}function tm(e){al=e.isCodeBlock,Vf=e.options,e.keep(function(n){if(n.nodeName==="TABLE"&&Yf(n,e.options))return!0;return!1});for(var t in Mn)e.addRule(t,Mn[t])}function nm(e){e.addRule("taskListItems",{filter:function(t){let n=t.parentNode,o=n.parentNode;return t.type==="checkbox"&&(n.nodeName==="LI"||n.nodeName==="LABEL"&&o&&o.nodeName==="LI")},replacement:function(t,n){return(n.checked?"[x]":"[ ]")+" "}})}function IS(e){e.use([Wf,qf,tm,nm])}om.gfm=IS;om.highlightedCodeBlock=Wf;om.strikethrough=qf;om.tables=tm;om.taskListItems=nm});if(typeof crypto<"u"&&typeof crypto.randomUUID!=="function")crypto.randomUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e)=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var Fi,he,Kd,_c,En,qd,Jd,Yd,Qd,Sc,xc,bc,Uw,Oi={},Li=[],Ww=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,ji=Array.isArray;function rn(e,t){for(var n in t)e[n]=t[n];return e}function kc(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function qw(e,t,n){var o,r,s,a={};for(s in t)s=="key"?o=t[s]:s=="ref"?r=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?Fi.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)a[s]===void 0&&(a[s]=e.defaultProps[s]);return Mi(e,a,o,r,null)}function Mi(e,t,n,o,r){var s={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r==null?++Kd:r,__i:-1,__u:0};return r==null&&he.vnode!=null&&he.vnode(s),s}function ve(e){return e.children}function Po(e,t){this.props=e,this.context=t}function No(e,t){if(t==null)return e.__?No(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?No(e):null}function Vw(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,o=[],r=[],s=rn({},t);s.__v=t.__v+1,he.vnode&&he.vnode(s),Cc(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,o,n==null?No(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,op(o,s,r),t.__e=t.__=null,s.__e!=n&&ep(s)}}function ep(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),ep(e)}function Vd(e){(!e.__d&&(e.__d=!0)&&En.push(e)&&!Di.__r++||qd!=he.debounceRendering)&&((qd=he.debounceRendering)||Jd)(Di)}function Di(){try{for(var e,t=1;En.length;)En.length>t&&En.sort(Yd),e=En.shift(),t=En.length,Vw(e)}finally{En.length=Di.__r=0}}function tp(e,t,n,o,r,s,a,c,l,u,d){var p,m,f,g,y,x,h,v=o&&o.__k||Li,b=t.length;for(l=Gw(n,t,v,l,b),p=0;p<b;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&v[f.__i]||Oi,f.__i=p,x=Cc(e,f,m,r,s,a,c,l,u,d),g=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&Tc(m.ref,null,f),d.push(f.ref,f.__c||g,f)),y==null&&g!=null&&(y=g),(h=!!(4&f.__u))||m.__k===f.__k?l=np(f,l,e,h):typeof f.type=="function"&&x!==void 0?l=x:g&&(l=g.nextSibling),f.__u&=-7);return n.__e=y,l}function Gw(e,t,n,o,r){var s,a,c,l,u,d=n.length,p=d,m=0;for(e.__k=Array(r),s=0;s<r;s++)(a=t[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=e.__k[s]=Mi(null,a,null,null,null):ji(a)?a=e.__k[s]=Mi(ve,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=e.__k[s]=Mi(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+m,a.__=e,a.__b=e.__b+1,c=null,(u=a.__i=Xw(a,n,l,p))!=-1&&(p--,(c=n[u])&&(c.__u|=2)),c==null||c.__v==null?(u==-1&&(r>d?m--:r<d&&m++),typeof a.type!="function"&&(a.__u|=4)):u!=l&&(u==l-1?m--:u==l+1?m++:(u>l?m--:m++,a.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<d;s++)(c=n[s])!=null&&(2&c.__u)==0&&(c.__e==o&&(o=No(c)),ip(c,c));return o}function np(e,t,n,o){var r,s;if(typeof e.type=="function"){for(r=e.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=e,t=np(r[s],t,n,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=No(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Xw(e,t,n,o){var r,s,a,{key:c,type:l}=e,u=t[n],d=u!=null&&(2&u.__u)==0;if(u===null&&c==null||d&&c==u.key&&l==u.type)return n;if(o>(d?1:0)){for(r=n-1,s=n+1;r>=0||s<t.length;)if((u=t[a=r>=0?r--:s++])!=null&&(2&u.__u)==0&&c==u.key&&l==u.type)return a}return-1}function Gd(e,t,n){t[0]=="-"?e.setProperty(t,n==null?"":n):e[t]=n==null?"":typeof n!="number"||Ww.test(t)?n:n+"px"}function $i(e,t,n,o,r){var s,a;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)n&&t in n||Gd(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||Gd(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(Qd,"$1")),a=t.toLowerCase(),t=a in e||t=="onFocusOut"||t=="onFocusIn"?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?o?n.u=o.u:(n.u=Sc,e.addEventListener(t,s?bc:xc,s)):e.removeEventListener(t,s?bc:xc,s);else{if(r=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n==null?"":n;break e}catch(c){}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Xd(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=Sc++;else if(t.t<n.u)return;return n(he.event?he.event(t):t)}}}function Cc(e,t,n,o,r,s,a,c,l,u){var d,p,m,f,g,y,x,h,v,b,z,F,_,k,T,P=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),s=[c=t.__e=n.__e]),(d=he.__b)&&d(t);e:if(typeof P=="function")try{if(h=t.props,v=P.prototype&&P.prototype.render,b=(d=P.contextType)&&o[d.__c],z=d?b?b.props.value:d.__:o,n.__c?x=(p=t.__c=n.__c).__=p.__E:(v?t.__c=p=new P(h,z):(t.__c=p=new Po(h,z),p.constructor=P,p.render=Jw),b&&b.sub(p),p.state||(p.state={}),p.__n=o,m=p.__d=!0,p.__h=[],p._sb=[]),v&&p.__s==null&&(p.__s=p.state),v&&P.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=rn({},p.__s)),rn(p.__s,P.getDerivedStateFromProps(h,p.__s))),f=p.props,g=p.state,p.__v=t,m)v&&P.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),v&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(v&&P.getDerivedStateFromProps==null&&h!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(h,z),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(h,p.__s,z)===!1){t.__v!=n.__v&&(p.props=h,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(Z){Z&&(Z.__=t)}),Li.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&a.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(h,p.__s,z),v&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,g,y)})}if(p.context=z,p.props=h,p.__P=e,p.__e=!1,F=he.__r,_=0,v)p.state=p.__s,p.__d=!1,F&&F(t),d=p.render(p.props,p.state,p.context),Li.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,F&&F(t),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++_<25);p.state=p.__s,p.getChildContext!=null&&(o=rn(rn({},o),p.getChildContext())),v&&!m&&p.getSnapshotBeforeUpdate!=null&&(y=p.getSnapshotBeforeUpdate(f,g)),k=d!=null&&d.type===ve&&d.key==null?rp(d.props.children):d,c=tp(e,ji(k)?k:[k],t,n,o,r,s,a,c,l,u),p.base=t.__e,t.__u&=-161,p.__h.length&&a.push(p),x&&(p.__E=p.__=null)}catch(Z){if(t.__v=null,l||s!=null)if(Z.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;s[s.indexOf(c)]=null,t.__e=c}else{for(T=s.length;T--;)kc(s[T]);wc(t)}else t.__e=n.__e,t.__k=n.__k,Z.then||wc(t);he.__e(Z,t,n)}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=Kw(n.__e,t,n,o,r,s,a,l,u);return(d=he.diffed)&&d(t),128&t.__u?void 0:c}function wc(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(wc))}function op(e,t,n){for(var o=0;o<n.length;o++)Tc(n[o],n[++o],n[++o]);he.__c&&he.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(s){s.call(r)})}catch(s){he.__e(s,r.__v)}})}function rp(e){return typeof e!="object"||e==null||e.__b>0?e:ji(e)?e.map(rp):rn({},e)}function Kw(e,t,n,o,r,s,a,c,l){var u,d,p,m,f,g,y,x=n.props||Oi,{props:h,type:v}=t;if(v=="svg"?r="http://www.w3.org/2000/svg":v=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((f=s[u])&&"setAttribute"in f==!!v&&(v?f.localName==v:f.nodeType==3)){e=f,s[u]=null;break}}if(e==null){if(v==null)return document.createTextNode(h);e=document.createElementNS(r,v,h.is&&h),c&&(he.__m&&he.__m(t,s),c=!1),s=null}if(v==null)x===h||c&&e.data==h||(e.data=h);else{if(s=s&&Fi.call(e.childNodes),!c&&s!=null)for(x={},u=0;u<e.attributes.length;u++)x[(f=e.attributes[u]).name]=f.value;for(u in x)f=x[u],u=="dangerouslySetInnerHTML"?p=f:u=="children"||(u in h)||u=="value"&&("defaultValue"in h)||u=="checked"&&("defaultChecked"in h)||$i(e,u,null,f,r);for(u in h)f=h[u],u=="children"?m=f:u=="dangerouslySetInnerHTML"?d=f:u=="value"?g=f:u=="checked"?y=f:c&&typeof f!="function"||x[u]===f||$i(e,u,f,x[u],r);if(d)c||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),tp(t.type=="template"?e.content:e,ji(m)?m:[m],t,n,o,v=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&No(n,0),c,l),s!=null)for(u=s.length;u--;)kc(s[u]);c||(u="value",v=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[u]||v=="progress"&&!g||v=="option"&&g!=x[u])&&$i(e,u,g,x[u],r),u="checked",y!=null&&y!=e[u]&&$i(e,u,y,x[u],r))}return e}function Tc(e,t,n){try{if(typeof e=="function"){var o=typeof e.__u=="function";o&&e.__u(),o&&t==null||(e.__u=e(t))}else e.current=t}catch(r){he.__e(r,n)}}function ip(e,t,n){var o,r;if(he.unmount&&he.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Tc(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){he.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(r=0;r<o.length;r++)o[r]&&ip(o[r],t,n||typeof e.type!="function");n||kc(e.__e),e.__c=e.__=e.__e=void 0}function Jw(e,t,n){return this.constructor(e,n)}function sp(e,t,n){var o,r,s,a;t==document&&(t=document.documentElement),he.__&&he.__(e,t),r=(o=typeof n=="function")?null:n&&n.__k||t.__k,s=[],a=[],Cc(t,e=(!o&&n||t).__k=qw(ve,null,[e]),r||Oi,Oi,t.namespaceURI,!o&&n?[n]:r?null:t.firstChild?Fi.call(t.childNodes):null,s,!o&&n?n:r?r.__e:t.firstChild,o,a),op(s,e,a)}Fi=Li.slice,he={__e:function(e,t,n,o){for(var r,s,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(e)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(e,o||{}),a=r.__d),a)return r.__E=r}catch(c){e=c}throw e}},Kd=0,_c=function(e){return e!=null&&e.constructor===void 0},Po.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=rn({},this.state),typeof e=="function"&&(e=e(rn({},n),this.props)),e&&rn(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Vd(this))},Po.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Vd(this))},Po.prototype.render=ve,En=[],Jd=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Yd=function(e,t){return e.__v.__b-t.__v.__b},Di.__r=0,Qd=/(PointerCapture)$|Capture$/i,Sc=0,xc=Xd(!1),bc=Xd(!0),Uw=0;var Ro,qe,Ec,ap,Pr=0,hp=[],Ge=he,{__b:cp,__r:lp,diffed:up,__c:dp,unmount:pp,__:fp}=Ge;function Hi(e,t){Ge.__h&&Ge.__h(qe,e,Pr||t),Pr=0;var n=qe.__H||(qe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function L(e){return Pr=1,Yw(gp,e)}function Yw(e,t,n){var o=Hi(Ro++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):gp(void 0,t),function(c){var l=o.__N?o.__N[0]:o.__[0],u=o.t(l,c);l!==u&&(o.__N=[u,o.__[1]],o.__c.setState({}))}],o.__c=qe,!qe.__f)){var r=function(c,l,u){if(!o.__c.__H)return!0;var d=o.__c.__H.__.filter(function(m){return m.__c});if(d.every(function(m){return!m.__N}))return!s||s.call(this,c,l,u);var p=o.__c.props!==c;return d.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),s&&s.call(this,c,l,u)||p};qe.__f=!0;var s=qe.shouldComponentUpdate,a=qe.componentWillUpdate;qe.componentWillUpdate=function(c,l,u){if(this.__e){var d=s;s=void 0,r(c,l,u),s=d}a&&a.call(this,c,l,u)},qe.shouldComponentUpdate=r}return o.__N||o.__}function D(e,t){var n=Hi(Ro++,3);!Ge.__s&&Ac(n.__H,t)&&(n.__=e,n.u=t,qe.__H.__h.push(n))}function Bi(e,t){var n=Hi(Ro++,4);!Ge.__s&&Ac(n.__H,t)&&(n.__=e,n.u=t,qe.__h.push(n))}function R(e){return Pr=5,Ae(function(){return{current:e}},[])}function Ae(e,t){var n=Hi(Ro++,7);return Ac(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function O(e,t){return Pr=8,Ae(function(){return e},t)}function Qw(){for(var e;e=hp.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Zi),t.__h.some(Ic),t.__h=[]}catch(n){t.__h=[],Ge.__e(n,e.__v)}}}Ge.__b=function(e){qe=null,cp&&cp(e)},Ge.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),fp&&fp(e,t)},Ge.__r=function(e){lp&&lp(e),Ro=0;var t=(qe=e.__c).__H;t&&(Ec===qe?(t.__h=[],qe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Zi),t.__h.some(Ic),t.__h=[],Ro=0)),Ec=qe},Ge.diffed=function(e){up&&up(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(hp.push(t)!==1&&ap===Ge.requestAnimationFrame||((ap=Ge.requestAnimationFrame)||e_)(Qw)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ec=qe=null},Ge.__c=function(e,t){t.some(function(n){try{n.__h.some(Zi),n.__h=n.__h.filter(function(o){return!o.__||Ic(o)})}catch(o){t.some(function(r){r.__h&&(r.__h=[])}),t=[],Ge.__e(o,n.__v)}}),dp&&dp(e,t)},Ge.unmount=function(e){pp&&pp(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(o){try{Zi(o)}catch(r){t=r}}),n.__H=void 0,t&&Ge.__e(t,n.__v))};var mp=typeof requestAnimationFrame=="function";function e_(e){var t,n=function(){clearTimeout(o),mp&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);mp&&(t=requestAnimationFrame(n))}function Zi(e){var t=qe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),qe=t}function Ic(e){var t=qe;e.__c=e.__(),qe=t}function Ac(e,t){return!e||e.length!==t.length||t.some(function(n,o){return n!==e[o]})}function gp(e,t){return typeof t=="function"?t(e):t}var t_=Symbol.for("preact-signals");function Vi(){if(!(sn>1)){var e,t=!1;(function(){var r=Wi;Wi=void 0;while(r!==void 0){if(r.S.v===r.v)r.S.i=r.i;r=r.o}})();while(Nr!==void 0){var n=Nr;Nr=void 0,Ui++;while(n!==void 0){var o=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&xp(n))try{n.c()}catch(r){if(!t)e=r,t=!0}n=o}}if(Ui=0,sn--,t)throw e}else sn--}function $t(e){if(sn>0)return e();zc=++n_,sn++;try{return e()}finally{Vi()}}var _e=void 0;function Pc(e){var t=_e;_e=void 0;try{return e()}finally{_e=t}}var vp,Nr=void 0,sn=0,Ui=0,n_=0,zc=0,Wi=void 0,qi=0;function yp(e){if(_e!==void 0){var t=e.n;if(t===void 0||t.t!==_e){if(t={i:0,S:e,p:_e.s,n:void 0,t:_e,e:void 0,x:void 0,r:t},_e.s!==void 0)_e.s.n=t;if(_e.s=t,e.n=t,32&_e.f)e.S(t);return t}else if(t.i===-1){if(t.i=0,t.n!==void 0){if(t.n.p=t.p,t.p!==void 0)t.p.n=t.n;t.p=_e.s,t.n=void 0,_e.s.n=t,_e.s=t}return t}}}function et(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t==null?void 0:t.watched,this.Z=t==null?void 0:t.unwatched,this.name=t==null?void 0:t.name}et.prototype.brand=t_;et.prototype.h=function(){return!0};et.prototype.S=function(e){var t=this,n=this.t;if(n!==e&&e.e===void 0)if(e.x=n,this.t=e,n!==void 0)n.e=e;else Pc(function(){var o;(o=t.W)==null||o.call(t)})};et.prototype.U=function(e){var t=this;if(this.t!==void 0){var{e:n,x:o}=e;if(n!==void 0)n.x=o,e.e=void 0;if(o!==void 0)o.e=n,e.x=void 0;if(e===this.t){if(this.t=o,o===void 0)Pc(function(){var r;(r=t.Z)==null||r.call(t)})}}};et.prototype.subscribe=function(e){var t=this;return Kt(function(){var n=t.value,o=_e;_e=void 0;try{e(n)}finally{_e=o}},{name:"sub"})};et.prototype.valueOf=function(){return this.value};et.prototype.toString=function(){return this.value+""};et.prototype.toJSON=function(){return this.value};et.prototype.peek=function(){var e=_e;_e=void 0;try{return this.value}finally{_e=e}};Object.defineProperty(et.prototype,"value",{get:function(){var e=yp(this);if(e!==void 0)e.i=this.i;return this.v},set:function(e){if(e!==this.v){if(Ui>100)throw Error("Cycle detected");(function(n){if(sn!==0&&Ui===0){if(n.l!==zc)n.l=zc,Wi={S:n,v:n.v,i:n.i,o:Wi}}})(this),this.v=e,this.i++,qi++,sn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Vi()}}}});function V(e,t){return new et(e,t)}function xp(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function bp(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0)t.r=n;if(t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function wp(e){var t=e.s,n=void 0;while(t!==void 0){var o=t.p;if(t.i===-1){if(t.S.U(t),o!==void 0)o.n=t.n;if(t.n!==void 0)t.n.p=o}else n=t;if(t.S.n=t.r,t.r!==void 0)t.r=void 0;t=o}e.s=n}function ro(e,t){et.call(this,void 0),this.x=e,this.s=void 0,this.g=qi-1,this.f=4,this.W=t==null?void 0:t.watched,this.Z=t==null?void 0:t.unwatched,this.name=t==null?void 0:t.name}ro.prototype=new et;ro.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32)return!0;if(this.f&=-5,this.g===qi)return!0;if(this.g=qi,this.f|=1,this.i>0&&!xp(this))return this.f&=-2,!0;var e=_e;try{bp(this),_e=this;var t=this.x();if(16&this.f||this.v!==t||this.i===0)this.v=t,this.f&=-17,this.i++}catch(n){this.v=n,this.f|=16,this.i++}return _e=e,wp(this),this.f&=-2,!0};ro.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}et.prototype.S.call(this,e)};ro.prototype.U=function(e){if(this.t!==void 0){if(et.prototype.U.call(this,e),this.t===void 0){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}}};ro.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}};Object.defineProperty(ro.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=yp(this);if(this.h(),e!==void 0)e.i=this.i;if(16&this.f)throw this.v;return this.v}});function Oe(e,t){return new ro(e,t)}function _p(e){var t=e.m;if(e.m=void 0,typeof t=="function"){sn++;var n=_e;_e=void 0;try{t()}catch(o){throw e.f&=-2,e.f|=8,Nc(e),o}finally{_e=n,Vi()}}}function Nc(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,_p(e)}function o_(e){if(_e!==this)throw Error("Out-of-order effect");if(wp(this),_e=e,this.f&=-2,8&this.f)Nc(this);Vi()}function $o(e,t){if(this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t==null?void 0:t.name,vp)vp.push(this)}$o.prototype.c=function(){var e=this.S();try{if(8&this.f)return;if(this.x===void 0)return;var t=this.x();if(typeof t=="function")this.m=t}finally{e()}};$o.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,_p(this),bp(this),sn++;var e=_e;return _e=this,o_.bind(this,e)};$o.prototype.N=function(){if(!(2&this.f))this.f|=2,this.u=Nr,Nr=this};$o.prototype.d=function(){if(this.f|=8,!(1&this.f))Nc(this)};$o.prototype.dispose=function(){this.d()};function Kt(e,t){var n=new $o(e,t);try{n.c()}catch(r){throw n.d(),r}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Sp,Rc,Gi,r_=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__;var kp=[];Kt(function(){Sp=this.N})();function Mo(e,t){he[e]=t.bind(null,he[e]||function(){})}function Xi(e){if(Gi){var t=Gi;Gi=void 0,t()}Gi=e&&e.S()}function Cp(e){var t=this,n=e.data,o=s_(n);o.value=n;var r=Ae(function(){var c=t,l=t.__v;while(l=l.__)if(l.__c){l.__c.__$f|=4;break}var u=Oe(function(){var f=o.value.value;return f===0?0:f===!0?"":f||""}),d=Oe(function(){return!Array.isArray(u.value)&&!_c(u.value)}),p=Kt(function(){if(this.N=Tp,d.value){var f=u.value;if(c.__v&&c.__v.__e&&c.__v.__e.nodeType===3)c.__v.__e.data=f}}),m=t.__$u.d;return t.__$u.d=function(){p(),m.call(this)},[d,u]},[]),s=r[0],a=r[1];return s.value?a.peek():a.value}Cp.displayName="ReactiveTextNode";Object.defineProperties(et.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Cp},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}});Mo("__b",function(e,t){if(typeof t.type=="string"){var n,o=t.props;for(var r in o)if(r!=="children"){var s=o[r];if(s instanceof et){if(!n)t.__np=n={};n[r]=s,o[r]=s.peek()}}}e(t)});Mo("__r",function(e,t){if(e(t),t.type!==ve){Xi();var n,o=t.__c;if(o){if(o.__$f&=-2,(n=o.__$u)===void 0)o.__$u=n=function(r,s){var a;return Kt(function(){a=this},{name:s}),a.c=r,a}(function(){var r;if(r_)(r=n.y)==null||r.call(n);o.__$f|=1,o.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:"")}Rc=o,Xi(n)}});Mo("__e",function(e,t,n,o){Xi(),Rc=void 0,e(t,n,o)});Mo("diffed",function(e,t){Xi(),Rc=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var{__np:o,props:r}=t;if(o){var s=n.U;if(s)for(var a in s){var c=s[a];if(c!==void 0&&!(a in o))c.d(),s[a]=void 0}else s={},n.U=s;for(var l in o){var u=s[l],d=o[l];if(u===void 0)u=i_(n,l,d),s[l]=u;else u.o(d,r)}for(var p in o)r[p]=o[p]}}e(t)});function i_(e,t,n,o){var r=t in e&&e.ownerSVGElement===void 0,s=V(n),a=n.peek();return{o:function(c,l){s.value=c,a=c.peek()},d:Kt(function(){this.N=Tp;var c=s.value.value;if(a!==c)if(a=void 0,r)e[t]=c;else if(c!=null&&(c!==!1||t[4]==="-"))e.setAttribute(t,c);else e.removeAttribute(t);else a=void 0})}}Mo("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var o=n.U;if(o){n.U=void 0;for(var r in o){var s=o[r];if(s)s.d()}}}t.__np=void 0}else{var a=t.__c;if(a){var c=a.__$u;if(c)a.__$u=void 0,c.d()}}e(t)});Mo("__h",function(e,t,n,o){if(o<3||o===9)t.__$f|=2;e(t,n,o)});Po.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var r in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(o||s||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(o||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var a in e)if(a!=="__source"&&e[a]!==this.props[a])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function s_(e,t){return Ae(function(){return V(e,t)},[])}var a_=function(e){queueMicrotask(function(){queueMicrotask(e)})};function c_(){$t(function(){var e;while(e=kp.shift())Sp.call(e)})}function Tp(){if(kp.push(this)===1)(he.requestAnimationFrame||a_)(c_)}var Ki=V(null),Rr=V([]),Lo=V(new Set),Do=V(new Set),Ji=V([]),Yi=V(new Set),Jt=V(!1),Oo=V(0);function Ep(){Ki.value=null,Rr.value=[],Lo.value=new Set,Do.value=new Set,Ji.value=[],Yi.value=new Set,Jt.value=!1,Oo.value=0}function Qi(){Jt.value=!0,Oo.value=0}function Ip(){Jt.value=!1}function Ap(e,t,n){Lo.value=new Set(e),Do.value=new Set(t),Ji.value=n}function es(e){Ki.value=e}function zp(e,t=6){if(Rr.value=[e,...Rr.value].slice(0,t),!Jt.value)Oo.value=Math.min(99,Oo.value+1)}function ts(e){Yi.value=new Set(e)}var l_=0;function i(e,t,n,o,r,s){t||(t={});var a,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?a=t[c]:l[c]=t[c];var u={type:e,props:l,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--l_,__i:-1,__u:0,__source:r,__self:s};if(typeof e=="function"&&(a=e.defaultProps))for(c in a)l[c]===void 0&&(l[c]=a[c]);return he.vnode&&he.vnode(u),u}function u_(e){return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function d_(){Qi()}function Pp(){let e=Rr.value;if(e.length===0)return null;let t=Jt.value,n=Oo.value;if(!t)return i("button",{type:"button",class:"attention-history-tab",onClick:d_,"aria-label":n>0?`Recent updates — ${n} new`:"Recent updates",title:n>0?`${n} new updates since last viewed`:"Recent updates",children:[i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"attention-history-tab-label",children:"Updates"},void 0,!1,void 0,this),n>0&&i("span",{class:"attention-history-tab-badge","aria-hidden":"true",children:n>9?"9+":n},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("aside",{class:"attention-history","aria-label":"Recent semantic changes",children:[i("div",{class:"attention-history-header",children:[i("div",{class:"attention-history-header-text",children:[i("span",{class:"attention-history-title",children:"Recent Updates"},void 0,!1,void 0,this),i("span",{class:"attention-history-subtitle",children:"Focus and meaning shifts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"attention-history-close",onClick:Ip,"aria-label":"Collapse changes panel",title:"Collapse",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"attention-history-list",children:e.map((o)=>i("article",{class:`attention-history-entry attention-tone-${o.tone}`,children:[i("div",{class:"attention-history-meta",children:[i("span",{class:"attention-history-kind",children:o.title},void 0,!1,void 0,this),i("time",{class:"attention-history-time",dateTime:new Date(o.createdAt).toISOString(),children:u_(o.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("p",{class:"attention-history-detail",children:o.detail},void 0,!1,void 0,this)]},o.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Np(){let e=Ki.value;if(!e)return null;return i("button",{type:"button",class:`attention-toast attention-tone-${e.tone}`,onClick:Qi,"aria-label":`${e.title} — open change history`,title:e.detail||e.title,children:[i("span",{class:"attention-toast-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"attention-toast-title",children:e.title},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var $c=null;function Rp(e){$c=e}function wt(){if($c?.isConnected){let e=$c.getBoundingClientRect();if(e.width>0&&e.height>0)return{left:e.left,top:e.top,width:e.width,height:e.height}}return{left:0,top:0,width:window.innerWidth,height:window.innerHeight}}function Fo(){let e=wt();return{x:e.left+e.width/2,y:e.top+e.height/2}}function Mc(){let e=16;try{let t=wt(),n=t.top+t.height;for(let o of[".command-bar",".minimap"]){let r=document.querySelector(o);if(!(r instanceof HTMLElement)||!r.isConnected)continue;let s=r.getBoundingClientRect();if(s.height<=0)continue;let a=n-s.top;if(a>0)e=Math.max(e,a+12)}}catch{}return{top:16,right:16,bottom:e,left:16}}var Mr=V(null),$p=0;function Yt(e,t,n={}){return new Promise((o)=>{Mr.value?.resolve(null),$p+=1,Mr.value={seq:$p,title:e,placeholder:t,initial:n.initial??"",allowEmpty:n.allowEmpty??!1,confirm:n.confirm??"Add",resolve:o}})}function $r(e){let t=Mr.value;Mr.value=null,t?.resolve(e)}function Mp(){let e=Mr.value,t=R(null);if(D(()=>{if(!e)return;let o=(r)=>{if(r.key!=="Escape")return;r.preventDefault(),r.stopPropagation(),$r(null)};return window.addEventListener("keydown",o,{capture:!0}),()=>window.removeEventListener("keydown",o,{capture:!0})},[e]),!e)return null;let n=()=>{let o=t.current?.value.trim()??"";$r(o?o:e.allowEmpty?"":null)};return i("div",{class:"text-prompt-backdrop",onPointerDown:()=>$r(null),children:i("div",{class:"text-prompt",role:"dialog","aria-label":e.title,"data-testid":"text-prompt",onPointerDown:(o)=>o.stopPropagation(),children:[i("div",{class:"text-prompt-title",children:e.title},void 0,!1,void 0,this),i("input",{ref:(o)=>{if(t.current=o,!o)return;if(o.focus(),e.initial)o.select()},class:"text-prompt-input",type:"text",defaultValue:e.initial,placeholder:e.placeholder,onKeyDown:(o)=>{if(o.key==="Enter")o.preventDefault(),o.stopPropagation(),n();else if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),$r(null)}},e.seq,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",onClick:()=>$r(null),children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"button",class:"text-prompt-confirm",onClick:n,children:e.confirm},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Oc(e,t){console.error(`[intent-bridge] ${e} failed`,t)}var ns=(()=>{try{let e=new URLSearchParams(window.location.search).get("agent")?.trim();return e?e.slice(0,64):null}catch{return null}})();function Lc(e){let t={...e?.headers};if(ns)t["x-pmx-source"]=ns;else t["X-PMX-Workbench"]="1";return{...e,headers:t}}async function ge(e,t,n,o){try{return await(await fetch(t,Lc(o))).json()}catch(r){return Oc(e,r),n}}async function Ct(e,t,n){try{return{ok:(await fetch(t,Lc(n))).ok}}catch(o){return Oc(e,o),{ok:!1}}}async function Ht(e,t,n){try{await fetch(t,Lc(n))}catch(o){Oc(e,o)}}async function Op(e,t={}){return ge("sendIntent","/api/workbench/intent",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:e,payload:t})})}async function io(e){let n=`Veto: do not ${e.label?.trim()||`${e.kind} intent`}${e.reason?` — ${e.reason}`:""}.`;if((await ge("vetoGhostIntent",`/api/canvas/ax/intent/${encodeURIComponent(e.id)}`,{ok:!1,cleared:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({vetoed:!0})})).cleared!==!0)return!1;return await Ht("vetoGhostSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:n,source:"browser"})}),!0}async function an(e){return(await ge("renderMarkdown","/api/render",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({markdown:e})})).html??""}async function Or(e){return ge("fetchFile",`/api/file?path=${encodeURIComponent(e)}`,{content:""})}async function Lp(e,t){return ge("saveFile","/api/file/save",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,content:t})})}async function os(e){return Ct("openWorkbenchFile","/api/workbench/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})})}async function rs(e){return ge("saveCanvasTheme","/api/canvas/theme",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:e})})}async function Dp(){return[]}async function Lr(e,t,n,o,r){if(!e.trim())return{ok:!1,error:"Prompt text is required"};return ge("submitCanvasPrompt","/api/canvas/prompt",{ok:!1,error:"Network error"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e,...t?{position:t}:{},...n?{parentNodeId:n}:{},...o&&o.length>0?{contextNodeIds:o}:{},...r?{threadNodeId:r}:{}})})}async function Fp(e,t){return Lr(t,void 0,void 0,void 0,e)}async function jp(e,t={}){await Ht("pushCanvasUpdate","/api/canvas/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e,...t.recordHistory===!1?{recordHistory:!1}:{}})})}async function so(e,t,n,o){return ge("createEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:t,type:n,label:o})})}async function Bt(e){return ge("createNodeFromClient","/api/canvas/node",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function rt(e,t){return ge("updateNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function is(e,t){return ge("refreshWebpageNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}/refresh`,{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{url:t}:{})})}async function In(e){return ge("removeNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"DELETE"})}async function Dc(){return ge("fetchAxSurfaceState","/api/canvas/ax/surface-snapshot",null)}async function Zp(){return ge("fetchAgentPresence","/api/canvas/ax/presence",null)}async function Hp(e,t){return ge("openNodeInSystemBrowserRequest","/api/canvas/open-external",{ok:!1,opened:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeId:e,url:t})})}async function ss(e){return ge("submitAxInteractionFromClient","/api/canvas/ax/interaction",{ok:!1,code:"request-failed",error:"Request failed"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceSurface:"native-node",...e,source:"browser"})})}async function Bp(e,t={}){return ge("updateViewportFromClient","/api/canvas/viewport",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...Up(),...t.recordHistory===!1?{recordHistory:!1}:{}})})}function Up(){if(typeof window>"u")return{};let e=wt(),t=Math.round(e.width),n=Math.round(e.height);if(!t||!n)return{};return{clientWidth:t,clientHeight:n}}async function Dr(){let e=Up();if(!("clientWidth"in e))return;await Ht("reportClientViewportSize","/api/canvas/viewport",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,recordHistory:!1})})}async function jo(e){return ge("createGroupFromClient","/api/canvas/group",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Fc(e,t,n){return ge("addToGroupFromClient","/api/canvas/group/add",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e,childIds:t,...n?{childLayout:n}:{}})})}async function as(e,t){return rt(e,{children:t})}async function Zo(e){return ge("ungroupFromClient","/api/canvas/group/ungroup",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e})})}async function Wp(){return ge("listSnapshots","/api/canvas/snapshots?all=true",[])}async function qp(e){return ge("saveSnapshot","/api/canvas/snapshots",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})})}async function Vp(e){return ge("restoreSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"POST"})}async function Gp(e){return ge("deleteSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"DELETE"})}async function cs(e,t){return ge("updateEdgeFromClient",`/api/canvas/edge/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function ls(e){return ge("removeEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({edge_id:e})})}var it={markdown:"MD","mcp-app":"APP",webpage:"WEB","json-render":"UI",graph:"GRAPH",prompt:"ASK",response:"ANS",status:"STATUS",context:"CONTEXT",ledger:"LOG",trace:"TRACE",file:"FILE",diff:"DIFF",mermaid:"MERMAID",image:"IMG",html:"HTML",group:"GROUP"},Fr=new Set(["markdown","mcp-app","webpage","json-render","graph","context","ledger","file","diff","mermaid","image","html"]);function Xp(e){return e.type==="mcp-app"&&e.data.mode==="ext-app"&&e.data.serverName==="Excalidraw"&&e.data.toolName==="create_view"}var p_=700,f_=1600;function m_(e){return e.replace(/\r\n?/g,`
22
+ `}}};Mn.tableCaption={filter:["caption"],replacement:()=>""};Mn.tableColgroup={filter:["colgroup","col"],replacement:()=>""};Mn.tableSection={filter:["thead","tbody","tfoot"],replacement:function(e){return e}};function CS(e){var t=e.parentNode;return t.nodeName==="THEAD"||t.firstChild===e&&(t.nodeName==="TABLE"||TS(t))&&_S.call(e.childNodes,function(n){return n.nodeName==="TH"})}function TS(e){var t=e.previousSibling;return e.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function Jf(e,t=null,n=null){if(n===null)n=wS.call(t.parentNode.childNodes,t);var o=" ";if(n===0)o="| ";let r=e.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");r=r.replace(/\|+/g,"\\|");while(r.length<3)r+=" ";if(t)r=AS(r,t," ");return o+r+" |"}function Yf(e){if(!e.childNodes)return!1;for(let t=0;t<e.childNodes.length;t++){let n=e.childNodes[t];if(n.nodeName==="TABLE")return!0;if(Yf(n))return!0}return!1}var dl=(e,t)=>{if(!e.childNodes)return!1;for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(t==="code"&&ul&&ul(o))return!0;if(t.includes(o.nodeName))return!0;if(dl(o,t))return!0}return!1},Qf=(e,t)=>{let n=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];if(t.preserveNestedTables)n.push("TABLE");return dl(e,"code")||dl(e,n)};function pl(e){let t=Wf.get(e);if(t!==void 0)return t;let n=ES(e);return Wf.set(e,n),n}function ES(e){if(!e)return!0;if(!e.rows)return!0;if(e.rows.length===1&&e.rows[0].childNodes.length<=1)return!0;if(Yf(e))return!0;return!1}function IS(e){let t=e.parentNode;while(t.nodeName!=="DIV")if(t=t.parentNode,!t)return null;return t}function em(e){let t=e.parentNode;while(t.nodeName!=="TABLE")if(t=t.parentNode,!t)return null;return t}function AS(e,t,n){let o=t.getAttribute("colspan")||1;for(let r=1;r<o;r++)e+=" | "+n.repeat(3);return e}function tm(e){let t=0;for(let n=0;n<e.rows.length;n++){let r=e.rows[n].childNodes.length;if(r>t)t=r}return t}function nm(e){ul=e.isCodeBlock,Gf=e.options,e.keep(function(n){if(n.nodeName==="TABLE"&&Qf(n,e.options))return!0;return!1});for(var t in Mn)e.addRule(t,Mn[t])}function om(e){e.addRule("taskListItems",{filter:function(t){let n=t.parentNode,o=n.parentNode;return t.type==="checkbox"&&(n.nodeName==="LI"||n.nodeName==="LABEL"&&o&&o.nodeName==="LI")},replacement:function(t,n){return(n.checked?"[x]":"[ ]")+" "}})}function zS(e){e.use([qf,Vf,nm,om])}rm.gfm=zS;rm.highlightedCodeBlock=qf;rm.strikethrough=Vf;rm.tables=nm;rm.taskListItems=om});if(typeof crypto<"u"&&typeof crypto.randomUUID!=="function")crypto.randomUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e)=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var ji,he,Yd,Cc,En,Gd,Qd,ep,tp,Tc,_c,Sc,qw,Li={},Di=[],Vw=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Zi=Array.isArray;function rn(e,t){for(var n in t)e[n]=t[n];return e}function Ec(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Gw(e,t,n){var o,r,s,a={};for(s in t)s=="key"?o=t[s]:s=="ref"?r=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?ji.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)a[s]===void 0&&(a[s]=e.defaultProps[s]);return Oi(e,a,o,r,null)}function Oi(e,t,n,o,r){var s={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r==null?++Yd:r,__i:-1,__u:0};return r==null&&he.vnode!=null&&he.vnode(s),s}function ve(e){return e.children}function Po(e,t){this.props=e,this.context=t}function No(e,t){if(t==null)return e.__?No(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?No(e):null}function Xw(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,o=[],r=[],s=rn({},t);s.__v=t.__v+1,he.vnode&&he.vnode(s),Ic(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,o,n==null?No(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,ip(o,s,r),t.__e=t.__=null,s.__e!=n&&np(s)}}function np(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),np(e)}function Xd(e){(!e.__d&&(e.__d=!0)&&En.push(e)&&!Fi.__r++||Gd!=he.debounceRendering)&&((Gd=he.debounceRendering)||Qd)(Fi)}function Fi(){try{for(var e,t=1;En.length;)En.length>t&&En.sort(ep),e=En.shift(),t=En.length,Xw(e)}finally{En.length=Fi.__r=0}}function op(e,t,n,o,r,s,a,c,l,u,d){var p,m,f,g,y,x,h,v=o&&o.__k||Di,b=t.length;for(l=Kw(n,t,v,l,b),p=0;p<b;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&v[f.__i]||Li,f.__i=p,x=Ic(e,f,m,r,s,a,c,l,u,d),g=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&Ac(m.ref,null,f),d.push(f.ref,f.__c||g,f)),y==null&&g!=null&&(y=g),(h=!!(4&f.__u))||m.__k===f.__k?l=rp(f,l,e,h):typeof f.type=="function"&&x!==void 0?l=x:g&&(l=g.nextSibling),f.__u&=-7);return n.__e=y,l}function Kw(e,t,n,o,r){var s,a,c,l,u,d=n.length,p=d,m=0;for(e.__k=Array(r),s=0;s<r;s++)(a=t[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=e.__k[s]=Oi(null,a,null,null,null):Zi(a)?a=e.__k[s]=Oi(ve,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=e.__k[s]=Oi(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+m,a.__=e,a.__b=e.__b+1,c=null,(u=a.__i=Jw(a,n,l,p))!=-1&&(p--,(c=n[u])&&(c.__u|=2)),c==null||c.__v==null?(u==-1&&(r>d?m--:r<d&&m++),typeof a.type!="function"&&(a.__u|=4)):u!=l&&(u==l-1?m--:u==l+1?m++:(u>l?m--:m++,a.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<d;s++)(c=n[s])!=null&&(2&c.__u)==0&&(c.__e==o&&(o=No(c)),ap(c,c));return o}function rp(e,t,n,o){var r,s;if(typeof e.type=="function"){for(r=e.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=e,t=rp(r[s],t,n,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=No(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Jw(e,t,n,o){var r,s,a,{key:c,type:l}=e,u=t[n],d=u!=null&&(2&u.__u)==0;if(u===null&&c==null||d&&c==u.key&&l==u.type)return n;if(o>(d?1:0)){for(r=n-1,s=n+1;r>=0||s<t.length;)if((u=t[a=r>=0?r--:s++])!=null&&(2&u.__u)==0&&c==u.key&&l==u.type)return a}return-1}function Kd(e,t,n){t[0]=="-"?e.setProperty(t,n==null?"":n):e[t]=n==null?"":typeof n!="number"||Vw.test(t)?n:n+"px"}function Mi(e,t,n,o,r){var s,a;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)n&&t in n||Kd(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||Kd(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(tp,"$1")),a=t.toLowerCase(),t=a in e||t=="onFocusOut"||t=="onFocusIn"?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?o?n.u=o.u:(n.u=Tc,e.addEventListener(t,s?Sc:_c,s)):e.removeEventListener(t,s?Sc:_c,s);else{if(r=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n==null?"":n;break e}catch(c){}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Jd(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=Tc++;else if(t.t<n.u)return;return n(he.event?he.event(t):t)}}}function Ic(e,t,n,o,r,s,a,c,l,u){var d,p,m,f,g,y,x,h,v,b,z,F,_,k,T,P=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),s=[c=t.__e=n.__e]),(d=he.__b)&&d(t);e:if(typeof P=="function")try{if(h=t.props,v=P.prototype&&P.prototype.render,b=(d=P.contextType)&&o[d.__c],z=d?b?b.props.value:d.__:o,n.__c?x=(p=t.__c=n.__c).__=p.__E:(v?t.__c=p=new P(h,z):(t.__c=p=new Po(h,z),p.constructor=P,p.render=Qw),b&&b.sub(p),p.state||(p.state={}),p.__n=o,m=p.__d=!0,p.__h=[],p._sb=[]),v&&p.__s==null&&(p.__s=p.state),v&&P.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=rn({},p.__s)),rn(p.__s,P.getDerivedStateFromProps(h,p.__s))),f=p.props,g=p.state,p.__v=t,m)v&&P.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),v&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(v&&P.getDerivedStateFromProps==null&&h!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(h,z),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(h,p.__s,z)===!1){t.__v!=n.__v&&(p.props=h,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(Z){Z&&(Z.__=t)}),Di.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&a.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(h,p.__s,z),v&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,g,y)})}if(p.context=z,p.props=h,p.__P=e,p.__e=!1,F=he.__r,_=0,v)p.state=p.__s,p.__d=!1,F&&F(t),d=p.render(p.props,p.state,p.context),Di.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,F&&F(t),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++_<25);p.state=p.__s,p.getChildContext!=null&&(o=rn(rn({},o),p.getChildContext())),v&&!m&&p.getSnapshotBeforeUpdate!=null&&(y=p.getSnapshotBeforeUpdate(f,g)),k=d!=null&&d.type===ve&&d.key==null?sp(d.props.children):d,c=op(e,Zi(k)?k:[k],t,n,o,r,s,a,c,l,u),p.base=t.__e,t.__u&=-161,p.__h.length&&a.push(p),x&&(p.__E=p.__=null)}catch(Z){if(t.__v=null,l||s!=null)if(Z.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;s[s.indexOf(c)]=null,t.__e=c}else{for(T=s.length;T--;)Ec(s[T]);kc(t)}else t.__e=n.__e,t.__k=n.__k,Z.then||kc(t);he.__e(Z,t,n)}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=Yw(n.__e,t,n,o,r,s,a,l,u);return(d=he.diffed)&&d(t),128&t.__u?void 0:c}function kc(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(kc))}function ip(e,t,n){for(var o=0;o<n.length;o++)Ac(n[o],n[++o],n[++o]);he.__c&&he.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(s){s.call(r)})}catch(s){he.__e(s,r.__v)}})}function sp(e){return typeof e!="object"||e==null||e.__b>0?e:Zi(e)?e.map(sp):rn({},e)}function Yw(e,t,n,o,r,s,a,c,l){var u,d,p,m,f,g,y,x=n.props||Li,{props:h,type:v}=t;if(v=="svg"?r="http://www.w3.org/2000/svg":v=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((f=s[u])&&"setAttribute"in f==!!v&&(v?f.localName==v:f.nodeType==3)){e=f,s[u]=null;break}}if(e==null){if(v==null)return document.createTextNode(h);e=document.createElementNS(r,v,h.is&&h),c&&(he.__m&&he.__m(t,s),c=!1),s=null}if(v==null)x===h||c&&e.data==h||(e.data=h);else{if(s=s&&ji.call(e.childNodes),!c&&s!=null)for(x={},u=0;u<e.attributes.length;u++)x[(f=e.attributes[u]).name]=f.value;for(u in x)f=x[u],u=="dangerouslySetInnerHTML"?p=f:u=="children"||(u in h)||u=="value"&&("defaultValue"in h)||u=="checked"&&("defaultChecked"in h)||Mi(e,u,null,f,r);for(u in h)f=h[u],u=="children"?m=f:u=="dangerouslySetInnerHTML"?d=f:u=="value"?g=f:u=="checked"?y=f:c&&typeof f!="function"||x[u]===f||Mi(e,u,f,x[u],r);if(d)c||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),op(t.type=="template"?e.content:e,Zi(m)?m:[m],t,n,o,v=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&No(n,0),c,l),s!=null)for(u=s.length;u--;)Ec(s[u]);c||(u="value",v=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[u]||v=="progress"&&!g||v=="option"&&g!=x[u])&&Mi(e,u,g,x[u],r),u="checked",y!=null&&y!=e[u]&&Mi(e,u,y,x[u],r))}return e}function Ac(e,t,n){try{if(typeof e=="function"){var o=typeof e.__u=="function";o&&e.__u(),o&&t==null||(e.__u=e(t))}else e.current=t}catch(r){he.__e(r,n)}}function ap(e,t,n){var o,r;if(he.unmount&&he.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Ac(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){he.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(r=0;r<o.length;r++)o[r]&&ap(o[r],t,n||typeof e.type!="function");n||Ec(e.__e),e.__c=e.__=e.__e=void 0}function Qw(e,t,n){return this.constructor(e,n)}function cp(e,t,n){var o,r,s,a;t==document&&(t=document.documentElement),he.__&&he.__(e,t),r=(o=typeof n=="function")?null:n&&n.__k||t.__k,s=[],a=[],Ic(t,e=(!o&&n||t).__k=Gw(ve,null,[e]),r||Li,Li,t.namespaceURI,!o&&n?[n]:r?null:t.firstChild?ji.call(t.childNodes):null,s,!o&&n?n:r?r.__e:t.firstChild,o,a),ip(s,e,a)}ji=Di.slice,he={__e:function(e,t,n,o){for(var r,s,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(e)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(e,o||{}),a=r.__d),a)return r.__E=r}catch(c){e=c}throw e}},Yd=0,Cc=function(e){return e!=null&&e.constructor===void 0},Po.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=rn({},this.state),typeof e=="function"&&(e=e(rn({},n),this.props)),e&&rn(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Xd(this))},Po.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Xd(this))},Po.prototype.render=ve,En=[],Qd=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ep=function(e,t){return e.__v.__b-t.__v.__b},Fi.__r=0,tp=/(PointerCapture)$|Capture$/i,Tc=0,_c=Jd(!1),Sc=Jd(!0),qw=0;var Ro,qe,zc,lp,Pr=0,vp=[],Ge=he,{__b:up,__r:dp,diffed:pp,__c:fp,unmount:mp,__:hp}=Ge;function Bi(e,t){Ge.__h&&Ge.__h(qe,e,Pr||t),Pr=0;var n=qe.__H||(qe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function L(e){return Pr=1,e_(yp,e)}function e_(e,t,n){var o=Bi(Ro++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):yp(void 0,t),function(c){var l=o.__N?o.__N[0]:o.__[0],u=o.t(l,c);l!==u&&(o.__N=[u,o.__[1]],o.__c.setState({}))}],o.__c=qe,!qe.__f)){var r=function(c,l,u){if(!o.__c.__H)return!0;var d=o.__c.__H.__.filter(function(m){return m.__c});if(d.every(function(m){return!m.__N}))return!s||s.call(this,c,l,u);var p=o.__c.props!==c;return d.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),s&&s.call(this,c,l,u)||p};qe.__f=!0;var s=qe.shouldComponentUpdate,a=qe.componentWillUpdate;qe.componentWillUpdate=function(c,l,u){if(this.__e){var d=s;s=void 0,r(c,l,u),s=d}a&&a.call(this,c,l,u)},qe.shouldComponentUpdate=r}return o.__N||o.__}function D(e,t){var n=Bi(Ro++,3);!Ge.__s&&Nc(n.__H,t)&&(n.__=e,n.u=t,qe.__H.__h.push(n))}function Ui(e,t){var n=Bi(Ro++,4);!Ge.__s&&Nc(n.__H,t)&&(n.__=e,n.u=t,qe.__h.push(n))}function M(e){return Pr=5,Ae(function(){return{current:e}},[])}function Ae(e,t){var n=Bi(Ro++,7);return Nc(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function O(e,t){return Pr=8,Ae(function(){return e},t)}function t_(){for(var e;e=vp.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Hi),t.__h.some(Pc),t.__h=[]}catch(n){t.__h=[],Ge.__e(n,e.__v)}}}Ge.__b=function(e){qe=null,up&&up(e)},Ge.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),hp&&hp(e,t)},Ge.__r=function(e){dp&&dp(e),Ro=0;var t=(qe=e.__c).__H;t&&(zc===qe?(t.__h=[],qe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Hi),t.__h.some(Pc),t.__h=[],Ro=0)),zc=qe},Ge.diffed=function(e){pp&&pp(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(vp.push(t)!==1&&lp===Ge.requestAnimationFrame||((lp=Ge.requestAnimationFrame)||n_)(t_)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),zc=qe=null},Ge.__c=function(e,t){t.some(function(n){try{n.__h.some(Hi),n.__h=n.__h.filter(function(o){return!o.__||Pc(o)})}catch(o){t.some(function(r){r.__h&&(r.__h=[])}),t=[],Ge.__e(o,n.__v)}}),fp&&fp(e,t)},Ge.unmount=function(e){mp&&mp(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(o){try{Hi(o)}catch(r){t=r}}),n.__H=void 0,t&&Ge.__e(t,n.__v))};var gp=typeof requestAnimationFrame=="function";function n_(e){var t,n=function(){clearTimeout(o),gp&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);gp&&(t=requestAnimationFrame(n))}function Hi(e){var t=qe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),qe=t}function Pc(e){var t=qe;e.__c=e.__(),qe=t}function Nc(e,t){return!e||e.length!==t.length||t.some(function(n,o){return n!==e[o]})}function yp(e,t){return typeof t=="function"?t(e):t}var o_=Symbol.for("preact-signals");function Gi(){if(!(sn>1)){var e,t=!1;(function(){var r=qi;qi=void 0;while(r!==void 0){if(r.S.v===r.v)r.S.i=r.i;r=r.o}})();while(Nr!==void 0){var n=Nr;Nr=void 0,Wi++;while(n!==void 0){var o=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&wp(n))try{n.c()}catch(r){if(!t)e=r,t=!0}n=o}}if(Wi=0,sn--,t)throw e}else sn--}function $t(e){if(sn>0)return e();Rc=++r_,sn++;try{return e()}finally{Gi()}}var _e=void 0;function $c(e){var t=_e;_e=void 0;try{return e()}finally{_e=t}}var xp,Nr=void 0,sn=0,Wi=0,r_=0,Rc=0,qi=void 0,Vi=0;function bp(e){if(_e!==void 0){var t=e.n;if(t===void 0||t.t!==_e){if(t={i:0,S:e,p:_e.s,n:void 0,t:_e,e:void 0,x:void 0,r:t},_e.s!==void 0)_e.s.n=t;if(_e.s=t,e.n=t,32&_e.f)e.S(t);return t}else if(t.i===-1){if(t.i=0,t.n!==void 0){if(t.n.p=t.p,t.p!==void 0)t.p.n=t.n;t.p=_e.s,t.n=void 0,_e.s.n=t,_e.s=t}return t}}}function Qe(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t==null?void 0:t.watched,this.Z=t==null?void 0:t.unwatched,this.name=t==null?void 0:t.name}Qe.prototype.brand=o_;Qe.prototype.h=function(){return!0};Qe.prototype.S=function(e){var t=this,n=this.t;if(n!==e&&e.e===void 0)if(e.x=n,this.t=e,n!==void 0)n.e=e;else $c(function(){var o;(o=t.W)==null||o.call(t)})};Qe.prototype.U=function(e){var t=this;if(this.t!==void 0){var{e:n,x:o}=e;if(n!==void 0)n.x=o,e.e=void 0;if(o!==void 0)o.e=n,e.x=void 0;if(e===this.t){if(this.t=o,o===void 0)$c(function(){var r;(r=t.Z)==null||r.call(t)})}}};Qe.prototype.subscribe=function(e){var t=this;return Mt(function(){var n=t.value,o=_e;_e=void 0;try{e(n)}finally{_e=o}},{name:"sub"})};Qe.prototype.valueOf=function(){return this.value};Qe.prototype.toString=function(){return this.value+""};Qe.prototype.toJSON=function(){return this.value};Qe.prototype.peek=function(){var e=_e;_e=void 0;try{return this.value}finally{_e=e}};Object.defineProperty(Qe.prototype,"value",{get:function(){var e=bp(this);if(e!==void 0)e.i=this.i;return this.v},set:function(e){if(e!==this.v){if(Wi>100)throw Error("Cycle detected");(function(n){if(sn!==0&&Wi===0){if(n.l!==Rc)n.l=Rc,qi={S:n,v:n.v,i:n.i,o:qi}}})(this),this.v=e,this.i++,Vi++,sn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Gi()}}}});function V(e,t){return new Qe(e,t)}function wp(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function _p(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0)t.r=n;if(t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function Sp(e){var t=e.s,n=void 0;while(t!==void 0){var o=t.p;if(t.i===-1){if(t.S.U(t),o!==void 0)o.n=t.n;if(t.n!==void 0)t.n.p=o}else n=t;if(t.S.n=t.r,t.r!==void 0)t.r=void 0;t=o}e.s=n}function ro(e,t){Qe.call(this,void 0),this.x=e,this.s=void 0,this.g=Vi-1,this.f=4,this.W=t==null?void 0:t.watched,this.Z=t==null?void 0:t.unwatched,this.name=t==null?void 0:t.name}ro.prototype=new Qe;ro.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32)return!0;if(this.f&=-5,this.g===Vi)return!0;if(this.g=Vi,this.f|=1,this.i>0&&!wp(this))return this.f&=-2,!0;var e=_e;try{_p(this),_e=this;var t=this.x();if(16&this.f||this.v!==t||this.i===0)this.v=t,this.f&=-17,this.i++}catch(n){this.v=n,this.f|=16,this.i++}return _e=e,Sp(this),this.f&=-2,!0};ro.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}Qe.prototype.S.call(this,e)};ro.prototype.U=function(e){if(this.t!==void 0){if(Qe.prototype.U.call(this,e),this.t===void 0){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}}};ro.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}};Object.defineProperty(ro.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=bp(this);if(this.h(),e!==void 0)e.i=this.i;if(16&this.f)throw this.v;return this.v}});function Oe(e,t){return new ro(e,t)}function kp(e){var t=e.m;if(e.m=void 0,typeof t=="function"){sn++;var n=_e;_e=void 0;try{t()}catch(o){throw e.f&=-2,e.f|=8,Mc(e),o}finally{_e=n,Gi()}}}function Mc(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,kp(e)}function i_(e){if(_e!==this)throw Error("Out-of-order effect");if(Sp(this),_e=e,this.f&=-2,8&this.f)Mc(this);Gi()}function $o(e,t){if(this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t==null?void 0:t.name,xp)xp.push(this)}$o.prototype.c=function(){var e=this.S();try{if(8&this.f)return;if(this.x===void 0)return;var t=this.x();if(typeof t=="function")this.m=t}finally{e()}};$o.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,kp(this),_p(this),sn++;var e=_e;return _e=this,i_.bind(this,e)};$o.prototype.N=function(){if(!(2&this.f))this.f|=2,this.u=Nr,Nr=this};$o.prototype.d=function(){if(this.f|=8,!(1&this.f))Mc(this)};$o.prototype.dispose=function(){this.d()};function Mt(e,t){var n=new $o(e,t);try{n.c()}catch(r){throw n.d(),r}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Cp,Oc,Xi,s_=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__;var Tp=[];Mt(function(){Cp=this.N})();function Mo(e,t){he[e]=t.bind(null,he[e]||function(){})}function Ki(e){if(Xi){var t=Xi;Xi=void 0,t()}Xi=e&&e.S()}function Ep(e){var t=this,n=e.data,o=c_(n);o.value=n;var r=Ae(function(){var c=t,l=t.__v;while(l=l.__)if(l.__c){l.__c.__$f|=4;break}var u=Oe(function(){var f=o.value.value;return f===0?0:f===!0?"":f||""}),d=Oe(function(){return!Array.isArray(u.value)&&!Cc(u.value)}),p=Mt(function(){if(this.N=Ip,d.value){var f=u.value;if(c.__v&&c.__v.__e&&c.__v.__e.nodeType===3)c.__v.__e.data=f}}),m=t.__$u.d;return t.__$u.d=function(){p(),m.call(this)},[d,u]},[]),s=r[0],a=r[1];return s.value?a.peek():a.value}Ep.displayName="ReactiveTextNode";Object.defineProperties(Qe.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ep},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}});Mo("__b",function(e,t){if(typeof t.type=="string"){var n,o=t.props;for(var r in o)if(r!=="children"){var s=o[r];if(s instanceof Qe){if(!n)t.__np=n={};n[r]=s,o[r]=s.peek()}}}e(t)});Mo("__r",function(e,t){if(e(t),t.type!==ve){Ki();var n,o=t.__c;if(o){if(o.__$f&=-2,(n=o.__$u)===void 0)o.__$u=n=function(r,s){var a;return Mt(function(){a=this},{name:s}),a.c=r,a}(function(){var r;if(s_)(r=n.y)==null||r.call(n);o.__$f|=1,o.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:"")}Oc=o,Ki(n)}});Mo("__e",function(e,t,n,o){Ki(),Oc=void 0,e(t,n,o)});Mo("diffed",function(e,t){Ki(),Oc=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var{__np:o,props:r}=t;if(o){var s=n.U;if(s)for(var a in s){var c=s[a];if(c!==void 0&&!(a in o))c.d(),s[a]=void 0}else s={},n.U=s;for(var l in o){var u=s[l],d=o[l];if(u===void 0)u=a_(n,l,d),s[l]=u;else u.o(d,r)}for(var p in o)r[p]=o[p]}}e(t)});function a_(e,t,n,o){var r=t in e&&e.ownerSVGElement===void 0,s=V(n),a=n.peek();return{o:function(c,l){s.value=c,a=c.peek()},d:Mt(function(){this.N=Ip;var c=s.value.value;if(a!==c)if(a=void 0,r)e[t]=c;else if(c!=null&&(c!==!1||t[4]==="-"))e.setAttribute(t,c);else e.removeAttribute(t);else a=void 0})}}Mo("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var o=n.U;if(o){n.U=void 0;for(var r in o){var s=o[r];if(s)s.d()}}}t.__np=void 0}else{var a=t.__c;if(a){var c=a.__$u;if(c)a.__$u=void 0,c.d()}}e(t)});Mo("__h",function(e,t,n,o){if(o<3||o===9)t.__$f|=2;e(t,n,o)});Po.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var r in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(o||s||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(o||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var a in e)if(a!=="__source"&&e[a]!==this.props[a])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function c_(e,t){return Ae(function(){return V(e,t)},[])}var l_=function(e){queueMicrotask(function(){queueMicrotask(e)})};function u_(){$t(function(){var e;while(e=Tp.shift())Cp.call(e)})}function Ip(){if(Tp.push(this)===1)(he.requestAnimationFrame||l_)(u_)}var Ji=V(null),Rr=V([]),Lo=V(new Set),Do=V(new Set),Yi=V([]),Qi=V(new Set),Jt=V(!1),Oo=V(0);function Ap(){Ji.value=null,Rr.value=[],Lo.value=new Set,Do.value=new Set,Yi.value=[],Qi.value=new Set,Jt.value=!1,Oo.value=0}function es(){Jt.value=!0,Oo.value=0}function zp(){Jt.value=!1}function Pp(e,t,n){Lo.value=new Set(e),Do.value=new Set(t),Yi.value=n}function ts(e){Ji.value=e}function Np(e,t=6){if(Rr.value=[e,...Rr.value].slice(0,t),!Jt.value)Oo.value=Math.min(99,Oo.value+1)}function ns(e){Qi.value=new Set(e)}var d_=0;function i(e,t,n,o,r,s){t||(t={});var a,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?a=t[c]:l[c]=t[c];var u={type:e,props:l,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--d_,__i:-1,__u:0,__source:r,__self:s};if(typeof e=="function"&&(a=e.defaultProps))for(c in a)l[c]===void 0&&(l[c]=a[c]);return he.vnode&&he.vnode(u),u}function p_(e){return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function f_(){es()}function Rp(){let e=Rr.value;if(e.length===0)return null;let t=Jt.value,n=Oo.value;if(!t)return i("button",{type:"button",class:"attention-history-tab",onClick:f_,"aria-label":n>0?`Recent updates — ${n} new`:"Recent updates",title:n>0?`${n} new updates since last viewed`:"Recent updates",children:[i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"attention-history-tab-label",children:"Updates"},void 0,!1,void 0,this),n>0&&i("span",{class:"attention-history-tab-badge","aria-hidden":"true",children:n>9?"9+":n},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("aside",{class:"attention-history","aria-label":"Recent semantic changes",children:[i("div",{class:"attention-history-header",children:[i("div",{class:"attention-history-header-text",children:[i("span",{class:"attention-history-title",children:"Recent Updates"},void 0,!1,void 0,this),i("span",{class:"attention-history-subtitle",children:"Focus and meaning shifts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"attention-history-close",onClick:zp,"aria-label":"Collapse changes panel",title:"Collapse",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"attention-history-list",children:e.map((o)=>i("article",{class:`attention-history-entry attention-tone-${o.tone}`,children:[i("div",{class:"attention-history-meta",children:[i("span",{class:"attention-history-kind",children:o.title},void 0,!1,void 0,this),i("time",{class:"attention-history-time",dateTime:new Date(o.createdAt).toISOString(),children:p_(o.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("p",{class:"attention-history-detail",children:o.detail},void 0,!1,void 0,this)]},o.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function $p(){let e=Ji.value;if(!e)return null;return i("button",{type:"button",class:`attention-toast attention-tone-${e.tone}`,onClick:es,"aria-label":`${e.title} — open change history`,title:e.detail||e.title,children:[i("span",{class:"attention-toast-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"attention-toast-title",children:e.title},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Lc=null;function Mp(e){Lc=e}function wt(){if(Lc?.isConnected){let e=Lc.getBoundingClientRect();if(e.width>0&&e.height>0)return{left:e.left,top:e.top,width:e.width,height:e.height}}return{left:0,top:0,width:window.innerWidth,height:window.innerHeight}}function Fo(){let e=wt();return{x:e.left+e.width/2,y:e.top+e.height/2}}function Dc(){let e=16;try{let t=wt(),n=t.top+t.height;for(let o of[".command-bar",".minimap"]){let r=document.querySelector(o);if(!(r instanceof HTMLElement)||!r.isConnected)continue;let s=r.getBoundingClientRect();if(s.height<=0)continue;let a=n-s.top;if(a>0)e=Math.max(e,a+12)}}catch{}return{top:16,right:16,bottom:e,left:16}}var Mr=V(null),Op=0;function Yt(e,t,n={}){return new Promise((o)=>{Mr.value?.resolve(null),Op+=1,Mr.value={seq:Op,title:e,placeholder:t,initial:n.initial??"",allowEmpty:n.allowEmpty??!1,confirm:n.confirm??"Add",resolve:o}})}function $r(e){let t=Mr.value;Mr.value=null,t?.resolve(e)}function Lp(){let e=Mr.value,t=M(null);if(D(()=>{if(!e)return;let o=(r)=>{if(r.key!=="Escape")return;r.preventDefault(),r.stopPropagation(),$r(null)};return window.addEventListener("keydown",o,{capture:!0}),()=>window.removeEventListener("keydown",o,{capture:!0})},[e]),!e)return null;let n=()=>{let o=t.current?.value.trim()??"";$r(o?o:e.allowEmpty?"":null)};return i("div",{class:"text-prompt-backdrop",onPointerDown:()=>$r(null),children:i("div",{class:"text-prompt",role:"dialog","aria-label":e.title,"data-testid":"text-prompt",onPointerDown:(o)=>o.stopPropagation(),children:[i("div",{class:"text-prompt-title",children:e.title},void 0,!1,void 0,this),i("input",{ref:(o)=>{if(t.current=o,!o)return;if(o.focus(),e.initial)o.select()},class:"text-prompt-input",type:"text",defaultValue:e.initial,placeholder:e.placeholder,onKeyDown:(o)=>{if(o.key==="Enter")o.preventDefault(),o.stopPropagation(),n();else if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),$r(null)}},e.seq,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",onClick:()=>$r(null),children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"button",class:"text-prompt-confirm",onClick:n,children:e.confirm},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Fc(e,t){console.error(`[intent-bridge] ${e} failed`,t)}var os=(()=>{try{let e=new URLSearchParams(window.location.search).get("agent")?.trim();return e?e.slice(0,64):null}catch{return null}})();function jc(e){let t={...e?.headers};if(os)t["x-pmx-source"]=os;else t["X-PMX-Workbench"]="1";return{...e,headers:t}}async function ge(e,t,n,o){try{return await(await fetch(t,jc(o))).json()}catch(r){return Fc(e,r),n}}async function Ct(e,t,n){try{return{ok:(await fetch(t,jc(n))).ok}}catch(o){return Fc(e,o),{ok:!1}}}async function Bt(e,t,n){try{await fetch(t,jc(n))}catch(o){Fc(e,o)}}async function Dp(e,t={}){return ge("sendIntent","/api/workbench/intent",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:e,payload:t})})}async function io(e){let n=`Veto: do not ${e.label?.trim()||`${e.kind} intent`}${e.reason?` — ${e.reason}`:""}.`;if((await ge("vetoGhostIntent",`/api/canvas/ax/intent/${encodeURIComponent(e.id)}`,{ok:!1,cleared:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({vetoed:!0})})).cleared!==!0)return!1;return await Bt("vetoGhostSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:n,source:"browser"})}),!0}async function an(e){return(await ge("renderMarkdown","/api/render",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({markdown:e})})).html??""}async function Or(e){return ge("fetchFile",`/api/file?path=${encodeURIComponent(e)}`,{content:""})}async function Fp(e,t){return ge("saveFile","/api/file/save",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,content:t})})}async function rs(e){return Ct("openWorkbenchFile","/api/workbench/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})})}async function is(e){return ge("saveCanvasTheme","/api/canvas/theme",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:e})})}async function jp(){return[]}async function Lr(e,t,n,o,r){if(!e.trim())return{ok:!1,error:"Prompt text is required"};return ge("submitCanvasPrompt","/api/canvas/prompt",{ok:!1,error:"Network error"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e,...t?{position:t}:{},...n?{parentNodeId:n}:{},...o&&o.length>0?{contextNodeIds:o}:{},...r?{threadNodeId:r}:{}})})}async function Zp(e,t){return Lr(t,void 0,void 0,void 0,e)}async function ss(e,t={}){await Bt("pushCanvasUpdate","/api/canvas/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e,...t.recordHistory===!1?{recordHistory:!1}:{}})})}async function so(e,t,n,o){return ge("createEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:t,type:n,label:o})})}async function Ut(e){return ge("createNodeFromClient","/api/canvas/node",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function it(e,t){return ge("updateNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function as(e,t){return ge("refreshWebpageNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}/refresh`,{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{url:t}:{})})}async function In(e){return ge("removeNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"DELETE"})}async function Zc(){return ge("fetchAxSurfaceState","/api/canvas/ax/surface-snapshot",null)}async function Hp(){return ge("fetchAgentPresence","/api/canvas/ax/presence",null)}async function Bp(e,t){return ge("openNodeInSystemBrowserRequest","/api/canvas/open-external",{ok:!1,opened:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeId:e,url:t})})}async function cs(e){return ge("submitAxInteractionFromClient","/api/canvas/ax/interaction",{ok:!1,code:"request-failed",error:"Request failed"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceSurface:"native-node",...e,source:"browser"})})}async function Up(e,t={}){return ge("updateViewportFromClient","/api/canvas/viewport",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...Wp(),...t.recordHistory===!1?{recordHistory:!1}:{}})})}function Wp(){if(typeof window>"u")return{};let e=wt(),t=Math.round(e.width),n=Math.round(e.height);if(!t||!n)return{};return{clientWidth:t,clientHeight:n}}async function Dr(){let e=Wp();if(!("clientWidth"in e))return;await Bt("reportClientViewportSize","/api/canvas/viewport",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,recordHistory:!1})})}async function jo(e){return ge("createGroupFromClient","/api/canvas/group",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Hc(e,t,n){return ge("addToGroupFromClient","/api/canvas/group/add",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e,childIds:t,...n?{childLayout:n}:{}})})}async function ls(e,t){return it(e,{children:t})}async function Zo(e){return ge("ungroupFromClient","/api/canvas/group/ungroup",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e})})}async function qp(){return ge("listSnapshots","/api/canvas/snapshots?all=true",[])}async function Vp(e){return ge("saveSnapshot","/api/canvas/snapshots",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})})}async function Gp(e){return ge("restoreSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"POST"})}async function Xp(e){return ge("deleteSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"DELETE"})}async function us(e,t){return ge("updateEdgeFromClient",`/api/canvas/edge/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function ds(e){return ge("removeEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({edge_id:e})})}var st={markdown:"MD","mcp-app":"APP",webpage:"WEB","json-render":"UI",graph:"GRAPH",prompt:"ASK",response:"ANS",status:"STATUS",context:"CONTEXT",ledger:"LOG",trace:"TRACE",file:"FILE",diff:"DIFF",mermaid:"MERMAID",image:"IMG",html:"HTML",group:"GROUP"},Fr=new Set(["markdown","mcp-app","webpage","json-render","graph","context","ledger","file","diff","mermaid","image","html"]);function Kp(e){return e.type==="mcp-app"&&e.data.mode==="ext-app"&&e.data.serverName==="Excalidraw"&&e.data.toolName==="create_view"}var m_=700,h_=1600;function g_(e){return e.replace(/\r\n?/g,`
23
23
  `).replace(/[ \t\f\v]+/g," ").replace(/\n\s+/g,`
24
24
  `).replace(/\s+\n/g,`
25
25
  `).replace(/\n{3,}/g,`
26
26
 
27
- `).trim()}function _t(e,t){if(t<=0)return"";let n=m_(e);if(n.length<=t)return n;if(t<=1)return n.slice(0,t);return`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`}function us(e,t){if(typeof e==="string")return _t(e,t);if(e===null||e===void 0)return"";try{return _t(JSON.stringify(e),t)}catch{return""}}function h_(e,t){let n=[],o=typeof e.url==="string"?e.url:"",r=typeof e.pageTitle==="string"?e.pageTitle:"",s=typeof e.description==="string"?e.description:"",a=typeof e.status==="string"?e.status:"",c=typeof e.statusCode==="number"?e.statusCode:null,l=typeof e.error==="string"?e.error:"",u=typeof e.content==="string"?e.content:typeof e.excerpt==="string"?e.excerpt:"";if(o)n.push(`URL: ${o}`);if(r)n.push(`Title: ${r}`);if(s)n.push(`Description: ${s}`);if(a||c!==null)n.push(`Fetch: ${a||"unknown"}${c!==null?` (${c})`:""}`);if(l)n.push(`Error: ${l}`);let d=n.join(`
27
+ `).trim()}function _t(e,t){if(t<=0)return"";let n=g_(e);if(n.length<=t)return n;if(t<=1)return n.slice(0,t);return`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`}function ps(e,t){if(typeof e==="string")return _t(e,t);if(e===null||e===void 0)return"";try{return _t(JSON.stringify(e),t)}catch{return""}}function v_(e,t){let n=[],o=typeof e.url==="string"?e.url:"",r=typeof e.pageTitle==="string"?e.pageTitle:"",s=typeof e.description==="string"?e.description:"",a=typeof e.status==="string"?e.status:"",c=typeof e.statusCode==="number"?e.statusCode:null,l=typeof e.error==="string"?e.error:"",u=typeof e.content==="string"?e.content:typeof e.excerpt==="string"?e.excerpt:"";if(o)n.push(`URL: ${o}`);if(r)n.push(`Title: ${r}`);if(s)n.push(`Description: ${s}`);if(a||c!==null)n.push(`Fetch: ${a||"unknown"}${c!==null?` (${c})`:""}`);if(l)n.push(`Error: ${l}`);let d=n.join(`
28
28
  `),p=Math.max(0,t-d.length-(d?2:0)),m=p>0?_t(u,p):"";if(d&&m)return`${d}
29
29
 
30
- ${m}`;if(d)return _t(d,t);return _t(u,t)}function g_(e){if(e===null||e===void 0)return"";if(typeof e!=="object"||Array.isArray(e))return"";let t=e.elements;if(Array.isArray(t))return`Diagram elements: ${t.length}`;let n=Object.keys(e).sort();return n.length>0?`Input keys: ${n.join(", ")}`:""}function v_(e,t){let n=[],o=typeof e.title==="string"?e.title:"",r=typeof e.mode==="string"?e.mode:"",s=typeof e.hostMode==="string"?e.hostMode:"",a=typeof e.serverName==="string"?e.serverName:"",c=typeof e.toolName==="string"?e.toolName:"",l=typeof e.resourceUri==="string"?e.resourceUri:"",u=typeof e.path==="string"?e.path:"",d=typeof e.url==="string"?e.url:"",p=typeof e.sessionStatus==="string"?e.sessionStatus:"",m=g_(e.toolInput);if(o)n.push(`App: ${o}`);if(r||s)n.push(`Mode: ${[r,s].filter(Boolean).join(" / ")}`);if(a||c)n.push(`Source: ${[a,c].filter(Boolean).join(" / ")}`);if(l)n.push(`Resource: ${l}`);if(u)n.push(`Path: ${u}`);if(d)n.push(`URL: ${d}`);if(p)n.push(`Session: ${p}`);if(m)n.push(m);if(n.length===0)return"MCP App node";return _t(n.join(`
31
- `),t)}function y_(e,t){let n=[],o=typeof e.content==="string"?e.content:"",r=typeof e.title==="string"?e.title:"",s=typeof e.path==="string"?e.path:"",a=typeof e.url==="string"?e.url:"",c=typeof e.projectPath==="string"?e.projectPath:"",l=typeof e.artifactBytes==="number"?e.artifactBytes:null,u=typeof e.sourceFileCount==="number"?e.sourceFileCount:null,d=Array.isArray(e.sourceFiles)?e.sourceFiles.filter((m)=>typeof m==="string"):[],p=Array.isArray(e.deps)?e.deps.filter((m)=>typeof m==="string"):[];if(o)n.push(o);if(!o&&r)n.push(`Web artifact: ${r}`);if(d.length>0&&!o.includes("Source files:")){let m=u!==null?Math.max(0,u-d.length):0;n.push(`Source files: ${d.join(", ")}${m>0?`, +${m} more`:""}`)}if(l!==null&&!o.includes("Artifact bytes:"))n.push(`Artifact bytes: ${l}`);if(p.length>0&&!o.includes("Dependencies:"))n.push(`Dependencies: ${p.join(", ")}`);if(s)n.push(`Path: ${s}`);if(c)n.push(`Project: ${c}`);if(a)n.push(`URL: ${a}`);return n.length>0?_t(n.join(`
32
- `),t):"Web artifact node"}function x_(e,t){let n=[],o=typeof e.htmlPrimitive==="string"?e.htmlPrimitive:"",r=typeof e.description==="string"?e.description:"",s=e.primitiveData;if(o)n.push(`HTML primitive: ${o}`);if(r)n.push(r);if(s!==void 0)n.push(`Data: ${us(s,t)}`);return _t(n.join(`
33
- `),t)}function Kp(e,t={}){let n=t.defaultTextLength??p_,o=t.webpageTextLength??f_;switch(e.type){case"markdown":{let r=e.data.rendered||e.data.content||"";return _t(r,n)}case"mcp-app":{if(e.data.viewerType==="web-artifact")return y_(e.data,n);let r=e.data.chartConfig;if(r){let s=r.title||"Untitled chart",a=r.type||"unknown",c=Array.isArray(r.labels)?r.labels.join(", "):"";return _t(`Chart: ${s} (${a}). Labels: ${c}`,n)}return v_(e.data,n)}case"webpage":return h_(e.data,o);case"json-render":case"graph":{let r=e.data.graphConfig;if(r)return _t(`Graph: ${JSON.stringify(r)}`,n);return us(e.data.spec??{},n)}case"html":{if(typeof e.data.agentSummary==="string")return _t(e.data.agentSummary,n);if(typeof e.data.htmlPrimitive==="string")return x_(e.data,n);return us({title:e.data.title,description:e.data.description,summary:e.data.summary,contentSummary:e.data.contentSummary,embeddedNodeIds:e.data.embeddedNodeIds,embeddedUrls:e.data.embeddedUrls},n)}case"prompt":case"response":{let r=e.data.text||e.data.content||"";return _t(r,n)}case"file":{let r=typeof e.data.path==="string"?e.data.path:"",s=typeof e.data.fileContent==="string"?e.data.fileContent:typeof e.data.content==="string"?e.data.content:"",a=r?`Path: ${r}
30
+ ${m}`;if(d)return _t(d,t);return _t(u,t)}function y_(e){if(e===null||e===void 0)return"";if(typeof e!=="object"||Array.isArray(e))return"";let t=e.elements;if(Array.isArray(t))return`Diagram elements: ${t.length}`;let n=Object.keys(e).sort();return n.length>0?`Input keys: ${n.join(", ")}`:""}function x_(e,t){let n=[],o=typeof e.title==="string"?e.title:"",r=typeof e.mode==="string"?e.mode:"",s=typeof e.hostMode==="string"?e.hostMode:"",a=typeof e.serverName==="string"?e.serverName:"",c=typeof e.toolName==="string"?e.toolName:"",l=typeof e.resourceUri==="string"?e.resourceUri:"",u=typeof e.path==="string"?e.path:"",d=typeof e.url==="string"?e.url:"",p=typeof e.sessionStatus==="string"?e.sessionStatus:"",m=y_(e.toolInput);if(o)n.push(`App: ${o}`);if(r||s)n.push(`Mode: ${[r,s].filter(Boolean).join(" / ")}`);if(a||c)n.push(`Source: ${[a,c].filter(Boolean).join(" / ")}`);if(l)n.push(`Resource: ${l}`);if(u)n.push(`Path: ${u}`);if(d)n.push(`URL: ${d}`);if(p)n.push(`Session: ${p}`);if(m)n.push(m);if(n.length===0)return"MCP App node";return _t(n.join(`
31
+ `),t)}function b_(e,t){let n=[],o=typeof e.content==="string"?e.content:"",r=typeof e.title==="string"?e.title:"",s=typeof e.path==="string"?e.path:"",a=typeof e.url==="string"?e.url:"",c=typeof e.projectPath==="string"?e.projectPath:"",l=typeof e.artifactBytes==="number"?e.artifactBytes:null,u=typeof e.sourceFileCount==="number"?e.sourceFileCount:null,d=Array.isArray(e.sourceFiles)?e.sourceFiles.filter((m)=>typeof m==="string"):[],p=Array.isArray(e.deps)?e.deps.filter((m)=>typeof m==="string"):[];if(o)n.push(o);if(!o&&r)n.push(`Web artifact: ${r}`);if(d.length>0&&!o.includes("Source files:")){let m=u!==null?Math.max(0,u-d.length):0;n.push(`Source files: ${d.join(", ")}${m>0?`, +${m} more`:""}`)}if(l!==null&&!o.includes("Artifact bytes:"))n.push(`Artifact bytes: ${l}`);if(p.length>0&&!o.includes("Dependencies:"))n.push(`Dependencies: ${p.join(", ")}`);if(s)n.push(`Path: ${s}`);if(c)n.push(`Project: ${c}`);if(a)n.push(`URL: ${a}`);return n.length>0?_t(n.join(`
32
+ `),t):"Web artifact node"}function w_(e,t){let n=[],o=typeof e.htmlPrimitive==="string"?e.htmlPrimitive:"",r=typeof e.description==="string"?e.description:"",s=e.primitiveData;if(o)n.push(`HTML primitive: ${o}`);if(r)n.push(r);if(s!==void 0)n.push(`Data: ${ps(s,t)}`);return _t(n.join(`
33
+ `),t)}function Jp(e,t={}){let n=t.defaultTextLength??m_,o=t.webpageTextLength??h_;switch(e.type){case"markdown":{let r=e.data.rendered||e.data.content||"";return _t(r,n)}case"mcp-app":{if(e.data.viewerType==="web-artifact")return b_(e.data,n);let r=e.data.chartConfig;if(r){let s=r.title||"Untitled chart",a=r.type||"unknown",c=Array.isArray(r.labels)?r.labels.join(", "):"";return _t(`Chart: ${s} (${a}). Labels: ${c}`,n)}return x_(e.data,n)}case"webpage":return v_(e.data,o);case"json-render":case"graph":{let r=e.data.graphConfig;if(r)return _t(`Graph: ${JSON.stringify(r)}`,n);return ps(e.data.spec??{},n)}case"html":{if(typeof e.data.agentSummary==="string")return _t(e.data.agentSummary,n);if(typeof e.data.htmlPrimitive==="string")return w_(e.data,n);return ps({title:e.data.title,description:e.data.description,summary:e.data.summary,contentSummary:e.data.contentSummary,embeddedNodeIds:e.data.embeddedNodeIds,embeddedUrls:e.data.embeddedUrls},n)}case"prompt":case"response":{let r=e.data.text||e.data.content||"";return _t(r,n)}case"file":{let r=typeof e.data.path==="string"?e.data.path:"",s=typeof e.data.fileContent==="string"?e.data.fileContent:typeof e.data.content==="string"?e.data.content:"",a=r?`Path: ${r}
34
34
 
35
- `:"",c=Math.max(0,n-a.length);return`${a}${_t(s,c)}`.trim()}default:return us(e.data,n)}}function b_(e,t){let n=e.position.x+e.size.width/2,o=e.position.y+e.size.height/2,r=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2;return Math.sqrt((n-r)**2+(o-s)**2)}function w_(e,t){let n=e.position.x+e.size.width,o=e.position.y+e.size.height,r=t.position.x+t.size.width,s=t.position.y+t.size.height,a=Math.max(0,Math.max(e.position.x,t.position.x)-Math.min(n,r)),c=Math.max(0,Math.max(e.position.y,t.position.y)-Math.min(o,s));return Math.sqrt(a**2+c**2)}function __(e){let t=[...e],n=100;return t.sort((o,r)=>{let s=Math.floor(o.position.y/100),a=Math.floor(r.position.y/100);if(s!==a)return s-a;return o.position.x-r.position.x}),t}function S_(e){let t=e.find((r)=>r.data.title&&typeof r.data.title==="string");if(t&&e.length<=3)return e.filter((s)=>s.data.title).map((s)=>s.data.title).slice(0,3).join(", ");let n={};for(let r of e)n[r.type]=(n[r.type]??0)+1;let o=Object.entries(n).map(([r,s])=>s===1?r:`${s} ${r}`);if(t)return`${t.data.title} + ${o.join(", ")}`;return o.join(", ")}function k_(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function C_(e,t){let n=t.filter((r)=>k_(e.bounds,{x:r.position.x,y:r.position.y,width:r.size.width,height:r.size.height})),o=n.map((r)=>typeof r.data.title==="string"&&r.data.title.length>0?r.data.title:r.id);return{id:e.id,label:e.label??e.text??null,bounds:e.bounds,targetNodeIds:n.map((r)=>r.id),targetNodeTitles:o,target:o.length>0?o.join(", "):"empty canvas region"}}function T_(e,t=200){if(e.length===0)return[];let n=new Map,o=(l)=>{while(n.get(l)!==l){let u=n.get(l);n.set(l,n.get(u)),l=u}return l},r=(l,u)=>{let d=o(l),p=o(u);if(d!==p)n.set(d,p)};for(let l of e)n.set(l.id,l.id);for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++)if(w_(e[l],e[u])<=t)r(e[l].id,e[u].id);let s=new Map;for(let l of e){let u=o(l.id);if(!s.has(u))s.set(u,[]);s.get(u).push(l)}let a=[],c=0;for(let[,l]of s){if(l.length<2)continue;let u=l.map((h)=>h.position.x),d=l.map((h)=>h.position.y),p=l.map((h)=>h.position.x+h.size.width),m=l.map((h)=>h.position.y+h.size.height),f=Math.min(...u),g=Math.min(...d),y=Math.max(...p),x=Math.max(...m);a.push({id:`cluster-${c++}`,nodeIds:l.map((h)=>h.id),label:S_(l),centroid:{x:Math.round((f+y)/2),y:Math.round((g+x)/2)},bounds:{x:f,y:g,width:y-f,height:x-g}})}return a.sort((l,u)=>{let d=Math.floor(l.centroid.y/200),p=Math.floor(u.centroid.y/200);if(d!==p)return d-p;return l.centroid.x-u.centroid.x}),a}function E_(e,t,n=5,o=600){let r=e.filter((a)=>t.has(a.id)),s=e.filter((a)=>!t.has(a.id));return r.map((a)=>{let c=s.map((l)=>({node:l,distance:b_(a,l)})).filter((l)=>l.distance<=o).sort((l,u)=>l.distance-u.distance).slice(0,n);return{pinnedNodeId:a.id,pinnedNodeTitle:a.data.title??null,neighbors:c.map((l)=>({id:l.node.id,type:l.node.type,title:l.node.data.title??null,distance:Math.round(l.distance)}))}})}function jr(e,t,n,o=[]){let r=T_(e),s=new Map;for(let u of r)for(let d of u.nodeIds)s.set(d,u.id);let c=__(e).map((u,d)=>({id:u.id,type:u.type,title:u.data.title??null,content:Kp(u,{defaultTextLength:320,webpageTextLength:640})||null,clusterId:s.get(u.id)??null,readingOrder:d})),l=E_(e,n);return{totalNodes:e.length,clusters:r,nodesInReadingOrder:c,pinnedNeighborhoods:l,annotations:o.map((u)=>C_(u,e))}}function Ho(e){if(!e)return null;let t=e.data.title;return typeof t==="string"&&t.trim().length>0?t.trim():null}function ds(e,t){return{id:e?.id??t,title:Ho(e),nodeType:e?.type??"markdown"}}function Jp(e,t){return{id:e.id,edgeType:e.type,fromId:e.from,toId:e.to,fromTitle:Ho(t.get(e.from)),toTitle:Ho(t.get(e.to))}}function ps(e){return new Map(e.map((t)=>[t.id,t]))}function Yp(e){return new Map(e.map((t)=>[t.id,t]))}function Ut(e){return Array.from(e).sort((t,n)=>t.localeCompare(n))}function jc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Zc(e){if(!e||e.type!=="group")return[];let t=e.data.children;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string").sort((n,o)=>n.localeCompare(o))}function Qp(e){let t=new Map;for(let n of e.clusters){let o=[...n.nodeIds].sort((r,s)=>r.localeCompare(s));for(let r of o)t.set(r,o.filter((s)=>s!==r))}return t}function ef(e){let t=new Map;for(let n of e.pinnedNeighborhoods)t.set(n.pinnedNodeId,n.neighbors.map((o)=>o.id).sort((o,r)=>o.localeCompare(r)));return t}function I_(e,t){let n=Ut(Array.from(t).filter((r)=>!e.has(r))),o=Ut(Array.from(e).filter((r)=>!t.has(r)));return{added:n,removed:o}}function tf(e){let t=e&&typeof e==="object"?e:{};return{timestamp:typeof t.timestamp==="string"?t.timestamp:void 0,sessionId:typeof t.sessionId==="string"?t.sessionId:void 0}}function A_(e,t,n){if(!e||!n)return{layout:e,pinnedNodeIds:[],primaryFocusNodeIds:[],secondaryFocusNodeIds:[],regions:[],spatial:n};let o=ps(e.nodes),r=Ut(t).filter((l)=>o.has(l)),s=new Set(r),a=new Set,c=[];for(let l of n.pinnedNeighborhoods){if(!s.has(l.pinnedNodeId))continue;let u=Ut([l.pinnedNodeId,...l.neighbors.map((d)=>d.id)]).filter((d,p,m)=>m.indexOf(d)===p&&o.has(d));for(let d of u)if(!s.has(d))a.add(d);c.push({id:`region-${l.pinnedNodeId}`,primaryNodeId:l.pinnedNodeId,nodeIds:u})}if(c.length===0&&r.length>0)for(let l of r)c.push({id:`region-${l}`,primaryNodeId:l,nodeIds:[l]});return{layout:e,pinnedNodeIds:r,primaryFocusNodeIds:r,secondaryFocusNodeIds:Ut(a),regions:c,spatial:n}}class fs{currentLayout=null;currentPins=new Set;previousSpatial=null;setInitialPins(e){this.currentPins=new Set(e)}getAttentionSnapshot(){return A_(this.currentLayout,this.currentPins,this.previousSpatial)}handleMessage(e){if(e.event==="context-pins-changed")return this.handleContextPinsChanged(e.data);if(e.event==="canvas-layout-update")return this.handleLayoutUpdate(e.data);return[]}handleContextPinsChanged(e){let t=e&&typeof e==="object"?e:{},n=Array.isArray(t.nodeIds)?t.nodeIds.filter((u)=>typeof u==="string"):[],o=tf(e),r=new Set(n),{added:s,removed:a}=I_(this.currentPins,r);if(this.currentPins=r,!this.currentLayout)return[];let c=ps(this.currentLayout.nodes),l={added:s.map((u)=>ds(c.get(u),u)),removed:a.map((u)=>ds(c.get(u),u))};if(this.previousSpatial=jr(this.currentLayout.nodes,this.currentLayout.edges,this.currentPins,this.currentLayout.annotations??[]),l.added.length===0&&l.removed.length===0)return[];return[{type:"context-pin",...o,...l}]}handleLayoutUpdate(e){let t=e&&typeof e==="object"?e:{},n=t.layout&&typeof t.layout==="object"?t.layout:null;if(!n)return[];let o=tf(e);if(!this.currentLayout)return this.currentLayout=n,this.previousSpatial=jr(n.nodes,n.edges,this.currentPins,n.annotations??[]),[];let r=this.currentLayout,s=this.previousSpatial??jr(r.nodes,r.edges,this.currentPins,r.annotations??[]),a=jr(n.nodes,n.edges,this.currentPins,n.annotations??[]),c=[],l=ps(r.nodes),u=ps(n.nodes),d=Yp(r.edges),p=Yp(n.edges),m=Ut(Array.from(p.keys()).filter((h)=>!d.has(h))).map((h)=>p.get(h)).filter((h)=>h!==void 0);if(m.length>0)c.push({type:"connect",...o,edges:m.map((h)=>Jp(h,u))});let f=Ut(Array.from(l.keys()).filter((h)=>!u.has(h))),g=Ut(Array.from(d.keys()).filter((h)=>!p.has(h)));if(f.length>0||g.length>0)c.push({type:"remove",...o,nodes:f.map((h)=>ds(l.get(h),h)),edges:g.map((h)=>d.get(h)).filter((h)=>h!==void 0).map((h)=>Jp(h,l))});let y=this.buildGroupEvent(l,u,o);if(y)c.push(y);let x=this.buildMoveEndEvent(r,n,l,u,s,a,o);if(x)c.push(x);return this.currentLayout=n,this.previousSpatial=a,c}buildGroupEvent(e,t,n){let o=Ut(Array.from(e.values()).filter((c)=>c.type==="group").map((c)=>c.id)),r=Ut(Array.from(t.values()).filter((c)=>c.type==="group").map((c)=>c.id)),s=r.filter((c)=>!o.includes(c)).map((c)=>{let l=t.get(c),u=Zc(l);return{id:c,title:Ho(l),childCount:u.length}}),a=[];for(let c of r.filter((l)=>o.includes(l))){let l=Zc(e.get(c)),u=Zc(t.get(c));if(jc(l,u))continue;a.push({id:c,title:Ho(t.get(c)),addedChildIds:u.filter((d)=>!l.includes(d)),removedChildIds:l.filter((d)=>!u.includes(d)),childCount:u.length})}if(s.length===0&&a.length===0)return null;return{type:"group",...n,created:s,updated:a}}buildMoveEndEvent(e,t,n,o,r,s,a){let c=Ut(Array.from(o.keys()).filter((x)=>{let h=n.get(x),v=o.get(x);if(!h||!v)return!1;return h.position.x!==v.position.x||h.position.y!==v.position.y}));if(c.length===0)return null;let l=Qp(r),u=Qp(s),d=ef(r),p=ef(s),m=new Map,f=(x,h)=>{let v=m.get(x)??new Set;v.add(h),m.set(x,v)};for(let x of c){let h=l.get(x)??[],v=u.get(x)??[];if(!jc(h,v))if(h.length===0&&v.length>0)f(x,"joined cluster");else if(h.length>0&&v.length===0)f(x,"left cluster");else f(x,"cluster changed")}let g=new Set([...d.keys(),...p.keys()]);for(let x of g){let h=d.get(x)??[],v=p.get(x)??[];if(jc(h,v))continue;let b=Ho(o.get(x)??n.get(x))??x,z=v.filter((_)=>!h.includes(_)),F=h.filter((_)=>!v.includes(_));for(let _ of z)if(c.includes(_))f(_,`entered pinned neighborhood of "${b}"`);for(let _ of F)if(c.includes(_))f(_,`left pinned neighborhood of "${b}"`);if(c.includes(x))f(x,"pinned neighborhood changed")}let y=c.filter((x)=>(m.get(x)?.size??0)>0).map((x)=>{let h=o.get(x);return{...ds(h,x),reasons:Array.from(m.get(x)??[]).sort((v,b)=>v.localeCompare(b))}});if(y.length===0)return null;return{type:"move-end",...a,nodes:y}}}var Wc=new fs,Bo=[],Zr=null,Uo=null,Hc="",Bc=0;function of(e,t){return globalThis.setTimeout(e,t)}function Uc(e){if(e===null)return;globalThis.clearTimeout(e)}function z_(e){if(typeof globalThis.requestAnimationFrame==="function"){globalThis.requestAnimationFrame(()=>e());return}e()}function An(e,t){return e&&e.trim().length>0?e.trim():t}function cn(e,t=3){if(e.length===0)return"";if(e.length<=t)return e.join(", ");return`${e.slice(0,t).join(", ")} +${e.length-t}`}function P_(e){return Array.from(new Set(Array.from(e).filter((t)=>t.length>0)))}function Wt(e,t,n,o,r=Date.now()){return{id:`${e}-${r}-${Math.random().toString(36).slice(2,8)}`,tone:e,title:t,detail:n,nodeIds:P_(o),createdAt:r}}function nf(e){if(e==="joined cluster")return"joined a nearby cluster";if(e==="left cluster")return"moved away from its cluster";if(e==="cluster changed")return"shifted into a different cluster";if(e==="pinned neighborhood changed")return"changed the local focus field";let t=/^entered pinned neighborhood of "(.+)"$/.exec(e);if(t)return`moved into focus around ${t[1]}`;let n=/^left pinned neighborhood of "(.+)"$/.exec(e);if(n)return`moved out of focus around ${n[1]}`;return e}function N_(e){let t=e.added.map((r)=>An(r.title,r.id)),n=e.removed.map((r)=>An(r.title,r.id));if(t.length===0&&n.length===0)return null;let o="";if(t.length>0&&n.length===0)o=`Now in focus: ${cn(t)}`;else if(n.length>0&&t.length===0)o=`Removed from focus: ${cn(n)}`;else{let r=[];if(t.length>0)r.push(`${cn(t)} added`);if(n.length>0)r.push(`${cn(n)} removed`);o=r.join(" · ")}return Wt("context","Context updated",o,[...e.added.map((r)=>r.id),...e.removed.map((r)=>r.id)],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function R_(e){if(e.edges.length===0)return null;if(e.edges.length===1){let t=e.edges[0];return Wt("relationship","Relationship added",`${An(t.fromTitle,t.fromId)} linked to ${An(t.toTitle,t.toId)}`,[t.fromId,t.toId],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return Wt("relationship","Relationships added",`${e.edges.length} connections changed the board structure`,e.edges.flatMap((t)=>[t.fromId,t.toId]),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function $_(e){if(e.nodes.length===0&&e.edges.length===0)return null;let t=e.nodes.map((o)=>An(o.title,o.id)),n=[];if(t.length>0)n.push(cn(t));if(e.edges.length>0)n.push(`${e.edges.length} relationship${e.edges.length===1?"":"s"}`);return Wt("remove","Items removed",n.join(" · "),[...e.nodes.map((o)=>o.id),...e.edges.flatMap((o)=>[o.fromId,o.toId])],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function M_(e){if(e.created.length>0){let t=e.created.map((n)=>An(n.title,n.id));return Wt("group",e.created.length===1?"Group created":"Groups created",e.created.length===1?`${t[0]} now frames ${e.created[0].childCount} items`:cn(t),e.created.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}if(e.updated.length>0){let t=e.updated.map((n)=>An(n.title,n.id));return Wt("group",e.updated.length===1?"Group updated":"Groups updated",e.updated.length===1?`${t[0]} now holds ${e.updated[0].childCount} items`:cn(t),e.updated.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return null}function O_(e){if(e.nodes.length===0)return null;let t=e.nodes.flatMap((s)=>s.reasons),n=e.nodes.map((s)=>An(s.title,s.id)),o=e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now();if(t.some((s)=>s.includes("pinned neighborhood"))){if(e.nodes.length===1)return Wt("neighborhood","Neighborhood changed",`${n[0]} ${nf(e.nodes[0].reasons[0])}`,e.nodes.map((s)=>s.id),o);return Wt("neighborhood","Neighborhood changed",cn(n),e.nodes.map((s)=>s.id),o)}let r=t.filter((s)=>s.includes("cluster"));if(r.length>0){let s=r.every((a)=>a==="joined cluster");if(e.nodes.length===1)return Wt("cluster",s?"Cluster formed":"Cluster changed",`${n[0]} ${nf(e.nodes[0].reasons[0])}`,e.nodes.map((a)=>a.id),o);return Wt("cluster",s?"Cluster formed":"Cluster changed",cn(n),e.nodes.map((a)=>a.id),o)}return null}function L_(e){switch(e.type){case"context-pin":return N_(e);case"connect":return R_(e);case"remove":return $_(e);case"group":return M_(e);case"move-end":return O_(e)}}function D_(){let e=Wc.getAttentionSnapshot();Ap(e.primaryFocusNodeIds,e.secondaryFocusNodeIds,e.regions)}function rf(){if(Zr!==null)return;let e=Bo.shift()??null;if(!e){es(null);return}es(e);let t=Math.max(1800,Math.min(2800,1600+e.detail.length*18));Zr=of(()=>{Zr=null,es(null),rf()},t)}function sf(e){if(Bo.push(e),Bo.length>3)Bo.splice(0,Bo.length-3);rf()}function Wo(e,t,n="",o=[]){sf(Wt(e,t,n,o))}function F_(e){if(Uc(Uo),Uo=null,ts([]),e.length===0)return;z_(()=>{ts(e),Uo=of(()=>{Uo=null,ts([])},900)})}function j_(e){let t=`${e.tone}:${e.title}:${e.detail}`,n=e.createdAt;if(t===Hc&&n-Bc<1200)return!0;return Hc=t,Bc=n,!1}function qc(){Uc(Zr),Uc(Uo),Zr=null,Uo=null,Bo=[],Hc="",Bc=0,Wc=new fs,Ep()}function Vc(e){let t=Wc.handleMessage(e).map((n)=>L_(n)).filter((n)=>n!==null);D_();for(let n of t){if(j_(n))continue;zp(n),sf(n),F_(n.nodeIds)}}async function zn(e,t,n,o){let r=await ss({type:t,sourceNodeId:e.id,sourceSurface:"native-node",...n?{payload:n}:{}});if(r.ok)Wo("context",o,"",[e.id]);else Wo("remove","AX action failed",r.error??r.code??"Unknown error",[e.id])}var ao={padding:"3px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer",flexShrink:0};function Z_(e){let t=e.title||e.label||e.key||"Context",n=e.summary?.trim()||"Available in startup context.",o=e.pathDisplay||e.path||"",r=e.category==="profile"?"Operator":e.category==="planning"||e.category==="memory"?"Product":e.category?e.category.charAt(0).toUpperCase()+e.category.slice(1):void 0,s=e.sourceKind==="global"?"Global":"Workspace",a=e.state==="missing"?"Missing":e.state==="stale"?"Stale":e.state==="invalid"?"Invalid":"Loaded";return{title:t,summary:n,pathDisplay:o,category:r,sourceKind:s,status:a,required:e.required===!0}}function qt(e){return typeof e==="string"?e.trim():""}function H_(e){return e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function B_(e){let t=qt(e.title),n=qt(e.content),o=H_(qt(e.rendered)),r=n||o,s=qt(e.path);if(!t&&!r&&!s)return null;return{title:t||"Context",summary:r,path:s}}function U_(e){let t=qt(e.data.title)||e.id,n=qt(e.data.content)||qt(e.data.excerpt)||qt(e.data.description)||qt(e.data.pageTitle)||"",o=qt(e.data.path)||qt(e.data.url);return{id:e.id,title:t,summary:n,kind:it[e.type]??e.type,path:o}}function af(e){if(e===null||!Number.isFinite(e)||e<0)return"0";if(e>=1e6)return`${(e/1e6).toFixed(1)}m`;if(e>=1000)return`${(e/1000).toFixed(1)}k`;return`${Math.round(e)}`}function W_(e){if(e>=0.95)return"var(--c-danger)";if(e>=0.85)return"var(--c-warn)";if(e>=0.7)return"var(--c-warn)";return"var(--c-accent)"}function ms({node:e,expanded:t=!1,pinnedNodes:n=[]}){let o=e.data.cards??[],r=e.data.auxTabs??[],s=n.map(U_),a=s.length>0,c=typeof e.data.currentTokens==="number"?e.data.currentTokens:null,l=typeof e.data.tokenLimit==="number"?e.data.tokenLimit:null,u=typeof e.data.utilization==="number"?e.data.utilization:null,d=typeof e.data.messagesLength==="number"?e.data.messagesLength:null,p=u!==null?Math.max(0,Math.min(100,Math.round(u*100))):null,m=W_(u??0),f=!a&&o.length===0&&r.length===0?B_(e.data):null,g=async(y)=>{let x=typeof y.path==="string"?y.path.trim():"";if(!x)return;await os(x)};return i("div",{style:{display:"flex",flexDirection:"column",gap:t?"10px":"6px",fontSize:t?"14px":"12px",maxWidth:t?"760px":void 0,margin:t?"0 auto":void 0,width:t?"100%":void 0,padding:t?"8px 0":void 0},children:[i("div",{style:{display:"flex",justifyContent:"flex-end"},children:i("button",{type:"button",class:"ax-node-action",title:"Point the agent at this node — sets it as the agent's current AX focus so the agent pulls it into context to work on next (a one-click alternative to manually pinning).",style:ao,onClick:(y)=>{y.stopPropagation(),zn(e,"ax.focus.set",void 0,"Focus set")},children:"Set focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this),l!==null&&l>0&&i("div",{style:{marginBottom:"8px"},children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:"Token Usage"},void 0,!1,void 0,this),i("div",{style:{height:"6px",background:"var(--c-surface-hover)",borderRadius:"3px",overflow:"hidden",marginBottom:"4px"},children:i("div",{style:{height:"100%",width:`${Math.min(100,(u??0)*100)}%`,background:m,borderRadius:"3px",transition:"width 0.3s ease"}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{style:{fontSize:"11px",color:"var(--c-muted)"},children:[p,"% — ",af(c)," / ",af(l)," tokens",d!==null&&i(ve,{children:[" · ",d," messages"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&i("div",{children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Pinned Context (",s.length,")"]},void 0,!0,void 0,this),s.map((y)=>i("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[i("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:y.title},void 0,!1,void 0,this),y.summary&&i("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px",whiteSpace:"pre-wrap"},children:y.summary},void 0,!1,void 0,this),i("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:y.kind},void 0,!1,void 0,this)},void 0,!1,void 0,this),y.path&&i("div",{style:{marginTop:"6px"},children:[i("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:y.path},void 0,!1,void 0,this),y.path.startsWith("/")&&i("button",{type:"button",onClick:()=>void os(y.path),style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},y.id,!0,void 0,this))]},void 0,!0,void 0,this),!a&&o.length>0&&i("div",{children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Context (",o.length,")"]},void 0,!0,void 0,this),o.map((y)=>{let x=Z_(y);return i("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[i("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:x.title},void 0,!1,void 0,this),i("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px"},children:x.summary},void 0,!1,void 0,this),x.pathDisplay&&i("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all"},children:x.pathDisplay},void 0,!1,void 0,this),i("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:[i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-accent-10)",color:"var(--c-accent)",borderRadius:"3px",display:"inline-block"},children:x.status},void 0,!1,void 0,this),x.category&&i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:x.category},void 0,!1,void 0,this),i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:x.sourceKind},void 0,!1,void 0,this),x.required&&i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-warn-12)",color:"var(--c-warn-alt)",borderRadius:"3px",display:"inline-block"},children:"Required"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y.path&&i("div",{style:{marginTop:"6px"},children:i("button",{type:"button",onClick:()=>void g(y),style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},y.key??x.pathDisplay??x.title,!0,void 0,this)})]},void 0,!0,void 0,this),!a&&r.length>0&&i("div",{children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px",marginTop:o.length>0?"8px":0},children:["References (",r.length,")"]},void 0,!0,void 0,this),r.map((y)=>i("a",{href:y.url,target:"_blank",rel:"noopener noreferrer",style:{display:"block",padding:"4px 8px",color:"var(--c-accent)",fontSize:"11px",textDecoration:"none",borderRadius:"4px",marginBottom:"2px",wordBreak:"break-all"},children:[y.url,y.reason&&i("span",{style:{color:"var(--c-dim)",fontSize:"10px",marginLeft:"6px"},children:["(",y.reason,")"]},void 0,!0,void 0,this)]},y.id,!0,void 0,this))]},void 0,!0,void 0,this),f&&i("div",{style:{padding:"8px 10px",background:"var(--c-surface-subtle)",borderRadius:"6px",borderLeft:"2px solid var(--c-accent)"},children:[i("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"4px"},children:f.title},void 0,!1,void 0,this),f.summary&&i("div",{style:{color:"var(--c-text-soft)",fontSize:"11px",lineHeight:1.5,whiteSpace:"pre-wrap"},children:f.summary},void 0,!1,void 0,this),f.path&&i("div",{style:{marginTop:"6px"},children:[i("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:f.path},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>void os(f.path),style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!a&&!f&&o.length===0&&r.length===0&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic"},children:"No context loaded"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function cf(e){return e.replace(/^[ab]\//,"")}function q_(e,t){if(t&&t!=="/dev/null")return cf(t);if(e&&e!=="/dev/null")return cf(e);return null}function V_(e){if(!e.trim())return[];let t=e.split(`
36
- `);if(t.length>0&&t[t.length-1]==="")t.pop();let n=[],o=null,r=!1,s=(a)=>{let c={path:a,lines:[]};return r=!1,n.push(c),c};for(let a=0;a<t.length;a++){let c=t[a]??"",l=c.match(/^diff --git a\/(.+?) b\/(.+)$/);if(l){o=s(l[2]??null);continue}let u=t[a+1]??"";if(c.startsWith("--- ")&&u.startsWith("+++ ")){let p=q_(c.slice(4).trim(),u.slice(4).trim());if(o&&!r){if(!o.path)o.path=p}else o=s(p);a++;continue}if(!o)o=s(null);let d=o;if(c.startsWith("@@"))r=!0,d.lines.push({kind:"hunk",text:c});else if(c.startsWith("+"))d.lines.push({kind:"add",text:c});else if(c.startsWith("-"))d.lines.push({kind:"remove",text:c});else d.lines.push({kind:"context",text:c})}return n}function hs({node:e}){let t=typeof e.data.content==="string"?e.data.content:"",n=Ae(()=>V_(t),[t]);if(n.length===0)return i("div",{class:"diff-node diff-node-empty",children:"Empty diff"},void 0,!1,void 0,this);return i("div",{class:"diff-node",children:n.map((o,r)=>i("div",{class:"diff-file",children:[o.path&&i("div",{class:"diff-file-header",children:o.path},void 0,!1,void 0,this),i("pre",{class:"diff-lines",children:o.lines.map((s,a)=>i("div",{class:s.kind==="hunk"?"diff-hunk":`diff-line-${s.kind}`,children:s.text||" "},a,!1,void 0,this))},void 0,!1,void 0,this)]},`${o.path??"anonymous"}-${r}`,!0,void 0,this))},void 0,!1,void 0,this)}function lf(e){if(e.length===0)return null;let{POSITIVE_INFINITY:t,POSITIVE_INFINITY:n,NEGATIVE_INFINITY:o,NEGATIVE_INFINITY:r}=Number;for(let s of e)t=Math.min(t,s.position.x),n=Math.min(n,s.position.y),o=Math.max(o,s.position.x+s.size.width),r=Math.max(r,s.position.y+s.size.height);if(!Number.isFinite(t)||!Number.isFinite(n))return null;return{x:t-40,y:n-40-32,width:o-t+80,height:r-n+80+32}}function G_(e){let t=e.filter((l)=>!l.pinned),n=new Map(t.map((l)=>[l.id,l])),o=new Map,r=[],s=new Map;for(let l of t){if(l.type==="group")continue;let u=typeof l.data.parentGroup==="string"?l.data.parentGroup:"",d=u?n.get(u):void 0;if(!d||d.type!=="group")continue;if(!s.has(u))s.set(u,[]);s.get(u).push(l)}let a=t.filter((l)=>l.type==="group").sort((l,u)=>l.position.y-u.position.y||l.position.x-u.position.x);for(let l of a){let u=s.get(l.id)??[];if(u.length===0){let f=`unit:${l.id}`;r.push({id:f,memberIds:[l.id],origin:{...l.position},size:{...l.size},sortKey:{x:l.position.x,y:l.position.y}}),o.set(l.id,f);continue}let d=u.map((f)=>({position:f.position,size:f.size})),p=lf(d);if(!p)continue;let m=`group:${l.id}`;r.push({id:m,memberIds:u.map((f)=>f.id),origin:{x:p.x,y:p.y},size:{width:p.width,height:p.height},sortKey:{x:p.x,y:p.y},groupId:l.id}),o.set(l.id,m);for(let f of u)o.set(f.id,m)}let c=t.filter((l)=>!o.has(l.id)).sort((l,u)=>l.position.y-u.position.y||l.position.x-u.position.x);for(let l of c){let u=`unit:${l.id}`;r.push({id:u,memberIds:[l.id],origin:{...l.position},size:{...l.size},sortKey:{x:l.position.x,y:l.position.y}}),o.set(l.id,u)}return{units:r,nodesById:n,nodeToUnit:o}}function X_(e,t,n){let o=new Map,r=new Map,s=new Map,a=new Map;for(let c of e)o.set(c.id,new Set),r.set(c.id,new Set),s.set(c.id,0),a.set(c.id,0);for(let c of n){let l=t.get(c.from),u=t.get(c.to);if(!l||!u||l===u)continue;if(!o.get(l).has(u))o.get(l).add(u),a.set(l,(a.get(l)??0)+1),s.set(u,(s.get(u)??0)+1);r.get(l).add(u),r.get(u).add(l)}return{outgoing:o,undirected:r,indegree:s,outdegree:a}}function K_(e,t){let n=new Map(e.map((s)=>[s.id,s])),o=new Set,r=[];for(let s of e){if(o.has(s.id))continue;let a=[s.id],c=[];o.add(s.id);while(a.length>0){let u=a.pop();c.push(u);for(let d of t.get(u)??[]){if(o.has(d))continue;o.add(d),a.push(d)}}let l=c.map((u)=>n.get(u)).filter((u)=>u!==void 0).sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);r.push(l)}return r.sort((s,a)=>s[0].sortKey.y-a[0].sortKey.y||s[0].sortKey.x-a[0].sortKey.x)}function J_(e){let t=new Map,n=0,o=0,r=0,s=0,a=Math.max(900,Math.ceil(Math.sqrt(e.reduce((c,l)=>c+l.size.width*l.size.height,0))));for(let c of e){if(n>0&&n+c.size.width>a)n=0,o+=r+72,r=0;t.set(c.id,{x:n,y:o}),n+=c.size.width+96,r=Math.max(r,c.size.height),s=Math.max(s,n-96)}return{positions:t,size:{width:Math.max(0,s),height:o+r},sortKey:e[0].sortKey}}function Y_(e,t,n,o,r){if(e.length===1)return{positions:new Map([[e[0].id,{x:0,y:0}]]),size:{...e[0].size},sortKey:e[0].sortKey};let s=new Set(e.map((v)=>v.id)),a=e.filter((v)=>(o.get(v.id)??0)===0&&(r.get(v.id)??0)>0).sort((v,b)=>v.sortKey.x-b.sortKey.x||v.sortKey.y-b.sortKey.y),c=a.length>0?a:[e.slice().sort((v,b)=>v.sortKey.x-b.sortKey.x||v.sortKey.y-b.sortKey.y)[0]],l=new Map,u=c.map((v)=>v.id);for(let v of c)l.set(v.id,0);while(u.length>0){let v=u.shift(),b=l.get(v)??0;for(let z of n.get(v)??[]){if(!s.has(z)||l.has(z))continue;l.set(z,b+1),u.push(z)}}let d=0;for(let v of e){if(l.has(v.id))continue;l.set(v.id,d),d+=1}let p=new Map;for(let v of e){let b=l.get(v.id)??0;if(!p.has(b))p.set(b,[]);p.get(b).push(v)}let m=Array.from(p.keys()).sort((v,b)=>v-b);for(let v of m)p.get(v).sort((b,z)=>b.sortKey.y-z.sortKey.y||b.sortKey.x-z.sortKey.x);let f=new Map,g=new Map,y=0;for(let v of m){let b=p.get(v),z=b.reduce((_,k,T)=>_+k.size.height+(T>0?72:0),0),F=Math.max(...b.map((_)=>_.size.width));f.set(v,z),g.set(v,F),y=Math.max(y,z)}let x=new Map,h=0;for(let v of m){let b=p.get(v),z=f.get(v)??0,F=g.get(v)??0,_=Math.max(0,(y-z)/2);for(let k of b)x.set(k.id,{x:h,y:_}),_+=k.size.height+72;h+=F+96}return{positions:x,size:{width:Math.max(0,h-96),height:y},sortKey:e[0].sortKey}}function Q_(e,t){let n=new Map(e.map((l)=>[l.id,l.id])),o=(l)=>{let u=l;while(n.get(u)!==u)u=n.get(u);let d=l;while(n.get(d)!==d){let p=n.get(d);n.set(d,u),d=p}return u},r=(l,u)=>{let d=o(l),p=o(u);if(d!==p)n.set(d,p)},s=160;for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++){let d=e[l],p=e[u];if(d.origin.x-160<p.origin.x+p.size.width+160&&d.origin.x+d.size.width+160>p.origin.x-160&&d.origin.y-160<p.origin.y+p.size.height+160&&d.origin.y+d.size.height+160>p.origin.y-160)r(d.id,p.id)}for(let[l,u]of t)for(let d of u)if(n.has(l)&&n.has(d))r(l,d);let a=new Map;for(let l of e){let u=o(l.id);if(!a.has(u))a.set(u,[]);a.get(u).push(l)}let c=Array.from(a.values());for(let l of c)l.sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);return c.sort((l,u)=>l[0].sortKey.y-u[0].sortKey.y||l[0].sortKey.x-u[0].sortKey.x)}function eS(e,t){let n=new Map,{x:o,y:r}=t,s=0;for(let a of e){if(o>t.x&&o-t.x+a.size.width>3200)o=t.x,r+=s+180,s=0;for(let[c,l]of a.positions.entries())n.set(c,{x:o+l.x,y:r+l.y});o+=a.size.width+220,s=Math.max(s,a.size.height)}return n}function Gc(e,t,n){let{units:o,nodesById:r,nodeToUnit:s}=G_(e),a=new Map,c=new Map;if(o.length===0)return{nodePositions:a,groupBounds:c};let{outgoing:l,undirected:u,indegree:d,outdegree:p}=X_(o,s,t),m=Q_(o,u),f=new Map,g=[];for(let y of m){let x=K_(y,u).map((_)=>n==="graph"?Y_(_,l,u,d,p):J_(_)),h={x:Math.min(...y.map((_)=>_.origin.x)),y:Math.min(...y.map((_)=>_.origin.y))},v=eS(x,h),b=new Map(y.map((_)=>[_.id,_.size])),z=(_)=>{let{POSITIVE_INFINITY:k,POSITIVE_INFINITY:T,NEGATIVE_INFINITY:P,NEGATIVE_INFINITY:Z}=Number;for(let[j,E]of _){let B=b.get(j);if(!B)continue;k=Math.min(k,E.x),T=Math.min(T,E.y),P=Math.max(P,E.x+B.width),Z=Math.max(Z,E.y+B.height)}return{x:k,y:T,width:P-k,height:Z-T}},F=v;for(let _=0;_<=g.length;_++){let k=z(F),T=g.filter((j)=>k.x<j.x+j.width+220&&k.x+k.width+220>j.x&&k.y<j.y+j.height+180&&k.y+k.height+180>j.y);if(T.length===0)break;let P=Math.max(...T.map((j)=>j.y+j.height))+180-k.y;if(P<=0)break;let Z=new Map;for(let[j,E]of F)Z.set(j,{x:E.x,y:E.y+P});F=Z}for(let[_,k]of F)f.set(_,k);g.push(z(F))}for(let y of o){let x=f.get(y.id);if(!x)continue;let h=x.x-y.origin.x,v=x.y-y.origin.y;if(y.groupId){let F=[];for(let k of y.memberIds){let T=r.get(k);if(!T)continue;let P={x:T.position.x+h,y:T.position.y+v};a.set(k,P),F.push({position:P,size:T.size})}let _=lf(F);if(_)c.set(y.groupId,_);continue}let b=y.memberIds[0],z=r.get(b);if(!z)continue;a.set(b,{x:z.position.x+h,y:z.position.y+v})}return{nodePositions:a,groupBounds:c}}function mf(e,t){console.error(`[canvas-store] ${e} failed`,t)}var re=V({x:0,y:0,scale:1}),M=V(new Map),Re=V(new Map),Vo=V(new Map),ke=V(null),un=V(null),Et=V("connecting"),co=V(0),lo=V(0),uo=V(0),dn=V(""),Go=V(!1),Xe=V("dark"),Vt=V(!1),Gt=V(null),Be=V(null),Qt=V(null),Tt=null,qo,uf=100,tS=2500,gs=V(null),je=V(null),Nn=V(null),ye=V(new Set),Ee=V(new Set),yt=V("select"),Br=V(!1);function Xo(){return yt.value==="pan"||Br.value}function hf(e,t){if(!e)return new Set;let n=new Set;for(let o of t.values()){if(o.from===e)n.add(o.to);if(o.to===e)n.add(o.from)}return n}var gf=Oe(()=>hf(ke.value,Re.value));function df(e,t){let n=new Set;for(let o of e)if(t.has(o))n.add(o);return n}function pf(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Jc(e){let t=new Set(ye.value);if(t.has(e))t.delete(e);else t.add(e);ye.value=t}function vf(e){ye.value=new Set(e)}function ht(){if(un.value=null,ye.value.size===0)return;ye.value=new Set}var ln=V(null),Yc=!1;function yf(){Yc=!0,ln.value=null}function xf(){Yc=!1,ln.value=null}function Xc(e){return{x:e.position.x,y:e.position.y,w:e.size.width,h:e.size.height}}function nS(e,t,n){let o=Xc(e);return t>=o.x&&t<=o.x+o.w&&n>=o.y&&n<=o.y+o.h}function ff(e,t){let n=Xc(e),o=Xc(t);return n.x+n.w<o.x||n.x>o.x+o.w||n.y+n.h<o.y||n.y>o.y+o.h}function bf(e){let t=M.value.get(e);if(!t||t.type==="group")return;let n=typeof t.data.parentGroup==="string"?t.data.parentGroup:null,o=n?M.value.get(n):void 0,r=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=null;for(let c of M.value.values()){if(c.type!=="group"||c.id===n||c.collapsed)continue;if(nS(c,r,s))a=c}if(!Yc){let c=a?{nodeId:e,groupId:a.id,mode:"add"}:o&&ff(t,o)?{nodeId:e,groupId:o.id,mode:"remove"}:null,l=ln.value;if((l?.groupId??null)!==(c?.groupId??null)||l?.mode!==c?.mode)ln.value=c}if(o&&o.data.frameMode!=="manual"&&!ff(t,o)){let l=Math.min(o.position.x,t.position.x-22),u=Math.min(o.position.y,t.position.y-22-32),d=Math.max(o.position.x+o.size.width,t.position.x+t.size.width+22),p=Math.max(o.position.y+o.size.height,t.position.y+t.size.height+22);if(l!==o.position.x||u!==o.position.y||d!==o.position.x+o.size.width||p!==o.position.y+o.size.height)bs(o.id,{position:{x:l,y:u},size:{width:d-l,height:p-u}},{skipGroupChildTranslation:!0})}}var Qc=Oe(()=>{let e=new Map;for(let t of M.value.values()){if(t.type!=="group"||!t.collapsed)continue;let n=Array.isArray(t.data.children)?t.data.children:[];for(let o of n)if(typeof o==="string")e.set(o,t.id)}return e});function vs(e){let t=Qc.value.get(e);return M.value.get(t??e)}function wf(){let e=new Set;for(let t of ye.value){let n=M.value.get(t);if(!n)continue;if(n.type==="group")e.add(n.id);else if(typeof n.data.parentGroup==="string")e.add(n.data.parentGroup)}return[...e]}function el(e){let t=tl();if(t.length<2)return;let n=Math.min(...t.map((l)=>e==="left"?l.position.x:l.position.y)),o=24,r=new Map;for(let l of t)r.set(l.id,e==="left"?{x:n,y:l.position.y}:{x:l.position.x,y:n});let s=(l,u)=>l.x<u.x+u.w&&u.x<l.x+l.w&&l.y<u.y+u.h&&u.y<l.y+l.h,a=t.map((l)=>{let u=r.get(l.id);return{node:l,x:u.x,y:u.y,w:l.size.width,h:l.size.height}});if(a.some((l,u)=>a.some((d,p)=>p>u&&s(l,d)))){let l=[...t].sort((d,p)=>e==="left"?d.position.y-p.position.y:d.position.x-p.position.x),u=e==="left"?Math.min(...t.map((d)=>d.position.y)):Math.min(...t.map((d)=>d.position.x));for(let d of l)r.set(d.id,e==="left"?{x:n,y:u}:{x:u,y:n}),u+=(e==="left"?d.size.height:d.size.width)+o}$t(()=>{for(let l of t)st(l.id,{position:r.get(l.id)})}),Ye()}function _f(){let e=tl().sort((c,l)=>c.position.x-l.position.x);if(e.length<3)return;let t=e[0],o=e[e.length-1].position.x-(t.position.x+t.size.width),r=e.slice(1,-1),s=r.reduce((c,l)=>c+l.size.width,0),a=(o-s)/(r.length+1);$t(()=>{if(a<8){let l=t.position.x+t.size.width+24;for(let u of e.slice(1))st(u.id,{position:{x:l,y:u.position.y}}),l+=u.size.width+24;return}let c=t.position.x+t.size.width+a;for(let l of r)st(l.id,{position:{x:c,y:l.position.y}}),c+=l.size.width+a}),Ye()}function Sf(e=24){let t=tl().sort((c,l)=>c.position.y-l.position.y||c.position.x-l.position.x);if(t.length<2)return;let n=Math.min(...t.map((c)=>c.position.x)),o=Math.min(...t.map((c)=>c.position.y)),r=Math.ceil(Math.sqrt(t.length)),s=Math.max(...t.map((c)=>c.size.width)),a=Math.max(...t.map((c)=>c.size.height));$t(()=>{t.forEach((c,l)=>{st(c.id,{position:{x:n+l%r*(s+e),y:o+Math.floor(l/r)*(a+e)}})})}),Ye()}function tl(){let e=ye.value;if(e.size===0)return[];return Array.from(e).map((t)=>M.value.get(t)).filter((t)=>t!==void 0)}function Rn(e){let t=new Set(Ee.value);if(t.has(e))t.delete(e);else t.add(e);Ee.value=t,Ye(),xs(t)}function ys(e){let t=new Set(Ee.value);for(let n of e)t.add(n);Ee.value=t,Ye(),xs(t)}function kf(){if(Ee.value.size===0)return;Ee.value=new Set,Ye(),xs(new Set)}function Cf(e){Ee.value=new Set(e)}function xs(e){Ht("syncContextPinsToServer","/api/canvas/context-pins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeIds:Array.from(e)})})}var Hr=1;function pn(e){$t(()=>{let t=new Map(M.value);if(e.zIndex>=Hr)Hr=e.zIndex+1;t.set(e.id,e),M.value=t,ke.value=e.id})}function st(e,t){bs(e,t)}function bs(e,t,n={}){let o=M.value.get(e);if(!o)return;let r=new Map(M.value);if(o.type==="group"&&t.position&&n.skipGroupChildTranslation!==!0){let a=t.position.x-o.position.x,c=t.position.y-o.position.y;if(a!==0||c!==0){let l=Array.isArray(o.data.children)?o.data.children.filter((u)=>typeof u==="string"):[];for(let u of l){let d=r.get(u);if(!d||d.type==="group")continue;r.set(u,{...d,position:{x:d.position.x+a,y:d.position.y+c}})}}}r.set(e,{...o,...t}),M.value=r;let s=r.get(e)?.data.appCheckpoint?.updatedAt;if(Qt.value===e&&s!==void 0&&s!==qo)Kc(e)}function oe(e,t){let n=M.value.get(e);if(!n)return;st(e,{data:{...n.data,...t}})}function It(e){oS(e);let t=new Map(M.value);if(t.delete(e),M.value=t,ke.value===e)ke.value=null;if(Be.value===e)Be.value=null;if(ye.value.has(e)){let n=new Set(ye.value);n.delete(e),ye.value=n}if(Ee.value.has(e)){let n=new Set(Ee.value);n.delete(e),Ee.value=n,xs(n)}}function ws(e){let t=new Map(Re.value);t.set(e.id,e),Re.value=t}function Tf(e){let t=new Map(Re.value);t.delete(e),Re.value=t}function oS(e){let t=!1,n=new Map(Re.value);for(let[o,r]of n)if(r.from===e||r.to===e)n.delete(o),t=!0;if(t)Re.value=n}function rS(e){let t=new Map(Vo.value);if(!t.delete(e))return;Vo.value=t}async function nl(e){return Ct("createAnnotationFromClient","/api/canvas/annotation",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Ef(e){let t=await Ct("removeAnnotationFromClient",`/api/canvas/annotation/${encodeURIComponent(e)}`,{method:"DELETE"});if(t.ok)rS(e);return t}function Ko(e,t){if(!M.value.get(e))return;st(e,{size:t})}function fn(e){let t=M.value.get(e);if(!t)return;$t(()=>{if(st(e,{zIndex:Hr++}),t.type==="group"&&Array.isArray(t.data.children)){for(let n of t.data.children)if(typeof n==="string"&&M.value.has(n))st(n,{zIndex:Hr++})}}),ke.value=e}function Jo(e){let t=M.value.get(e);if(!t)return;st(e,{collapsed:!t.collapsed}),Ye()}function If(e){re.value={...re.value,...e}}function Af(e){re.value=e}function zf(e){Pf(e)}function Pf(e,t={}){re.value=e,Ye(t),Bp(e,t)}function Nf(e,t={}){let n=new Map,o=1;for(let p of e.nodes)if(n.set(p.id,p),p.zIndex>=o)o=p.zIndex+1;let r=e.edges.filter((p)=>n.has(p.from)&&n.has(p.to)),s=new Map;for(let p of r)s.set(p.id,p);let a=new Map;for(let p of e.annotations??[])a.set(p.id,p);let c=ke.value!==null&&n.has(ke.value)?ke.value:null,l=Be.value!==null&&n.has(Be.value)?Be.value:null,u=df(ye.value,n),d=df(Ee.value,n);$t(()=>{if(t.applyViewport===!0&&e.viewport)re.value=e.viewport;if(Hr=o,M.value=n,Re.value=s,Vo.value=a,ke.value=c,Be.value=l,!pf(ye.value,u))ye.value=u;if(!pf(Ee.value,d))Ee.value=d})}var Pn=null;function iS(e){return 1-(1-e)**3}function Yo(e,t=150){let n=re.value,o=Math.min(4,Math.max(0.1,n.scale*e));if(o===n.scale)return;let r=o/n.scale,{x:s,y:a}=Fo();$n({x:s-r*(s-n.x),y:a-r*(a-n.y),scale:o},t)}function $n(e,t=300,n={}){if(Pn!==null)cancelAnimationFrame(Pn);let o={...re.value},r=performance.now();function s(a){let c=a-r,l=Math.min(1,c/t),u=iS(l);if(re.value={x:o.x+(e.x-o.x)*u,y:o.y+(e.y-o.y)*u,scale:o.scale+(e.scale-o.scale)*u},l<1)Pn=requestAnimationFrame(s);else Pn=null,Pf(e,n)}Pn=requestAnimationFrame(s)}function Qo(){if(Pn!==null)cancelAnimationFrame(Pn),Pn=null}var Rf="pmx-canvas-layout";function Ye(e={}){try{let t=Array.from(M.value.values()),n=t.map((r)=>({id:r.id,position:r.position,size:r.size,collapsed:r.collapsed})),o={viewport:re.value,nodes:t.map((r)=>({id:r.id,type:r.type,position:r.position,size:r.size,collapsed:r.collapsed,pinned:r.pinned})),edges:Array.from(Re.value.values()).map((r)=>({id:r.id,from:r.from,to:r.to,type:r.type,label:r.label,style:r.style,animated:r.animated})),contextPinnedNodeIds:Array.from(Ee.value)};localStorage.setItem(Rf,JSON.stringify(o)),jp(n,e)}catch(t){mf("persistLayout",t)}}function ol(){try{let e=localStorage.getItem(Rf);if(!e)return null;let t=JSON.parse(e),n=Array.isArray(t.nodes)?t.nodes:[];if(n.length===0)return null;let o=new Map;for(let r of n){if(typeof r.id!=="string"||r.id.length===0)continue;o.set(r.id,{...r.position?{position:r.position}:{},...r.size?{size:r.size}:{},...r.collapsed!==void 0?{collapsed:r.collapsed}:{},...r.pinned!==void 0?{pinned:r.pinned}:{}})}return o.size>0?o:null}catch(e){return mf("restoreLayout",e),null}}function er(e,t){let n=Array.from(M.value.values());if(n.length===0)return;let{POSITIVE_INFINITY:o,POSITIVE_INFINITY:r,NEGATIVE_INFINITY:s,NEGATIVE_INFINITY:a}=Number;for(let y of n)o=Math.min(o,y.position.x),r=Math.min(r,y.position.y),s=Math.max(s,y.position.x+y.size.width),a=Math.max(a,y.position.y+y.size.height);let c=Mc(),l=Math.max(80,e-c.left-c.right),u=Math.max(80,t-c.top-c.bottom),d=Math.max(1,s-o),p=Math.max(1,a-r),m=Math.min(1,Math.min(l/d,u/p)),f=(o+s)/2,g=(r+a)/2;$n({x:c.left+l/2-f*m,y:c.top+u/2-g*m,scale:m})}function tt(e,t={}){let n=M.value.get(e);if(!n)return;let o=re.value,r=wt(),s=Mc(),a=Math.max(80,r.width-s.left-s.right),c=Math.max(80,r.height-s.top-s.bottom),l=Math.min(o.scale,a/n.size.width,c/n.size.height),u=n.position.x+n.size.width/2,d=n.position.y+n.size.height/2;$n({x:s.left+a/2-u*l,y:s.top+c/2-d*l,scale:l},300,t),fn(e)}function $f(e=1){let t=Array.from(M.value.keys());if(t.length===0)return;let o=((ke.value?t.indexOf(ke.value):-1)+e+t.length)%t.length,r=t[o];fn(r),tt(r)}function Mf(e){let t=ke.value;if(!t)return;let n=M.value.get(t);if(!n)return;let o=hf(t,Re.value);if(o.size===0)return;let r=n.position.x+n.size.width/2,s=n.position.y+n.size.height/2,a=null,c=-1/0;for(let l of o){let u=M.value.get(l);if(!u)continue;let d=u.position.x+u.size.width/2,p=u.position.y+u.size.height/2,m=d-r,f=p-s,g=Math.sqrt(m*m+f*f);if(g<1)continue;let y;switch(e){case"up":y=-f;break;case"down":y=f;break;case"left":y=-m;break;case"right":y=m;break}if(y<=0)continue;let x=y/g-g*0.001;if(x>c)c=x,a=l}if(a)tt(a)}function en(e){if(!M.value.get(e))return;if(Tt!==null)clearTimeout(Tt),Tt=null;Qt.value=null,qo=void 0,fn(e),Be.value=e}function Kc(e){if(Tt!==null)clearTimeout(Tt),Tt=null;if(Be.value===e)Be.value=null;if(Qt.value===e)Qt.value=null;qo=void 0}function po(){let e=Be.value,t=e?M.value.get(e):void 0;if(e&&t&&Xp(t)){let n=e,o=Date.now();if(Qt.value=n,qo=t.data.appCheckpoint?.updatedAt,Tt!==null)clearTimeout(Tt);let r=()=>{let a=M.value.get(n)?.data.appCheckpoint?.updatedAt;if(a!==void 0&&a!==qo){Kc(n);return}if(Date.now()-o>=tS){Kc(n);return}Tt=setTimeout(r,uf)};Tt=setTimeout(r,uf);return}if(Tt!==null)clearTimeout(Tt),Tt=null;Qt.value=null,qo=void 0,Be.value=null}function _s(){let e=Gc(Array.from(M.value.values()),Array.from(Re.value.values()),"grid");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;$t(()=>{for(let[t,n]of e.nodePositions.entries())st(t,{position:n});for(let[t,n]of e.groupBounds.entries())bs(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),Ye()}function Ss(){let e=Gc(Array.from(M.value.values()),Array.from(Re.value.values()),"graph");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;$t(()=>{for(let[t,n]of e.nodePositions.entries())st(t,{position:n});for(let[t,n]of e.groupBounds.entries())bs(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),Ye()}var Of="pmx-canvas-iframe-probe";var sS="/api/canvas/iframe-probe",aS=3000,gt=V(null);function cS(){let e=new URLSearchParams(window.location.search).get("iframe-mode");return e==="srcdoc"||e==="src"?e:null}function Lf(e=aS){return new Promise((t)=>{let n=document.createElement("iframe");n.setAttribute("data-pmx-iframe-probe",""),n.style.cssText="position:fixed;width:1px;height:1px;left:-9999px;border:none",n.setAttribute("sandbox","allow-scripts");let o=(a)=>{window.clearTimeout(s),window.removeEventListener("message",r),n.remove(),t(a)},r=(a)=>{if(a.source!==n.contentWindow)return;if(a.data?.source!==Of)return;o(!0)},s=window.setTimeout(()=>o(!1),e);window.addEventListener("message",r),n.addEventListener("error",()=>o(!1)),n.src=sS,(document.body??document.documentElement).appendChild(n)})}var ks=null;function lS(){try{return window.self!==window.top}catch{return!0}}function uS(){return window.__PMX_AMP_ORB===!0}function Df(e={}){if(gt.value)return Promise.resolve(gt.value);if(ks)return ks;let t=cS();if(t)return gt.value=t,Promise.resolve(t);if(!(e.embedded??lS()))return gt.value="src",Lf(e.probeTimeoutMs).then((n)=>{if(!n&&gt.value==="src")gt.value="srcdoc"}),Promise.resolve("src");if(e.ampOrb??uS())return gt.value="srcdoc",Promise.resolve("srcdoc");return ks=Lf(e.probeTimeoutMs).then((n)=>{let o=n?"src":"srcdoc";return gt.value=o,o}),ks}function dS(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",py:"Python",rs:"Rust",go:"Go",rb:"Ruby",java:"Java",kt:"Kotlin",swift:"Swift",c:"C",cpp:"C++",h:"C/C++",css:"CSS",html:"HTML",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",toml:"TOML",sql:"SQL",sh:"Shell",bash:"Shell",xml:"XML",graphql:"GraphQL",proto:"Protobuf"}[t]??(t.toUpperCase()||"Text")}var rl=500;function pS(e){let t=e.toLowerCase();if(t.endsWith(".csv"))return",";if(t.endsWith(".tsv"))return"\t";return null}function fS(e,t){let n=[],o=[],r="",s=!1,a=!1;for(let l=0;l<e.length;l++){let u=e[l];if(a=!0,s){if(u==='"')if(e[l+1]==='"')r+='"',l++;else s=!1;else if(u==="\r"&&e[l+1]===`
35
+ `:"",c=Math.max(0,n-a.length);return`${a}${_t(s,c)}`.trim()}default:return ps(e.data,n)}}function __(e,t){let n=e.position.x+e.size.width/2,o=e.position.y+e.size.height/2,r=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2;return Math.sqrt((n-r)**2+(o-s)**2)}function S_(e,t){let n=e.position.x+e.size.width,o=e.position.y+e.size.height,r=t.position.x+t.size.width,s=t.position.y+t.size.height,a=Math.max(0,Math.max(e.position.x,t.position.x)-Math.min(n,r)),c=Math.max(0,Math.max(e.position.y,t.position.y)-Math.min(o,s));return Math.sqrt(a**2+c**2)}function k_(e){let t=[...e],n=100;return t.sort((o,r)=>{let s=Math.floor(o.position.y/100),a=Math.floor(r.position.y/100);if(s!==a)return s-a;return o.position.x-r.position.x}),t}function C_(e){let t=e.find((r)=>r.data.title&&typeof r.data.title==="string");if(t&&e.length<=3)return e.filter((s)=>s.data.title).map((s)=>s.data.title).slice(0,3).join(", ");let n={};for(let r of e)n[r.type]=(n[r.type]??0)+1;let o=Object.entries(n).map(([r,s])=>s===1?r:`${s} ${r}`);if(t)return`${t.data.title} + ${o.join(", ")}`;return o.join(", ")}function T_(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function E_(e,t){let n=t.filter((r)=>T_(e.bounds,{x:r.position.x,y:r.position.y,width:r.size.width,height:r.size.height})),o=n.map((r)=>typeof r.data.title==="string"&&r.data.title.length>0?r.data.title:r.id);return{id:e.id,label:e.label??e.text??null,bounds:e.bounds,targetNodeIds:n.map((r)=>r.id),targetNodeTitles:o,target:o.length>0?o.join(", "):"empty canvas region"}}function I_(e,t=200){if(e.length===0)return[];let n=new Map,o=(l)=>{while(n.get(l)!==l){let u=n.get(l);n.set(l,n.get(u)),l=u}return l},r=(l,u)=>{let d=o(l),p=o(u);if(d!==p)n.set(d,p)};for(let l of e)n.set(l.id,l.id);for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++)if(S_(e[l],e[u])<=t)r(e[l].id,e[u].id);let s=new Map;for(let l of e){let u=o(l.id);if(!s.has(u))s.set(u,[]);s.get(u).push(l)}let a=[],c=0;for(let[,l]of s){if(l.length<2)continue;let u=l.map((h)=>h.position.x),d=l.map((h)=>h.position.y),p=l.map((h)=>h.position.x+h.size.width),m=l.map((h)=>h.position.y+h.size.height),f=Math.min(...u),g=Math.min(...d),y=Math.max(...p),x=Math.max(...m);a.push({id:`cluster-${c++}`,nodeIds:l.map((h)=>h.id),label:C_(l),centroid:{x:Math.round((f+y)/2),y:Math.round((g+x)/2)},bounds:{x:f,y:g,width:y-f,height:x-g}})}return a.sort((l,u)=>{let d=Math.floor(l.centroid.y/200),p=Math.floor(u.centroid.y/200);if(d!==p)return d-p;return l.centroid.x-u.centroid.x}),a}function A_(e,t,n=5,o=600){let r=e.filter((a)=>t.has(a.id)),s=e.filter((a)=>!t.has(a.id));return r.map((a)=>{let c=s.map((l)=>({node:l,distance:__(a,l)})).filter((l)=>l.distance<=o).sort((l,u)=>l.distance-u.distance).slice(0,n);return{pinnedNodeId:a.id,pinnedNodeTitle:a.data.title??null,neighbors:c.map((l)=>({id:l.node.id,type:l.node.type,title:l.node.data.title??null,distance:Math.round(l.distance)}))}})}function jr(e,t,n,o=[]){let r=I_(e),s=new Map;for(let u of r)for(let d of u.nodeIds)s.set(d,u.id);let c=k_(e).map((u,d)=>({id:u.id,type:u.type,title:u.data.title??null,content:Jp(u,{defaultTextLength:320,webpageTextLength:640})||null,clusterId:s.get(u.id)??null,readingOrder:d})),l=A_(e,n);return{totalNodes:e.length,clusters:r,nodesInReadingOrder:c,pinnedNeighborhoods:l,annotations:o.map((u)=>E_(u,e))}}function Ho(e){if(!e)return null;let t=e.data.title;return typeof t==="string"&&t.trim().length>0?t.trim():null}function fs(e,t){return{id:e?.id??t,title:Ho(e),nodeType:e?.type??"markdown"}}function Yp(e,t){return{id:e.id,edgeType:e.type,fromId:e.from,toId:e.to,fromTitle:Ho(t.get(e.from)),toTitle:Ho(t.get(e.to))}}function ms(e){return new Map(e.map((t)=>[t.id,t]))}function Qp(e){return new Map(e.map((t)=>[t.id,t]))}function Wt(e){return Array.from(e).sort((t,n)=>t.localeCompare(n))}function Bc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Uc(e){if(!e||e.type!=="group")return[];let t=e.data.children;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string").sort((n,o)=>n.localeCompare(o))}function ef(e){let t=new Map;for(let n of e.clusters){let o=[...n.nodeIds].sort((r,s)=>r.localeCompare(s));for(let r of o)t.set(r,o.filter((s)=>s!==r))}return t}function tf(e){let t=new Map;for(let n of e.pinnedNeighborhoods)t.set(n.pinnedNodeId,n.neighbors.map((o)=>o.id).sort((o,r)=>o.localeCompare(r)));return t}function z_(e,t){let n=Wt(Array.from(t).filter((r)=>!e.has(r))),o=Wt(Array.from(e).filter((r)=>!t.has(r)));return{added:n,removed:o}}function nf(e){let t=e&&typeof e==="object"?e:{};return{timestamp:typeof t.timestamp==="string"?t.timestamp:void 0,sessionId:typeof t.sessionId==="string"?t.sessionId:void 0}}function P_(e,t,n){if(!e||!n)return{layout:e,pinnedNodeIds:[],primaryFocusNodeIds:[],secondaryFocusNodeIds:[],regions:[],spatial:n};let o=ms(e.nodes),r=Wt(t).filter((l)=>o.has(l)),s=new Set(r),a=new Set,c=[];for(let l of n.pinnedNeighborhoods){if(!s.has(l.pinnedNodeId))continue;let u=Wt([l.pinnedNodeId,...l.neighbors.map((d)=>d.id)]).filter((d,p,m)=>m.indexOf(d)===p&&o.has(d));for(let d of u)if(!s.has(d))a.add(d);c.push({id:`region-${l.pinnedNodeId}`,primaryNodeId:l.pinnedNodeId,nodeIds:u})}if(c.length===0&&r.length>0)for(let l of r)c.push({id:`region-${l}`,primaryNodeId:l,nodeIds:[l]});return{layout:e,pinnedNodeIds:r,primaryFocusNodeIds:r,secondaryFocusNodeIds:Wt(a),regions:c,spatial:n}}class hs{currentLayout=null;currentPins=new Set;previousSpatial=null;setInitialPins(e){this.currentPins=new Set(e)}getAttentionSnapshot(){return P_(this.currentLayout,this.currentPins,this.previousSpatial)}handleMessage(e){if(e.event==="context-pins-changed")return this.handleContextPinsChanged(e.data);if(e.event==="canvas-layout-update")return this.handleLayoutUpdate(e.data);return[]}handleContextPinsChanged(e){let t=e&&typeof e==="object"?e:{},n=Array.isArray(t.nodeIds)?t.nodeIds.filter((u)=>typeof u==="string"):[],o=nf(e),r=new Set(n),{added:s,removed:a}=z_(this.currentPins,r);if(this.currentPins=r,!this.currentLayout)return[];let c=ms(this.currentLayout.nodes),l={added:s.map((u)=>fs(c.get(u),u)),removed:a.map((u)=>fs(c.get(u),u))};if(this.previousSpatial=jr(this.currentLayout.nodes,this.currentLayout.edges,this.currentPins,this.currentLayout.annotations??[]),l.added.length===0&&l.removed.length===0)return[];return[{type:"context-pin",...o,...l}]}handleLayoutUpdate(e){let t=e&&typeof e==="object"?e:{},n=t.layout&&typeof t.layout==="object"?t.layout:null;if(!n)return[];let o=nf(e);if(!this.currentLayout)return this.currentLayout=n,this.previousSpatial=jr(n.nodes,n.edges,this.currentPins,n.annotations??[]),[];let r=this.currentLayout,s=this.previousSpatial??jr(r.nodes,r.edges,this.currentPins,r.annotations??[]),a=jr(n.nodes,n.edges,this.currentPins,n.annotations??[]),c=[],l=ms(r.nodes),u=ms(n.nodes),d=Qp(r.edges),p=Qp(n.edges),m=Wt(Array.from(p.keys()).filter((h)=>!d.has(h))).map((h)=>p.get(h)).filter((h)=>h!==void 0);if(m.length>0)c.push({type:"connect",...o,edges:m.map((h)=>Yp(h,u))});let f=Wt(Array.from(l.keys()).filter((h)=>!u.has(h))),g=Wt(Array.from(d.keys()).filter((h)=>!p.has(h)));if(f.length>0||g.length>0)c.push({type:"remove",...o,nodes:f.map((h)=>fs(l.get(h),h)),edges:g.map((h)=>d.get(h)).filter((h)=>h!==void 0).map((h)=>Yp(h,l))});let y=this.buildGroupEvent(l,u,o);if(y)c.push(y);let x=this.buildMoveEndEvent(r,n,l,u,s,a,o);if(x)c.push(x);return this.currentLayout=n,this.previousSpatial=a,c}buildGroupEvent(e,t,n){let o=Wt(Array.from(e.values()).filter((c)=>c.type==="group").map((c)=>c.id)),r=Wt(Array.from(t.values()).filter((c)=>c.type==="group").map((c)=>c.id)),s=r.filter((c)=>!o.includes(c)).map((c)=>{let l=t.get(c),u=Uc(l);return{id:c,title:Ho(l),childCount:u.length}}),a=[];for(let c of r.filter((l)=>o.includes(l))){let l=Uc(e.get(c)),u=Uc(t.get(c));if(Bc(l,u))continue;a.push({id:c,title:Ho(t.get(c)),addedChildIds:u.filter((d)=>!l.includes(d)),removedChildIds:l.filter((d)=>!u.includes(d)),childCount:u.length})}if(s.length===0&&a.length===0)return null;return{type:"group",...n,created:s,updated:a}}buildMoveEndEvent(e,t,n,o,r,s,a){let c=Wt(Array.from(o.keys()).filter((x)=>{let h=n.get(x),v=o.get(x);if(!h||!v)return!1;return h.position.x!==v.position.x||h.position.y!==v.position.y}));if(c.length===0)return null;let l=ef(r),u=ef(s),d=tf(r),p=tf(s),m=new Map,f=(x,h)=>{let v=m.get(x)??new Set;v.add(h),m.set(x,v)};for(let x of c){let h=l.get(x)??[],v=u.get(x)??[];if(!Bc(h,v))if(h.length===0&&v.length>0)f(x,"joined cluster");else if(h.length>0&&v.length===0)f(x,"left cluster");else f(x,"cluster changed")}let g=new Set([...d.keys(),...p.keys()]);for(let x of g){let h=d.get(x)??[],v=p.get(x)??[];if(Bc(h,v))continue;let b=Ho(o.get(x)??n.get(x))??x,z=v.filter((_)=>!h.includes(_)),F=h.filter((_)=>!v.includes(_));for(let _ of z)if(c.includes(_))f(_,`entered pinned neighborhood of "${b}"`);for(let _ of F)if(c.includes(_))f(_,`left pinned neighborhood of "${b}"`);if(c.includes(x))f(x,"pinned neighborhood changed")}let y=c.filter((x)=>(m.get(x)?.size??0)>0).map((x)=>{let h=o.get(x);return{...fs(h,x),reasons:Array.from(m.get(x)??[]).sort((v,b)=>v.localeCompare(b))}});if(y.length===0)return null;return{type:"move-end",...a,nodes:y}}}var Gc=new hs,Bo=[],Zr=null,Uo=null,Wc="",qc=0;function rf(e,t){return globalThis.setTimeout(e,t)}function Vc(e){if(e===null)return;globalThis.clearTimeout(e)}function N_(e){if(typeof globalThis.requestAnimationFrame==="function"){globalThis.requestAnimationFrame(()=>e());return}e()}function An(e,t){return e&&e.trim().length>0?e.trim():t}function cn(e,t=3){if(e.length===0)return"";if(e.length<=t)return e.join(", ");return`${e.slice(0,t).join(", ")} +${e.length-t}`}function R_(e){return Array.from(new Set(Array.from(e).filter((t)=>t.length>0)))}function qt(e,t,n,o,r=Date.now()){return{id:`${e}-${r}-${Math.random().toString(36).slice(2,8)}`,tone:e,title:t,detail:n,nodeIds:R_(o),createdAt:r}}function of(e){if(e==="joined cluster")return"joined a nearby cluster";if(e==="left cluster")return"moved away from its cluster";if(e==="cluster changed")return"shifted into a different cluster";if(e==="pinned neighborhood changed")return"changed the local focus field";let t=/^entered pinned neighborhood of "(.+)"$/.exec(e);if(t)return`moved into focus around ${t[1]}`;let n=/^left pinned neighborhood of "(.+)"$/.exec(e);if(n)return`moved out of focus around ${n[1]}`;return e}function $_(e){let t=e.added.map((r)=>An(r.title,r.id)),n=e.removed.map((r)=>An(r.title,r.id));if(t.length===0&&n.length===0)return null;let o="";if(t.length>0&&n.length===0)o=`Now in focus: ${cn(t)}`;else if(n.length>0&&t.length===0)o=`Removed from focus: ${cn(n)}`;else{let r=[];if(t.length>0)r.push(`${cn(t)} added`);if(n.length>0)r.push(`${cn(n)} removed`);o=r.join(" · ")}return qt("context","Context updated",o,[...e.added.map((r)=>r.id),...e.removed.map((r)=>r.id)],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function M_(e){if(e.edges.length===0)return null;if(e.edges.length===1){let t=e.edges[0];return qt("relationship","Relationship added",`${An(t.fromTitle,t.fromId)} linked to ${An(t.toTitle,t.toId)}`,[t.fromId,t.toId],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return qt("relationship","Relationships added",`${e.edges.length} connections changed the board structure`,e.edges.flatMap((t)=>[t.fromId,t.toId]),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function O_(e){if(e.nodes.length===0&&e.edges.length===0)return null;let t=e.nodes.map((o)=>An(o.title,o.id)),n=[];if(t.length>0)n.push(cn(t));if(e.edges.length>0)n.push(`${e.edges.length} relationship${e.edges.length===1?"":"s"}`);return qt("remove","Items removed",n.join(" · "),[...e.nodes.map((o)=>o.id),...e.edges.flatMap((o)=>[o.fromId,o.toId])],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function L_(e){if(e.created.length>0){let t=e.created.map((n)=>An(n.title,n.id));return qt("group",e.created.length===1?"Group created":"Groups created",e.created.length===1?`${t[0]} now frames ${e.created[0].childCount} items`:cn(t),e.created.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}if(e.updated.length>0){let t=e.updated.map((n)=>An(n.title,n.id));return qt("group",e.updated.length===1?"Group updated":"Groups updated",e.updated.length===1?`${t[0]} now holds ${e.updated[0].childCount} items`:cn(t),e.updated.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return null}function D_(e){if(e.nodes.length===0)return null;let t=e.nodes.flatMap((s)=>s.reasons),n=e.nodes.map((s)=>An(s.title,s.id)),o=e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now();if(t.some((s)=>s.includes("pinned neighborhood"))){if(e.nodes.length===1)return qt("neighborhood","Neighborhood changed",`${n[0]} ${of(e.nodes[0].reasons[0])}`,e.nodes.map((s)=>s.id),o);return qt("neighborhood","Neighborhood changed",cn(n),e.nodes.map((s)=>s.id),o)}let r=t.filter((s)=>s.includes("cluster"));if(r.length>0){let s=r.every((a)=>a==="joined cluster");if(e.nodes.length===1)return qt("cluster",s?"Cluster formed":"Cluster changed",`${n[0]} ${of(e.nodes[0].reasons[0])}`,e.nodes.map((a)=>a.id),o);return qt("cluster",s?"Cluster formed":"Cluster changed",cn(n),e.nodes.map((a)=>a.id),o)}return null}function F_(e){switch(e.type){case"context-pin":return $_(e);case"connect":return M_(e);case"remove":return O_(e);case"group":return L_(e);case"move-end":return D_(e)}}function j_(){let e=Gc.getAttentionSnapshot();Pp(e.primaryFocusNodeIds,e.secondaryFocusNodeIds,e.regions)}function sf(){if(Zr!==null)return;let e=Bo.shift()??null;if(!e){ts(null);return}ts(e);let t=Math.max(1800,Math.min(2800,1600+e.detail.length*18));Zr=rf(()=>{Zr=null,ts(null),sf()},t)}function af(e){if(Bo.push(e),Bo.length>3)Bo.splice(0,Bo.length-3);sf()}function Wo(e,t,n="",o=[]){af(qt(e,t,n,o))}function Z_(e){if(Vc(Uo),Uo=null,ns([]),e.length===0)return;N_(()=>{ns(e),Uo=rf(()=>{Uo=null,ns([])},900)})}function H_(e){let t=`${e.tone}:${e.title}:${e.detail}`,n=e.createdAt;if(t===Wc&&n-qc<1200)return!0;return Wc=t,qc=n,!1}function Xc(){Vc(Zr),Vc(Uo),Zr=null,Uo=null,Bo=[],Wc="",qc=0,Gc=new hs,Ap()}function Kc(e){let t=Gc.handleMessage(e).map((n)=>F_(n)).filter((n)=>n!==null);j_();for(let n of t){if(H_(n))continue;Np(n),af(n),Z_(n.nodeIds)}}async function zn(e,t,n,o){let r=await cs({type:t,sourceNodeId:e.id,sourceSurface:"native-node",...n?{payload:n}:{}});if(r.ok)Wo("context",o,"",[e.id]);else Wo("remove","AX action failed",r.error??r.code??"Unknown error",[e.id])}var ao={padding:"3px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer",flexShrink:0};function B_(e){let t=e.title||e.label||e.key||"Context",n=e.summary?.trim()||"Available in startup context.",o=e.pathDisplay||e.path||"",r=e.category==="profile"?"Operator":e.category==="planning"||e.category==="memory"?"Product":e.category?e.category.charAt(0).toUpperCase()+e.category.slice(1):void 0,s=e.sourceKind==="global"?"Global":"Workspace",a=e.state==="missing"?"Missing":e.state==="stale"?"Stale":e.state==="invalid"?"Invalid":"Loaded";return{title:t,summary:n,pathDisplay:o,category:r,sourceKind:s,status:a,required:e.required===!0}}function Vt(e){return typeof e==="string"?e.trim():""}function U_(e){return e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function W_(e){let t=Vt(e.title),n=Vt(e.content),o=U_(Vt(e.rendered)),r=n||o,s=Vt(e.path);if(!t&&!r&&!s)return null;return{title:t||"Context",summary:r,path:s}}function q_(e){let t=Vt(e.data.title)||e.id,n=Vt(e.data.content)||Vt(e.data.excerpt)||Vt(e.data.description)||Vt(e.data.pageTitle)||"",o=Vt(e.data.path)||Vt(e.data.url);return{id:e.id,title:t,summary:n,kind:st[e.type]??e.type,path:o}}function cf(e){if(e===null||!Number.isFinite(e)||e<0)return"0";if(e>=1e6)return`${(e/1e6).toFixed(1)}m`;if(e>=1000)return`${(e/1000).toFixed(1)}k`;return`${Math.round(e)}`}function V_(e){if(e>=0.95)return"var(--c-danger)";if(e>=0.85)return"var(--c-warn)";if(e>=0.7)return"var(--c-warn)";return"var(--c-accent)"}function gs({node:e,expanded:t=!1,pinnedNodes:n=[]}){let o=e.data.cards??[],r=e.data.auxTabs??[],s=n.map(q_),a=s.length>0,c=typeof e.data.currentTokens==="number"?e.data.currentTokens:null,l=typeof e.data.tokenLimit==="number"?e.data.tokenLimit:null,u=typeof e.data.utilization==="number"?e.data.utilization:null,d=typeof e.data.messagesLength==="number"?e.data.messagesLength:null,p=u!==null?Math.max(0,Math.min(100,Math.round(u*100))):null,m=V_(u??0),f=!a&&o.length===0&&r.length===0?W_(e.data):null,g=async(y)=>{let x=typeof y.path==="string"?y.path.trim():"";if(!x)return;await rs(x)};return i("div",{style:{display:"flex",flexDirection:"column",gap:t?"10px":"6px",fontSize:t?"14px":"12px",maxWidth:t?"760px":void 0,margin:t?"0 auto":void 0,width:t?"100%":void 0,padding:t?"8px 0":void 0},children:[i("div",{style:{display:"flex",justifyContent:"flex-end"},children:i("button",{type:"button",class:"ax-node-action",title:"Point the agent at this node — sets it as the agent's current AX focus so the agent pulls it into context to work on next (a one-click alternative to manually pinning).",style:ao,onClick:(y)=>{y.stopPropagation(),zn(e,"ax.focus.set",void 0,"Focus set")},children:"Set focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this),l!==null&&l>0&&i("div",{style:{marginBottom:"8px"},children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:"Token Usage"},void 0,!1,void 0,this),i("div",{style:{height:"6px",background:"var(--c-surface-hover)",borderRadius:"3px",overflow:"hidden",marginBottom:"4px"},children:i("div",{style:{height:"100%",width:`${Math.min(100,(u??0)*100)}%`,background:m,borderRadius:"3px",transition:"width 0.3s ease"}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{style:{fontSize:"11px",color:"var(--c-muted)"},children:[p,"% — ",cf(c)," / ",cf(l)," tokens",d!==null&&i(ve,{children:[" · ",d," messages"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&i("div",{children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Pinned Context (",s.length,")"]},void 0,!0,void 0,this),s.map((y)=>i("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[i("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:y.title},void 0,!1,void 0,this),y.summary&&i("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px",whiteSpace:"pre-wrap"},children:y.summary},void 0,!1,void 0,this),i("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:y.kind},void 0,!1,void 0,this)},void 0,!1,void 0,this),y.path&&i("div",{style:{marginTop:"6px"},children:[i("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:y.path},void 0,!1,void 0,this),y.path.startsWith("/")&&i("button",{type:"button",onClick:()=>void rs(y.path),style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},y.id,!0,void 0,this))]},void 0,!0,void 0,this),!a&&o.length>0&&i("div",{children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Context (",o.length,")"]},void 0,!0,void 0,this),o.map((y)=>{let x=B_(y);return i("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[i("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:x.title},void 0,!1,void 0,this),i("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px"},children:x.summary},void 0,!1,void 0,this),x.pathDisplay&&i("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all"},children:x.pathDisplay},void 0,!1,void 0,this),i("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:[i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-accent-10)",color:"var(--c-accent)",borderRadius:"3px",display:"inline-block"},children:x.status},void 0,!1,void 0,this),x.category&&i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:x.category},void 0,!1,void 0,this),i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:x.sourceKind},void 0,!1,void 0,this),x.required&&i("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-warn-12)",color:"var(--c-warn-alt)",borderRadius:"3px",display:"inline-block"},children:"Required"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y.path&&i("div",{style:{marginTop:"6px"},children:i("button",{type:"button",onClick:()=>void g(y),style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},y.key??x.pathDisplay??x.title,!0,void 0,this)})]},void 0,!0,void 0,this),!a&&r.length>0&&i("div",{children:[i("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px",marginTop:o.length>0?"8px":0},children:["References (",r.length,")"]},void 0,!0,void 0,this),r.map((y)=>i("a",{href:y.url,target:"_blank",rel:"noopener noreferrer",style:{display:"block",padding:"4px 8px",color:"var(--c-accent)",fontSize:"11px",textDecoration:"none",borderRadius:"4px",marginBottom:"2px",wordBreak:"break-all"},children:[y.url,y.reason&&i("span",{style:{color:"var(--c-dim)",fontSize:"10px",marginLeft:"6px"},children:["(",y.reason,")"]},void 0,!0,void 0,this)]},y.id,!0,void 0,this))]},void 0,!0,void 0,this),f&&i("div",{style:{padding:"8px 10px",background:"var(--c-surface-subtle)",borderRadius:"6px",borderLeft:"2px solid var(--c-accent)"},children:[i("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"4px"},children:f.title},void 0,!1,void 0,this),f.summary&&i("div",{style:{color:"var(--c-text-soft)",fontSize:"11px",lineHeight:1.5,whiteSpace:"pre-wrap"},children:f.summary},void 0,!1,void 0,this),f.path&&i("div",{style:{marginTop:"6px"},children:[i("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:f.path},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>void rs(f.path),style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-accent-12)",border:"1px solid var(--c-accent-25)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!a&&!f&&o.length===0&&r.length===0&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic"},children:"No context loaded"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function lf(e){return e.replace(/^[ab]\//,"")}function G_(e,t){if(t&&t!=="/dev/null")return lf(t);if(e&&e!=="/dev/null")return lf(e);return null}function X_(e){if(!e.trim())return[];let t=e.split(`
36
+ `);if(t.length>0&&t[t.length-1]==="")t.pop();let n=[],o=null,r=!1,s=(a)=>{let c={path:a,lines:[]};return r=!1,n.push(c),c};for(let a=0;a<t.length;a++){let c=t[a]??"",l=c.match(/^diff --git a\/(.+?) b\/(.+)$/);if(l){o=s(l[2]??null);continue}let u=t[a+1]??"";if(c.startsWith("--- ")&&u.startsWith("+++ ")){let p=G_(c.slice(4).trim(),u.slice(4).trim());if(o&&!r){if(!o.path)o.path=p}else o=s(p);a++;continue}if(!o)o=s(null);let d=o;if(c.startsWith("@@"))r=!0,d.lines.push({kind:"hunk",text:c});else if(c.startsWith("+"))d.lines.push({kind:"add",text:c});else if(c.startsWith("-"))d.lines.push({kind:"remove",text:c});else d.lines.push({kind:"context",text:c})}return n}function vs({node:e}){let t=typeof e.data.content==="string"?e.data.content:"",n=Ae(()=>X_(t),[t]);if(n.length===0)return i("div",{class:"diff-node diff-node-empty",children:"Empty diff"},void 0,!1,void 0,this);return i("div",{class:"diff-node",children:n.map((o,r)=>i("div",{class:"diff-file",children:[o.path&&i("div",{class:"diff-file-header",children:o.path},void 0,!1,void 0,this),i("pre",{class:"diff-lines",children:o.lines.map((s,a)=>i("div",{class:s.kind==="hunk"?"diff-hunk":`diff-line-${s.kind}`,children:s.text||" "},a,!1,void 0,this))},void 0,!1,void 0,this)]},`${o.path??"anonymous"}-${r}`,!0,void 0,this))},void 0,!1,void 0,this)}function uf(e){if(e.length===0)return null;let{POSITIVE_INFINITY:t,POSITIVE_INFINITY:n,NEGATIVE_INFINITY:o,NEGATIVE_INFINITY:r}=Number;for(let s of e)t=Math.min(t,s.position.x),n=Math.min(n,s.position.y),o=Math.max(o,s.position.x+s.size.width),r=Math.max(r,s.position.y+s.size.height);if(!Number.isFinite(t)||!Number.isFinite(n))return null;return{x:t-40,y:n-40-32,width:o-t+80,height:r-n+80+32}}function K_(e){let t=e.filter((l)=>!l.pinned),n=new Map(t.map((l)=>[l.id,l])),o=new Map,r=[],s=new Map;for(let l of t){if(l.type==="group")continue;let u=typeof l.data.parentGroup==="string"?l.data.parentGroup:"",d=u?n.get(u):void 0;if(!d||d.type!=="group")continue;if(!s.has(u))s.set(u,[]);s.get(u).push(l)}let a=t.filter((l)=>l.type==="group").sort((l,u)=>l.position.y-u.position.y||l.position.x-u.position.x);for(let l of a){let u=s.get(l.id)??[];if(u.length===0){let f=`unit:${l.id}`;r.push({id:f,memberIds:[l.id],origin:{...l.position},size:{...l.size},sortKey:{x:l.position.x,y:l.position.y}}),o.set(l.id,f);continue}let d=u.map((f)=>({position:f.position,size:f.size})),p=uf(d);if(!p)continue;let m=`group:${l.id}`;r.push({id:m,memberIds:u.map((f)=>f.id),origin:{x:p.x,y:p.y},size:{width:p.width,height:p.height},sortKey:{x:p.x,y:p.y},groupId:l.id}),o.set(l.id,m);for(let f of u)o.set(f.id,m)}let c=t.filter((l)=>!o.has(l.id)).sort((l,u)=>l.position.y-u.position.y||l.position.x-u.position.x);for(let l of c){let u=`unit:${l.id}`;r.push({id:u,memberIds:[l.id],origin:{...l.position},size:{...l.size},sortKey:{x:l.position.x,y:l.position.y}}),o.set(l.id,u)}return{units:r,nodesById:n,nodeToUnit:o}}function J_(e,t,n){let o=new Map,r=new Map,s=new Map,a=new Map;for(let c of e)o.set(c.id,new Set),r.set(c.id,new Set),s.set(c.id,0),a.set(c.id,0);for(let c of n){let l=t.get(c.from),u=t.get(c.to);if(!l||!u||l===u)continue;if(!o.get(l).has(u))o.get(l).add(u),a.set(l,(a.get(l)??0)+1),s.set(u,(s.get(u)??0)+1);r.get(l).add(u),r.get(u).add(l)}return{outgoing:o,undirected:r,indegree:s,outdegree:a}}function Y_(e,t){let n=new Map(e.map((s)=>[s.id,s])),o=new Set,r=[];for(let s of e){if(o.has(s.id))continue;let a=[s.id],c=[];o.add(s.id);while(a.length>0){let u=a.pop();c.push(u);for(let d of t.get(u)??[]){if(o.has(d))continue;o.add(d),a.push(d)}}let l=c.map((u)=>n.get(u)).filter((u)=>u!==void 0).sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);r.push(l)}return r.sort((s,a)=>s[0].sortKey.y-a[0].sortKey.y||s[0].sortKey.x-a[0].sortKey.x)}function Q_(e){let t=new Map,n=0,o=0,r=0,s=0,a=Math.max(900,Math.ceil(Math.sqrt(e.reduce((c,l)=>c+l.size.width*l.size.height,0))));for(let c of e){if(n>0&&n+c.size.width>a)n=0,o+=r+72,r=0;t.set(c.id,{x:n,y:o}),n+=c.size.width+96,r=Math.max(r,c.size.height),s=Math.max(s,n-96)}return{positions:t,size:{width:Math.max(0,s),height:o+r},sortKey:e[0].sortKey}}function eS(e,t,n,o,r){if(e.length===1)return{positions:new Map([[e[0].id,{x:0,y:0}]]),size:{...e[0].size},sortKey:e[0].sortKey};let s=new Set(e.map((v)=>v.id)),a=e.filter((v)=>(o.get(v.id)??0)===0&&(r.get(v.id)??0)>0).sort((v,b)=>v.sortKey.x-b.sortKey.x||v.sortKey.y-b.sortKey.y),c=a.length>0?a:[e.slice().sort((v,b)=>v.sortKey.x-b.sortKey.x||v.sortKey.y-b.sortKey.y)[0]],l=new Map,u=c.map((v)=>v.id);for(let v of c)l.set(v.id,0);while(u.length>0){let v=u.shift(),b=l.get(v)??0;for(let z of n.get(v)??[]){if(!s.has(z)||l.has(z))continue;l.set(z,b+1),u.push(z)}}let d=0;for(let v of e){if(l.has(v.id))continue;l.set(v.id,d),d+=1}let p=new Map;for(let v of e){let b=l.get(v.id)??0;if(!p.has(b))p.set(b,[]);p.get(b).push(v)}let m=Array.from(p.keys()).sort((v,b)=>v-b);for(let v of m)p.get(v).sort((b,z)=>b.sortKey.y-z.sortKey.y||b.sortKey.x-z.sortKey.x);let f=new Map,g=new Map,y=0;for(let v of m){let b=p.get(v),z=b.reduce((_,k,T)=>_+k.size.height+(T>0?72:0),0),F=Math.max(...b.map((_)=>_.size.width));f.set(v,z),g.set(v,F),y=Math.max(y,z)}let x=new Map,h=0;for(let v of m){let b=p.get(v),z=f.get(v)??0,F=g.get(v)??0,_=Math.max(0,(y-z)/2);for(let k of b)x.set(k.id,{x:h,y:_}),_+=k.size.height+72;h+=F+96}return{positions:x,size:{width:Math.max(0,h-96),height:y},sortKey:e[0].sortKey}}function tS(e,t){let n=new Map(e.map((l)=>[l.id,l.id])),o=(l)=>{let u=l;while(n.get(u)!==u)u=n.get(u);let d=l;while(n.get(d)!==d){let p=n.get(d);n.set(d,u),d=p}return u},r=(l,u)=>{let d=o(l),p=o(u);if(d!==p)n.set(d,p)},s=160;for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++){let d=e[l],p=e[u];if(d.origin.x-160<p.origin.x+p.size.width+160&&d.origin.x+d.size.width+160>p.origin.x-160&&d.origin.y-160<p.origin.y+p.size.height+160&&d.origin.y+d.size.height+160>p.origin.y-160)r(d.id,p.id)}for(let[l,u]of t)for(let d of u)if(n.has(l)&&n.has(d))r(l,d);let a=new Map;for(let l of e){let u=o(l.id);if(!a.has(u))a.set(u,[]);a.get(u).push(l)}let c=Array.from(a.values());for(let l of c)l.sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);return c.sort((l,u)=>l[0].sortKey.y-u[0].sortKey.y||l[0].sortKey.x-u[0].sortKey.x)}function nS(e,t){let n=new Map,{x:o,y:r}=t,s=0;for(let a of e){if(o>t.x&&o-t.x+a.size.width>3200)o=t.x,r+=s+180,s=0;for(let[c,l]of a.positions.entries())n.set(c,{x:o+l.x,y:r+l.y});o+=a.size.width+220,s=Math.max(s,a.size.height)}return n}function Jc(e,t,n){let{units:o,nodesById:r,nodeToUnit:s}=K_(e),a=new Map,c=new Map;if(o.length===0)return{nodePositions:a,groupBounds:c};let{outgoing:l,undirected:u,indegree:d,outdegree:p}=J_(o,s,t),m=tS(o,u),f=new Map,g=[];for(let y of m){let x=Y_(y,u).map((_)=>n==="graph"?eS(_,l,u,d,p):Q_(_)),h={x:Math.min(...y.map((_)=>_.origin.x)),y:Math.min(...y.map((_)=>_.origin.y))},v=nS(x,h),b=new Map(y.map((_)=>[_.id,_.size])),z=(_)=>{let{POSITIVE_INFINITY:k,POSITIVE_INFINITY:T,NEGATIVE_INFINITY:P,NEGATIVE_INFINITY:Z}=Number;for(let[j,E]of _){let B=b.get(j);if(!B)continue;k=Math.min(k,E.x),T=Math.min(T,E.y),P=Math.max(P,E.x+B.width),Z=Math.max(Z,E.y+B.height)}return{x:k,y:T,width:P-k,height:Z-T}},F=v;for(let _=0;_<=g.length;_++){let k=z(F),T=g.filter((j)=>k.x<j.x+j.width+220&&k.x+k.width+220>j.x&&k.y<j.y+j.height+180&&k.y+k.height+180>j.y);if(T.length===0)break;let P=Math.max(...T.map((j)=>j.y+j.height))+180-k.y;if(P<=0)break;let Z=new Map;for(let[j,E]of F)Z.set(j,{x:E.x,y:E.y+P});F=Z}for(let[_,k]of F)f.set(_,k);g.push(z(F))}for(let y of o){let x=f.get(y.id);if(!x)continue;let h=x.x-y.origin.x,v=x.y-y.origin.y;if(y.groupId){let F=[];for(let k of y.memberIds){let T=r.get(k);if(!T)continue;let P={x:T.position.x+h,y:T.position.y+v};a.set(k,P),F.push({position:P,size:T.size})}let _=uf(F);if(_)c.set(y.groupId,_);continue}let b=y.memberIds[0],z=r.get(b);if(!z)continue;a.set(b,{x:z.position.x+h,y:z.position.y+v})}return{nodePositions:a,groupBounds:c}}function hf(e,t){console.error(`[canvas-store] ${e} failed`,t)}var re=V({x:0,y:0,scale:1}),R=V(new Map),Re=V(new Map),Vo=V(new Map),ke=V(null),un=V(null),Et=V("connecting"),co=V(0),lo=V(0),uo=V(0),dn=V(""),Go=V(!1),Xe=V("dark"),Gt=V(!1),Xt=V(null),Be=V(null),Qt=V(null),Tt=null,qo,df=100,oS=2500,ys=V(null),je=V(null),Nn=V(null),ye=V(new Set),Ee=V(new Set),yt=V("select"),Br=V(!1);function Xo(){return yt.value==="pan"||Br.value}function gf(e,t){if(!e)return new Set;let n=new Set;for(let o of t.values()){if(o.from===e)n.add(o.to);if(o.to===e)n.add(o.from)}return n}var vf=Oe(()=>gf(ke.value,Re.value));function pf(e,t){let n=new Set;for(let o of e)if(t.has(o))n.add(o);return n}function ff(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function el(e){let t=new Set(ye.value);if(t.has(e))t.delete(e);else t.add(e);ye.value=t}function yf(e){ye.value=new Set(e)}function ht(){if(un.value=null,ye.value.size===0)return;ye.value=new Set}var ln=V(null),tl=!1;function xf(){tl=!0,ln.value=null}function bf(){tl=!1,ln.value=null}function Yc(e){return{x:e.position.x,y:e.position.y,w:e.size.width,h:e.size.height}}function rS(e,t,n){let o=Yc(e);return t>=o.x&&t<=o.x+o.w&&n>=o.y&&n<=o.y+o.h}function mf(e,t){let n=Yc(e),o=Yc(t);return n.x+n.w<o.x||n.x>o.x+o.w||n.y+n.h<o.y||n.y>o.y+o.h}function wf(e){let t=R.value.get(e);if(!t||t.type==="group")return;let n=typeof t.data.parentGroup==="string"?t.data.parentGroup:null,o=n?R.value.get(n):void 0,r=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=null;for(let c of R.value.values()){if(c.type!=="group"||c.id===n||c.collapsed)continue;if(rS(c,r,s))a=c}if(!tl){let c=a?{nodeId:e,groupId:a.id,mode:"add"}:o&&mf(t,o)?{nodeId:e,groupId:o.id,mode:"remove"}:null,l=ln.value;if((l?.groupId??null)!==(c?.groupId??null)||l?.mode!==c?.mode)ln.value=c}if(o&&o.data.frameMode!=="manual"&&!mf(t,o)){let l=Math.min(o.position.x,t.position.x-22),u=Math.min(o.position.y,t.position.y-22-32),d=Math.max(o.position.x+o.size.width,t.position.x+t.size.width+22),p=Math.max(o.position.y+o.size.height,t.position.y+t.size.height+22);if(l!==o.position.x||u!==o.position.y||d!==o.position.x+o.size.width||p!==o.position.y+o.size.height)_s(o.id,{position:{x:l,y:u},size:{width:d-l,height:p-u}},{skipGroupChildTranslation:!0})}}var nl=Oe(()=>{let e=new Map;for(let t of R.value.values()){if(t.type!=="group"||!t.collapsed)continue;let n=Array.isArray(t.data.children)?t.data.children:[];for(let o of n)if(typeof o==="string")e.set(o,t.id)}return e});function xs(e){let t=nl.value.get(e);return R.value.get(t??e)}function _f(){let e=new Set;for(let t of ye.value){let n=R.value.get(t);if(!n)continue;if(n.type==="group")e.add(n.id);else if(typeof n.data.parentGroup==="string")e.add(n.data.parentGroup)}return[...e]}function ol(e){let t=rl();if(t.length<2)return;let n=Math.min(...t.map((l)=>e==="left"?l.position.x:l.position.y)),o=24,r=new Map;for(let l of t)r.set(l.id,e==="left"?{x:n,y:l.position.y}:{x:l.position.x,y:n});let s=(l,u)=>l.x<u.x+u.w&&u.x<l.x+l.w&&l.y<u.y+u.h&&u.y<l.y+l.h,a=t.map((l)=>{let u=r.get(l.id);return{node:l,x:u.x,y:u.y,w:l.size.width,h:l.size.height}});if(a.some((l,u)=>a.some((d,p)=>p>u&&s(l,d)))){let l=[...t].sort((d,p)=>e==="left"?d.position.y-p.position.y:d.position.x-p.position.x),u=e==="left"?Math.min(...t.map((d)=>d.position.y)):Math.min(...t.map((d)=>d.position.x));for(let d of l)r.set(d.id,e==="left"?{x:n,y:u}:{x:u,y:n}),u+=(e==="left"?d.size.height:d.size.width)+o}$t(()=>{for(let l of t)et(l.id,{position:r.get(l.id)})}),nt()}function Sf(){let e=rl().sort((c,l)=>c.position.x-l.position.x);if(e.length<3)return;let t=e[0],o=e[e.length-1].position.x-(t.position.x+t.size.width),r=e.slice(1,-1),s=r.reduce((c,l)=>c+l.size.width,0),a=(o-s)/(r.length+1);$t(()=>{if(a<8){let l=t.position.x+t.size.width+24;for(let u of e.slice(1))et(u.id,{position:{x:l,y:u.position.y}}),l+=u.size.width+24;return}let c=t.position.x+t.size.width+a;for(let l of r)et(l.id,{position:{x:c,y:l.position.y}}),c+=l.size.width+a}),nt()}function kf(e=24){let t=rl().sort((c,l)=>c.position.y-l.position.y||c.position.x-l.position.x);if(t.length<2)return;let n=Math.min(...t.map((c)=>c.position.x)),o=Math.min(...t.map((c)=>c.position.y)),r=Math.ceil(Math.sqrt(t.length)),s=Math.max(...t.map((c)=>c.size.width)),a=Math.max(...t.map((c)=>c.size.height));$t(()=>{t.forEach((c,l)=>{et(c.id,{position:{x:n+l%r*(s+e),y:o+Math.floor(l/r)*(a+e)}})})}),nt()}function rl(){let e=ye.value;if(e.size===0)return[];return Array.from(e).map((t)=>R.value.get(t)).filter((t)=>t!==void 0)}function Rn(e){let t=new Set(Ee.value);if(t.has(e))t.delete(e);else t.add(e);Ee.value=t,nt(),ws(t)}function bs(e){let t=new Set(Ee.value);for(let n of e)t.add(n);Ee.value=t,nt(),ws(t)}function Cf(){if(Ee.value.size===0)return;Ee.value=new Set,nt(),ws(new Set)}function Tf(e){Ee.value=new Set(e)}function ws(e){Bt("syncContextPinsToServer","/api/canvas/context-pins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeIds:Array.from(e)})})}var Hr=1;function pn(e){$t(()=>{let t=new Map(R.value);if(e.zIndex>=Hr)Hr=e.zIndex+1;t.set(e.id,e),R.value=t,ke.value=e.id})}function et(e,t){_s(e,t)}function _s(e,t,n={}){let o=R.value.get(e);if(!o)return;let r=new Map(R.value);if(o.type==="group"&&t.position&&n.skipGroupChildTranslation!==!0){let a=t.position.x-o.position.x,c=t.position.y-o.position.y;if(a!==0||c!==0){let l=Array.isArray(o.data.children)?o.data.children.filter((u)=>typeof u==="string"):[];for(let u of l){let d=r.get(u);if(!d||d.type==="group")continue;r.set(u,{...d,position:{x:d.position.x+a,y:d.position.y+c}})}}}r.set(e,{...o,...t}),R.value=r;let s=r.get(e)?.data.appCheckpoint?.updatedAt;if(Qt.value===e&&s!==void 0&&s!==qo)Qc(e)}function oe(e,t){let n=R.value.get(e);if(!n)return;et(e,{data:{...n.data,...t}})}function It(e){iS(e);let t=new Map(R.value);if(t.delete(e),R.value=t,ke.value===e)ke.value=null;if(Be.value===e)Be.value=null;if(ye.value.has(e)){let n=new Set(ye.value);n.delete(e),ye.value=n}if(Ee.value.has(e)){let n=new Set(Ee.value);n.delete(e),Ee.value=n,ws(n)}}function Ss(e){let t=new Map(Re.value);t.set(e.id,e),Re.value=t}function Ef(e){let t=new Map(Re.value);t.delete(e),Re.value=t}function iS(e){let t=!1,n=new Map(Re.value);for(let[o,r]of n)if(r.from===e||r.to===e)n.delete(o),t=!0;if(t)Re.value=n}function sS(e){let t=new Map(Vo.value);if(!t.delete(e))return;Vo.value=t}async function il(e){return Ct("createAnnotationFromClient","/api/canvas/annotation",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function If(e){let t=await Ct("removeAnnotationFromClient",`/api/canvas/annotation/${encodeURIComponent(e)}`,{method:"DELETE"});if(t.ok)sS(e);return t}function ks(e,t){if(!R.value.get(e))return;et(e,{size:t})}function fn(e){let t=R.value.get(e);if(!t)return;$t(()=>{if(et(e,{zIndex:Hr++}),t.type==="group"&&Array.isArray(t.data.children)){for(let n of t.data.children)if(typeof n==="string"&&R.value.has(n))et(n,{zIndex:Hr++})}}),ke.value=e}function Ko(e){let t=R.value.get(e);if(!t)return;et(e,{collapsed:!t.collapsed}),nt()}function Af(e){re.value={...re.value,...e}}function zf(e){re.value=e}function Pf(e){Nf(e)}function Nf(e,t={}){re.value=e,nt(t),Up(e,t)}function Rf(e,t={}){let n=new Map,o=1;for(let p of e.nodes)if(n.set(p.id,p),p.zIndex>=o)o=p.zIndex+1;let r=e.edges.filter((p)=>n.has(p.from)&&n.has(p.to)),s=new Map;for(let p of r)s.set(p.id,p);let a=new Map;for(let p of e.annotations??[])a.set(p.id,p);let c=ke.value!==null&&n.has(ke.value)?ke.value:null,l=Be.value!==null&&n.has(Be.value)?Be.value:null,u=pf(ye.value,n),d=pf(Ee.value,n);$t(()=>{if(t.applyViewport===!0&&e.viewport)re.value=e.viewport;if(Hr=o,R.value=n,Re.value=s,Vo.value=a,ke.value=c,Be.value=l,!ff(ye.value,u))ye.value=u;if(!ff(Ee.value,d))Ee.value=d})}var Pn=null;function aS(e){return 1-(1-e)**3}function Jo(e,t=150){let n=re.value,o=Math.min(4,Math.max(0.1,n.scale*e));if(o===n.scale)return;let r=o/n.scale,{x:s,y:a}=Fo();$n({x:s-r*(s-n.x),y:a-r*(a-n.y),scale:o},t)}function $n(e,t=300,n={}){if(Pn!==null)cancelAnimationFrame(Pn);let o={...re.value},r=performance.now();function s(a){let c=a-r,l=Math.min(1,c/t),u=aS(l);if(re.value={x:o.x+(e.x-o.x)*u,y:o.y+(e.y-o.y)*u,scale:o.scale+(e.scale-o.scale)*u},l<1)Pn=requestAnimationFrame(s);else Pn=null,Nf(e,n)}Pn=requestAnimationFrame(s)}function Yo(){if(Pn!==null)cancelAnimationFrame(Pn),Pn=null}var $f="pmx-canvas-layout";function nt(e={}){try{let t=Array.from(R.value.values()),n=t.map((r)=>({id:r.id,position:r.position,size:r.size,collapsed:r.collapsed})),o={viewport:re.value,nodes:t.map((r)=>({id:r.id,type:r.type,position:r.position,size:r.size,collapsed:r.collapsed,pinned:r.pinned})),edges:Array.from(Re.value.values()).map((r)=>({id:r.id,from:r.from,to:r.to,type:r.type,label:r.label,style:r.style,animated:r.animated})),contextPinnedNodeIds:Array.from(Ee.value)};localStorage.setItem($f,JSON.stringify(o)),ss(n,e)}catch(t){hf("persistLayout",t)}}function sl(){try{let e=localStorage.getItem($f);if(!e)return null;let t=JSON.parse(e),n=Array.isArray(t.nodes)?t.nodes:[];if(n.length===0)return null;let o=new Map;for(let r of n){if(typeof r.id!=="string"||r.id.length===0)continue;o.set(r.id,{...r.position?{position:r.position}:{},...r.size?{size:r.size}:{},...r.collapsed!==void 0?{collapsed:r.collapsed}:{},...r.pinned!==void 0?{pinned:r.pinned}:{}})}return o.size>0?o:null}catch(e){return hf("restoreLayout",e),null}}function Qo(e,t){let n=Array.from(R.value.values());if(n.length===0)return;let{POSITIVE_INFINITY:o,POSITIVE_INFINITY:r,NEGATIVE_INFINITY:s,NEGATIVE_INFINITY:a}=Number;for(let y of n)o=Math.min(o,y.position.x),r=Math.min(r,y.position.y),s=Math.max(s,y.position.x+y.size.width),a=Math.max(a,y.position.y+y.size.height);let c=Dc(),l=Math.max(80,e-c.left-c.right),u=Math.max(80,t-c.top-c.bottom),d=Math.max(1,s-o),p=Math.max(1,a-r),m=Math.min(1,Math.min(l/d,u/p)),f=(o+s)/2,g=(r+a)/2;$n({x:c.left+l/2-f*m,y:c.top+u/2-g*m,scale:m})}function tt(e,t={}){let n=R.value.get(e);if(!n)return;let o=re.value,r=wt(),s=Dc(),a=Math.max(80,r.width-s.left-s.right),c=Math.max(80,r.height-s.top-s.bottom),l=Math.min(o.scale,a/n.size.width,c/n.size.height),u=n.position.x+n.size.width/2,d=n.position.y+n.size.height/2;$n({x:s.left+a/2-u*l,y:s.top+c/2-d*l,scale:l},300,t),fn(e)}function Mf(e=1){let t=Array.from(R.value.keys());if(t.length===0)return;let o=((ke.value?t.indexOf(ke.value):-1)+e+t.length)%t.length,r=t[o];fn(r),tt(r)}function Of(e){let t=ke.value;if(!t)return;let n=R.value.get(t);if(!n)return;let o=gf(t,Re.value);if(o.size===0)return;let r=n.position.x+n.size.width/2,s=n.position.y+n.size.height/2,a=null,c=-1/0;for(let l of o){let u=R.value.get(l);if(!u)continue;let d=u.position.x+u.size.width/2,p=u.position.y+u.size.height/2,m=d-r,f=p-s,g=Math.sqrt(m*m+f*f);if(g<1)continue;let y;switch(e){case"up":y=-f;break;case"down":y=f;break;case"left":y=-m;break;case"right":y=m;break}if(y<=0)continue;let x=y/g-g*0.001;if(x>c)c=x,a=l}if(a)tt(a)}function en(e){if(!R.value.get(e))return;if(Tt!==null)clearTimeout(Tt),Tt=null;Qt.value=null,qo=void 0,fn(e),Be.value=e}function Qc(e){if(Tt!==null)clearTimeout(Tt),Tt=null;if(Be.value===e)Be.value=null;if(Qt.value===e)Qt.value=null;qo=void 0}function po(){let e=Be.value,t=e?R.value.get(e):void 0;if(e&&t&&Kp(t)){let n=e,o=Date.now();if(Qt.value=n,qo=t.data.appCheckpoint?.updatedAt,Tt!==null)clearTimeout(Tt);let r=()=>{let a=R.value.get(n)?.data.appCheckpoint?.updatedAt;if(a!==void 0&&a!==qo){Qc(n);return}if(Date.now()-o>=oS){Qc(n);return}Tt=setTimeout(r,df)};Tt=setTimeout(r,df);return}if(Tt!==null)clearTimeout(Tt),Tt=null;Qt.value=null,qo=void 0,Be.value=null}function Cs(){let e=Jc(Array.from(R.value.values()),Array.from(Re.value.values()),"grid");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;$t(()=>{for(let[t,n]of e.nodePositions.entries())et(t,{position:n});for(let[t,n]of e.groupBounds.entries())_s(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),nt()}function Ts(){let e=Jc(Array.from(R.value.values()),Array.from(Re.value.values()),"graph");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;$t(()=>{for(let[t,n]of e.nodePositions.entries())et(t,{position:n});for(let[t,n]of e.groupBounds.entries())_s(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),nt()}var Lf="pmx-canvas-iframe-probe";var cS="/api/canvas/iframe-probe",lS=3000,gt=V(null);function uS(){let e=new URLSearchParams(window.location.search).get("iframe-mode");return e==="srcdoc"||e==="src"?e:null}function Df(e=lS){return new Promise((t)=>{let n=document.createElement("iframe");n.setAttribute("data-pmx-iframe-probe",""),n.style.cssText="position:fixed;width:1px;height:1px;left:-9999px;border:none",n.setAttribute("sandbox","allow-scripts");let o=(a)=>{window.clearTimeout(s),window.removeEventListener("message",r),n.remove(),t(a)},r=(a)=>{if(a.source!==n.contentWindow)return;if(a.data?.source!==Lf)return;o(!0)},s=window.setTimeout(()=>o(!1),e);window.addEventListener("message",r),n.addEventListener("error",()=>o(!1)),n.src=cS,(document.body??document.documentElement).appendChild(n)})}var Es=null;function dS(){try{return window.self!==window.top}catch{return!0}}function pS(){return window.__PMX_AMP_ORB===!0}function Ff(e={}){if(gt.value)return Promise.resolve(gt.value);if(Es)return Es;let t=uS();if(t)return gt.value=t,Promise.resolve(t);if(!(e.embedded??dS()))return gt.value="src",Df(e.probeTimeoutMs).then((n)=>{if(!n&&gt.value==="src")gt.value="srcdoc"}),Promise.resolve("src");if(e.ampOrb??pS())return gt.value="srcdoc",Promise.resolve("srcdoc");return Es=Df(e.probeTimeoutMs).then((n)=>{let o=n?"src":"srcdoc";return gt.value=o,o}),Es}function fS(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",py:"Python",rs:"Rust",go:"Go",rb:"Ruby",java:"Java",kt:"Kotlin",swift:"Swift",c:"C",cpp:"C++",h:"C/C++",css:"CSS",html:"HTML",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",toml:"TOML",sql:"SQL",sh:"Shell",bash:"Shell",xml:"XML",graphql:"GraphQL",proto:"Protobuf"}[t]??(t.toUpperCase()||"Text")}var al=500;function mS(e){let t=e.toLowerCase();if(t.endsWith(".csv"))return",";if(t.endsWith(".tsv"))return"\t";return null}function hS(e,t){let n=[],o=[],r="",s=!1,a=!1;for(let l=0;l<e.length;l++){let u=e[l];if(a=!0,s){if(u==='"')if(e[l+1]==='"')r+='"',l++;else s=!1;else if(u==="\r"&&e[l+1]===`
37
37
  `)r+=`
38
38
  `,l++;else r+=u;continue}if(u==='"'&&r==="")s=!0;else if(u===t)o.push(r),r="";else if(u===`
39
39
  `||u==="\r"){if(u==="\r"&&e[l+1]===`
40
- `)l++;o.push(r),r="",n.push(o),o=[],a=!1}else r+=u}if(a)o.push(r),n.push(o);let c=n.shift()??[];return{header:c,rows:n.map((l)=>Array.from({length:c.length},(u,d)=>l[d]??""))}}function il(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.round(e)} B`;let t=["KB","MB","GB","TB"],n=e/1024,o=0;while(n>=1024&&o<t.length-1)n/=1024,o++;return`${n<10?n.toFixed(1):Math.round(n)} ${t[o]}`}function Cs({node:e,expanded:t=!1}){let n=e.data.path||e.data.content||"",o=e.data.title||n.split("/").pop()||"File",r=e.data.fileContent,s=e.data.updatedAt,a=e.data.lineCount,c=e.data.byteSize,l=e.data.binary===!0,u=e.data.truncated===!0,p=e.data.mimeType==="application/pdf"||n.toLowerCase().endsWith(".pdf"),m=l||p,[f,g]=L(r??""),[y,x]=L(!r&&!!n&&!m),[h,v]=L(null),[b,z]=L(0);D(()=>{if(!n)return;if(m){x(!1);return}if(r!==void 0){g(r),x(!1);return}let H=!1;return x(!0),v(null),Or(n).then(({content:U})=>{if(H)return;if(!U&&U!==""){v("File not found"),x(!1);return}g(U),x(!1);let ee=U.split(`
41
- `).length;oe(e.id,{fileContent:U,lineCount:ee}),rt(e.id,{data:{fileContent:U,lineCount:ee}})}).catch(()=>{if(!H)v("Failed to load file"),x(!1)}),()=>{H=!0}},[n,r,m]),D(()=>{if(r!==void 0&&r!==f)g(r)},[r]);let F=O(()=>{if(!n)return;if(m){z((H)=>H+1);return}x(!0),v(null),oe(e.id,{fileContent:void 0}),rt(e.id,{data:{fileContent:void 0}}),Or(n).then(({content:H})=>{g(H),x(!1);let U=H.split(`
42
- `).length,ee=new Date().toISOString();oe(e.id,{fileContent:H,lineCount:U,updatedAt:ee}),rt(e.id,{data:{fileContent:H,lineCount:U,updatedAt:ee}})}).catch(()=>{v("Failed to reload"),x(!1)})},[n,e.id,m]),_=dS(n),k=f.split(`
43
- `),T=`${String(k.length).length+1}ch`,P=pS(n),Z=Ae(()=>{if(!P||m||!f)return null;let H=fS(f,P);return H.header.length>=2?H:null},[f,P,m]),j=`/api/canvas/file-bytes?nodeId=${encodeURIComponent(e.id)}${b?`&v=${b}`:""}`,E=gt.value==="srcdoc",B=m||Z!==null,W=u?i("div",{class:"file-node-notice",children:["Showing the first ",il(f.length)," of ",il(c??f.length)]},void 0,!0,void 0,this):null;if(!n)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No file path set"},void 0,!1,void 0,this);return i("div",{style:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"var(--mono)",fontSize:t?"13px":"11px"},children:[i("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 10px",borderBottom:"1px solid var(--c-line)",flexShrink:0},children:[i("span",{style:{fontSize:"9px",padding:"1px 5px",background:"var(--c-accent-12)",color:"var(--c-accent)",borderRadius:"3px",fontWeight:600},children:_},void 0,!1,void 0,this),i("span",{style:{color:"var(--c-text-soft)",fontSize:t?"12px":"10px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:n,children:n},void 0,!1,void 0,this),a!==void 0&&i("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:[a," lines"]},void 0,!0,void 0,this),s&&i("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:new Date(s).toLocaleTimeString()},void 0,!1,void 0,this),i("button",{type:"button",class:"ax-node-action",title:"Mark this file as AX evidence",onClick:(H)=>{H.stopPropagation(),zn(e,"ax.evidence.add",{kind:"file",title:n.split("/").pop()||n,ref:n},"Marked as evidence")},style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:"⊕"},void 0,!1,void 0,this),i("button",{type:"button",onClick:F,title:"Reload file",style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:"↻"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{flex:1,minHeight:0,overflow:B?"hidden":"auto",padding:B?0:"8px 0",background:t?"var(--c-panel-soft)":void 0,borderRadius:t?"0 0 8px 8px":void 0},children:[p&&(E?i("div",{class:"file-node-placeholder",children:[i("div",{children:"PDF preview is unavailable in this embedded host."},void 0,!1,void 0,this),i("a",{class:"file-node-link",href:j,target:"_blank",rel:"noreferrer",children:"Open PDF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i("iframe",{src:j,title:o,sandbox:"",style:{width:"100%",height:"100%",border:"none",display:"block"}},void 0,!1,void 0,this)),!p&&l&&i("div",{class:"file-node-placeholder",children:[i("div",{class:"file-node-placeholder-name",children:o},void 0,!1,void 0,this),i("div",{children:"Binary file"},void 0,!1,void 0,this),c!==void 0&&i("div",{children:il(c)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!m&&i(ve,{children:[y&&i("div",{style:{color:"var(--c-dim)",padding:"12px",fontStyle:"italic"},children:"Loading…"},void 0,!1,void 0,this),h&&i("div",{style:{color:"var(--c-danger)",padding:"12px"},children:h},void 0,!1,void 0,this),!y&&!h&&(Z?i("div",{class:"file-table-shell",children:[W,Z.rows.length>rl&&i("div",{class:"file-node-notice",children:["Showing ",rl," of ",Z.rows.length," rows"]},void 0,!0,void 0,this),i("div",{class:"file-table-wrap",children:i("table",{class:"file-table",children:[i("thead",{children:i("tr",{children:Z.header.map((H,U)=>i("th",{children:H},U,!1,void 0,this))},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("tbody",{children:Z.rows.slice(0,rl).map((H,U)=>i("tr",{children:H.map((ee,xe)=>i("td",{children:ee},xe,!1,void 0,this))},U,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(ve,{children:[W,i("pre",{style:{margin:0,lineHeight:"1.55",tabSize:2},children:k.map((H,U)=>i("div",{style:{display:"flex",minHeight:"1.55em"},children:[i("span",{style:{width:T,minWidth:T,textAlign:"right",color:"var(--c-dim)",paddingRight:"12px",paddingLeft:"10px",userSelect:"none",flexShrink:0,opacity:0.6},children:U+1},void 0,!1,void 0,this),i("code",{style:{color:"var(--c-text)",whiteSpace:"pre",paddingRight:"10px"},children:H||`
44
- `},void 0,!1,void 0,this)]},U,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var mS=new Set(["title","__type","content","strictSize","arrangeLocked"]);function Ts({node:e}){let t=e.data,o=(typeof t.content==="string"?t.content:"").split(/\r\n|\r|\n|\\n/).map((s)=>s.trimEnd()).filter((s)=>s.length>0),r=Object.entries(t).filter(([s])=>!mS.has(s));if(o.length===0&&r.length===0)return i("div",{style:{color:"var(--c-dim)",fontSize:"12px",fontStyle:"italic"},children:"No ledger data"},void 0,!1,void 0,this);return i("div",{style:{display:"flex",flexDirection:"column",gap:"4px",fontSize:"12px"},children:[o.length>0&&i("div",{style:{display:"flex",flexDirection:"column"},children:o.map((s,a)=>i("div",{style:{padding:"3px 0",borderBottom:a<o.length-1?"1px solid rgba(45,55,90,0.3)":"none",color:"var(--c-text)",fontFamily:"var(--mono)",fontSize:"11px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s},a,!1,void 0,this))},void 0,!1,void 0,this),r.map(([s,a])=>i("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px",padding:"3px 0",borderBottom:"1px solid rgba(45,55,90,0.3)"},children:[i("span",{style:{color:"var(--c-muted)",fontSize:"11px",flexShrink:0},children:s.replace(/([A-Z])/g," $1").replace(/^./,(c)=>c.toUpperCase())},void 0,!1,void 0,this),i("span",{style:{color:"var(--c-text)",fontFamily:"var(--mono)",fontSize:"11px",textAlign:"right",wordBreak:"break-word"},children:typeof a==="object"?JSON.stringify(a):String(a??"—")},void 0,!1,void 0,this)]},s,!0,void 0,this))]},void 0,!0,void 0,this)}var Ur=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),Ff=Ur?"⌘":"Ctrl";function Ze(e){return Ur?`${Ff}${e}`:`${Ff}+${e}`}function Es(e,t){let{selectionStart:n,selectionEnd:o,value:r}=e,s=r.slice(n,o),a=r.slice(Math.max(0,n-t.length),n),c=r.slice(o,o+t.length);if(a===t&&c===t){let l=r.slice(0,n-t.length)+s+r.slice(o+t.length);tn(e,l,n-t.length,o-t.length);return}if(s){let l=r.slice(0,n)+t+s+t+r.slice(o);tn(e,l,n+t.length,o+t.length)}else{let l=r.slice(0,n)+t+t+r.slice(o);tn(e,l,n+t.length,n+t.length)}}function Wr(e,t){let{selectionStart:n,selectionEnd:o,value:r}=e,s=r.lastIndexOf(`
40
+ `)l++;o.push(r),r="",n.push(o),o=[],a=!1}else r+=u}if(a)o.push(r),n.push(o);let c=n.shift()??[];return{header:c,rows:n.map((l)=>Array.from({length:c.length},(u,d)=>l[d]??""))}}function cl(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.round(e)} B`;let t=["KB","MB","GB","TB"],n=e/1024,o=0;while(n>=1024&&o<t.length-1)n/=1024,o++;return`${n<10?n.toFixed(1):Math.round(n)} ${t[o]}`}function Is({node:e,expanded:t=!1}){let n=e.data.path||e.data.content||"",o=e.data.title||n.split("/").pop()||"File",r=e.data.fileContent,s=e.data.updatedAt,a=e.data.lineCount,c=e.data.byteSize,l=e.data.binary===!0,u=e.data.truncated===!0,p=e.data.mimeType==="application/pdf"||n.toLowerCase().endsWith(".pdf"),m=l||p,[f,g]=L(r??""),[y,x]=L(!r&&!!n&&!m),[h,v]=L(null),[b,z]=L(0);D(()=>{if(!n)return;if(m){x(!1);return}if(r!==void 0){g(r),x(!1);return}let H=!1;return x(!0),v(null),Or(n).then(({content:U})=>{if(H)return;if(!U&&U!==""){v("File not found"),x(!1);return}g(U),x(!1);let ee=U.split(`
41
+ `).length;oe(e.id,{fileContent:U,lineCount:ee}),it(e.id,{data:{fileContent:U,lineCount:ee}})}).catch(()=>{if(!H)v("Failed to load file"),x(!1)}),()=>{H=!0}},[n,r,m]),D(()=>{if(r!==void 0&&r!==f)g(r)},[r]);let F=O(()=>{if(!n)return;if(m){z((H)=>H+1);return}x(!0),v(null),oe(e.id,{fileContent:void 0}),it(e.id,{data:{fileContent:void 0}}),Or(n).then(({content:H})=>{g(H),x(!1);let U=H.split(`
42
+ `).length,ee=new Date().toISOString();oe(e.id,{fileContent:H,lineCount:U,updatedAt:ee}),it(e.id,{data:{fileContent:H,lineCount:U,updatedAt:ee}})}).catch(()=>{v("Failed to reload"),x(!1)})},[n,e.id,m]),_=fS(n),k=f.split(`
43
+ `),T=`${String(k.length).length+1}ch`,P=mS(n),Z=Ae(()=>{if(!P||m||!f)return null;let H=hS(f,P);return H.header.length>=2?H:null},[f,P,m]),j=`/api/canvas/file-bytes?nodeId=${encodeURIComponent(e.id)}${b?`&v=${b}`:""}`,E=gt.value==="srcdoc",B=m||Z!==null,W=u?i("div",{class:"file-node-notice",children:["Showing the first ",cl(f.length)," of ",cl(c??f.length)]},void 0,!0,void 0,this):null;if(!n)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No file path set"},void 0,!1,void 0,this);return i("div",{style:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"var(--mono)",fontSize:t?"13px":"11px"},children:[i("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 10px",borderBottom:"1px solid var(--c-line)",flexShrink:0},children:[i("span",{style:{fontSize:"9px",padding:"1px 5px",background:"var(--c-accent-12)",color:"var(--c-accent)",borderRadius:"3px",fontWeight:600},children:_},void 0,!1,void 0,this),i("span",{style:{color:"var(--c-text-soft)",fontSize:t?"12px":"10px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:n,children:n},void 0,!1,void 0,this),a!==void 0&&i("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:[a," lines"]},void 0,!0,void 0,this),s&&i("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:new Date(s).toLocaleTimeString()},void 0,!1,void 0,this),i("button",{type:"button",class:"ax-node-action",title:"Mark this file as AX evidence",onClick:(H)=>{H.stopPropagation(),zn(e,"ax.evidence.add",{kind:"file",title:n.split("/").pop()||n,ref:n},"Marked as evidence")},style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:"⊕"},void 0,!1,void 0,this),i("button",{type:"button",onClick:F,title:"Reload file",style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:"↻"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{flex:1,minHeight:0,overflow:B?"hidden":"auto",padding:B?0:"8px 0",background:t?"var(--c-panel-soft)":void 0,borderRadius:t?"0 0 8px 8px":void 0},children:[p&&(E?i("div",{class:"file-node-placeholder",children:[i("div",{children:"PDF preview is unavailable in this embedded host."},void 0,!1,void 0,this),i("a",{class:"file-node-link",href:j,target:"_blank",rel:"noreferrer",children:"Open PDF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i("iframe",{src:j,title:o,sandbox:"",style:{width:"100%",height:"100%",border:"none",display:"block"}},void 0,!1,void 0,this)),!p&&l&&i("div",{class:"file-node-placeholder",children:[i("div",{class:"file-node-placeholder-name",children:o},void 0,!1,void 0,this),i("div",{children:"Binary file"},void 0,!1,void 0,this),c!==void 0&&i("div",{children:cl(c)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!m&&i(ve,{children:[y&&i("div",{style:{color:"var(--c-dim)",padding:"12px",fontStyle:"italic"},children:"Loading…"},void 0,!1,void 0,this),h&&i("div",{style:{color:"var(--c-danger)",padding:"12px"},children:h},void 0,!1,void 0,this),!y&&!h&&(Z?i("div",{class:"file-table-shell",children:[W,Z.rows.length>al&&i("div",{class:"file-node-notice",children:["Showing ",al," of ",Z.rows.length," rows"]},void 0,!0,void 0,this),i("div",{class:"file-table-wrap",children:i("table",{class:"file-table",children:[i("thead",{children:i("tr",{children:Z.header.map((H,U)=>i("th",{children:H},U,!1,void 0,this))},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("tbody",{children:Z.rows.slice(0,al).map((H,U)=>i("tr",{children:H.map((ee,xe)=>i("td",{children:ee},xe,!1,void 0,this))},U,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(ve,{children:[W,i("pre",{style:{margin:0,lineHeight:"1.55",tabSize:2},children:k.map((H,U)=>i("div",{style:{display:"flex",minHeight:"1.55em"},children:[i("span",{style:{width:T,minWidth:T,textAlign:"right",color:"var(--c-dim)",paddingRight:"12px",paddingLeft:"10px",userSelect:"none",flexShrink:0,opacity:0.6},children:U+1},void 0,!1,void 0,this),i("code",{style:{color:"var(--c-text)",whiteSpace:"pre",paddingRight:"10px"},children:H||`
44
+ `},void 0,!1,void 0,this)]},U,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var gS=new Set(["title","__type","content","strictSize","arrangeLocked"]);function As({node:e}){let t=e.data,o=(typeof t.content==="string"?t.content:"").split(/\r\n|\r|\n|\\n/).map((s)=>s.trimEnd()).filter((s)=>s.length>0),r=Object.entries(t).filter(([s])=>!gS.has(s));if(o.length===0&&r.length===0)return i("div",{style:{color:"var(--c-dim)",fontSize:"12px",fontStyle:"italic"},children:"No ledger data"},void 0,!1,void 0,this);return i("div",{style:{display:"flex",flexDirection:"column",gap:"4px",fontSize:"12px"},children:[o.length>0&&i("div",{style:{display:"flex",flexDirection:"column"},children:o.map((s,a)=>i("div",{style:{padding:"3px 0",borderBottom:a<o.length-1?"1px solid rgba(45,55,90,0.3)":"none",color:"var(--c-text)",fontFamily:"var(--mono)",fontSize:"11px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s},a,!1,void 0,this))},void 0,!1,void 0,this),r.map(([s,a])=>i("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px",padding:"3px 0",borderBottom:"1px solid rgba(45,55,90,0.3)"},children:[i("span",{style:{color:"var(--c-muted)",fontSize:"11px",flexShrink:0},children:s.replace(/([A-Z])/g," $1").replace(/^./,(c)=>c.toUpperCase())},void 0,!1,void 0,this),i("span",{style:{color:"var(--c-text)",fontFamily:"var(--mono)",fontSize:"11px",textAlign:"right",wordBreak:"break-word"},children:typeof a==="object"?JSON.stringify(a):String(a??"—")},void 0,!1,void 0,this)]},s,!0,void 0,this))]},void 0,!0,void 0,this)}var Ur=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),jf=Ur?"⌘":"Ctrl";function Ze(e){return Ur?`${jf}${e}`:`${jf}+${e}`}function zs(e,t){let{selectionStart:n,selectionEnd:o,value:r}=e,s=r.slice(n,o),a=r.slice(Math.max(0,n-t.length),n),c=r.slice(o,o+t.length);if(a===t&&c===t){let l=r.slice(0,n-t.length)+s+r.slice(o+t.length);tn(e,l,n-t.length,o-t.length);return}if(s){let l=r.slice(0,n)+t+s+t+r.slice(o);tn(e,l,n+t.length,o+t.length)}else{let l=r.slice(0,n)+t+t+r.slice(o);tn(e,l,n+t.length,n+t.length)}}function Wr(e,t){let{selectionStart:n,selectionEnd:o,value:r}=e,s=r.lastIndexOf(`
45
45
  `,n-1)+1,a=r.indexOf(`
46
- `,o),c=a===-1?r.length:a,l=r.slice(s,c);if(l.startsWith(t)){let d=r.slice(0,s)+l.slice(t.length)+r.slice(c);tn(e,d,Math.max(s,n-t.length),Math.max(s,o-t.length));return}let u=r.slice(0,s)+t+r.slice(s);tn(e,u,n+t.length,o+t.length)}function hS(e){let{selectionStart:t,selectionEnd:n,value:o}=e,r=o.slice(t,n);if(r){let s=o.slice(0,t)+`[${r}](url)`+o.slice(n),a=t+r.length+3;tn(e,s,a,a+3)}else{let s=o.slice(0,t)+"[text](url)"+o.slice(n);tn(e,s,t+1,t+5)}}function gS(e){let{selectionStart:t,selectionEnd:n,value:o}=e,r=o.slice(t,n),s="```";if(r){let a=o.slice(0,t)+`\`\`\`
46
+ `,o),c=a===-1?r.length:a,l=r.slice(s,c);if(l.startsWith(t)){let d=r.slice(0,s)+l.slice(t.length)+r.slice(c);tn(e,d,Math.max(s,n-t.length),Math.max(s,o-t.length));return}let u=r.slice(0,s)+t+r.slice(s);tn(e,u,n+t.length,o+t.length)}function vS(e){let{selectionStart:t,selectionEnd:n,value:o}=e,r=o.slice(t,n);if(r){let s=o.slice(0,t)+`[${r}](url)`+o.slice(n),a=t+r.length+3;tn(e,s,a,a+3)}else{let s=o.slice(0,t)+"[text](url)"+o.slice(n);tn(e,s,t+1,t+5)}}function yS(e){let{selectionStart:t,selectionEnd:n,value:o}=e,r=o.slice(t,n),s="```";if(r){let a=o.slice(0,t)+`\`\`\`
47
47
  ${r}
48
- \`\`\``+o.slice(n);tn(e,a,t+3+1,t+3+1+r.length)}else{let a=o.slice(0,t)+"```\n\n```"+o.slice(n);tn(e,a,t+3+1,t+3+1)}}function jf(e,t){let{selectionStart:n,selectionEnd:o,value:r}=e,s=r.lastIndexOf(`
48
+ \`\`\``+o.slice(n);tn(e,a,t+3+1,t+3+1+r.length)}else{let a=o.slice(0,t)+"```\n\n```"+o.slice(n);tn(e,a,t+3+1,t+3+1)}}function Zf(e,t){let{selectionStart:n,selectionEnd:o,value:r}=e,s=r.lastIndexOf(`
49
49
  `,n-1)+1,a=r.indexOf(`
50
50
  `,o),c=a===-1?r.length:a,l=r.slice(s,c).split(`
51
51
  `),u=n,d=o,p=l.map((f,g)=>{if(t){if(f.startsWith(" ")){if(g===0)u=Math.max(s,u-2);return d-=2,f.slice(2)}else if(f.startsWith("\t")){if(g===0)u=Math.max(s,u-1);return d-=1,f.slice(1)}return f}else{if(g===0)u+=2;return d+=2," "+f}}),m=r.slice(0,s)+p.join(`
52
- `)+r.slice(c);tn(e,m,u,d)}function tn(e,t,n,o){let r=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;if(r)r.call(e,t);else e.value=t;e.selectionStart=n,e.selectionEnd=o,e.dispatchEvent(new Event("input",{bubbles:!0}))}var Is=[{key:"bold",label:"Bold",icon:"B",shortcut:"b",action:(e)=>Es(e,"**")},{key:"italic",label:"Italic",icon:"I",shortcut:"i",action:(e)=>Es(e,"_")},{key:"strike",label:"Strikethrough",icon:"S",shortcut:"u",action:(e)=>Es(e,"~~")},{key:"code",label:"Inline code",icon:"`",shortcut:"e",action:(e)=>Es(e,"`")},{key:"link",label:"Link",icon:"\uD83D\uDD17",shortcut:"k",action:hS},{key:"h1",label:"Heading 1",icon:"H1",action:(e)=>Wr(e,"# ")},{key:"h2",label:"Heading 2",icon:"H2",action:(e)=>Wr(e,"## ")},{key:"quote",label:"Blockquote",icon:"❝",action:(e)=>Wr(e,"> ")},{key:"ul",label:"Bullet list",icon:"•",action:(e)=>Wr(e,"- ")},{key:"ol",label:"Numbered list",icon:"1.",action:(e)=>Wr(e,"1. ")},{key:"codeblock",label:"Code block",icon:"{ }",action:gS}];function Zf(e,t){if(!(e.metaKey||e.ctrlKey))return!1;let n=Is.find((o)=>o.shortcut===e.key);if(!n)return!1;return e.preventDefault(),n.action(t),!0}function Hf(e){if(e.selectionStart===e.selectionEnd)return null;let t=document.createElement("div"),n=getComputedStyle(e),o=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","wordSpacing","textIndent","whiteSpace","wordWrap","overflowWrap","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","width"];for(let d of o)t.style[d]=n[d];t.style.position="absolute",t.style.visibility="hidden",t.style.overflow="hidden",t.style.height="auto",t.style.top="0",t.style.left="0";let r=e.value,s=document.createTextNode(r.slice(0,e.selectionStart)),a=document.createElement("span");a.textContent=r.slice(e.selectionStart,e.selectionEnd)||".",t.appendChild(s),t.appendChild(a),t.appendChild(document.createTextNode(r.slice(e.selectionEnd))),document.body.appendChild(t);let c=a.getBoundingClientRect(),l=t.getBoundingClientRect(),u=e.getBoundingClientRect();return document.body.removeChild(t),{top:u.top+(c.top-l.top)-e.scrollTop,left:u.left+(c.left-l.left)-e.scrollLeft,width:c.width}}var vS=Is.filter((e)=>e.shortcut),yS=Is.filter((e)=>!e.shortcut);function sl({textareaRef:e}){let[t,n]=L(!1),[o,r]=L({top:0,left:0}),s=R(null),a=R(null),c=O(()=>{let u=e.current;if(!u||u.selectionStart===u.selectionEnd){n(!1);return}let d=Hf(u);if(!d){n(!1);return}let p=380,m=Math.max(8,Math.min(d.left+d.width/2-p/2,window.innerWidth-p-8));r({top:d.top-40,left:m}),n(!0)},[e]);D(()=>{let u=e.current;if(!u)return;let d=()=>{if(a.current)clearTimeout(a.current);a.current=setTimeout(c,50)},p=()=>{a.current=setTimeout(()=>n(!1),200)},m=(f)=>{if(f.shiftKey||f.key.startsWith("Arrow"))d()};return u.addEventListener("select",d),u.addEventListener("mouseup",d),u.addEventListener("keyup",m),u.addEventListener("blur",p),()=>{if(u.removeEventListener("select",d),u.removeEventListener("mouseup",d),u.removeEventListener("keyup",m),u.removeEventListener("blur",p),a.current)clearTimeout(a.current)}},[e,c]);let l=O((u)=>{let d=e.current;if(d)u.action(d),d.focus()},[e]);if(!t)return null;return i("div",{ref:s,class:"md-format-bar",style:{top:`${o.top}px`,left:`${o.left}px`},onMouseDown:(u)=>u.preventDefault(),children:[vS.map((u)=>i("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,title:`${u.label} (${Ze(u.shortcut.toUpperCase())})`,onClick:()=>l(u),children:u.icon},u.key,!1,void 0,this)),i("div",{class:"md-format-divider"},void 0,!1,void 0,this),yS.map((u)=>i("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,title:u.label,onClick:()=>l(u),children:u.icon},u.key,!1,void 0,this))]},void 0,!0,void 0,this)}var bm=Hw(rm(),1);function $S(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o))e[o]=n[o]}return e}function fl(e,t){return Array(t+1).join(e)}function am(e){return e.replace(/^\n*/,"")}function cm(e){var t=e.length;while(t>0&&e[t-1]===`
53
- `)t--;return e.substring(0,t)}function lm(e){return cm(am(e))}var MS=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function ml(e){return hl(e,MS)}var um=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function dm(e){return hl(e,um)}function OS(e){return fm(e,um)}var pm=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function LS(e){return hl(e,pm)}function DS(e){return fm(e,pm)}function hl(e,t){return t.indexOf(e.nodeName)>=0}function fm(e,t){return e.getElementsByTagName&&t.some(function(n){return e.getElementsByTagName(n).length})}var FS=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function mm(e){return FS.reduce(function(t,n){return t.replace(n[0],n[1])},e)}var vt={};vt.paragraph={filter:"p",replacement:function(e){return`
52
+ `)+r.slice(c);tn(e,m,u,d)}function tn(e,t,n,o){let r=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;if(r)r.call(e,t);else e.value=t;e.selectionStart=n,e.selectionEnd=o,e.dispatchEvent(new Event("input",{bubbles:!0}))}var Ps=[{key:"bold",label:"Bold",icon:"B",shortcut:"b",action:(e)=>zs(e,"**")},{key:"italic",label:"Italic",icon:"I",shortcut:"i",action:(e)=>zs(e,"_")},{key:"strike",label:"Strikethrough",icon:"S",shortcut:"u",action:(e)=>zs(e,"~~")},{key:"code",label:"Inline code",icon:"`",shortcut:"e",action:(e)=>zs(e,"`")},{key:"link",label:"Link",icon:"\uD83D\uDD17",shortcut:"k",action:vS},{key:"h1",label:"Heading 1",icon:"H1",action:(e)=>Wr(e,"# ")},{key:"h2",label:"Heading 2",icon:"H2",action:(e)=>Wr(e,"## ")},{key:"quote",label:"Blockquote",icon:"❝",action:(e)=>Wr(e,"> ")},{key:"ul",label:"Bullet list",icon:"•",action:(e)=>Wr(e,"- ")},{key:"ol",label:"Numbered list",icon:"1.",action:(e)=>Wr(e,"1. ")},{key:"codeblock",label:"Code block",icon:"{ }",action:yS}];function Hf(e,t){if(!(e.metaKey||e.ctrlKey))return!1;let n=Ps.find((o)=>o.shortcut===e.key);if(!n)return!1;return e.preventDefault(),n.action(t),!0}function Bf(e){if(e.selectionStart===e.selectionEnd)return null;let t=document.createElement("div"),n=getComputedStyle(e),o=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","wordSpacing","textIndent","whiteSpace","wordWrap","overflowWrap","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","width"];for(let d of o)t.style[d]=n[d];t.style.position="absolute",t.style.visibility="hidden",t.style.overflow="hidden",t.style.height="auto",t.style.top="0",t.style.left="0";let r=e.value,s=document.createTextNode(r.slice(0,e.selectionStart)),a=document.createElement("span");a.textContent=r.slice(e.selectionStart,e.selectionEnd)||".",t.appendChild(s),t.appendChild(a),t.appendChild(document.createTextNode(r.slice(e.selectionEnd))),document.body.appendChild(t);let c=a.getBoundingClientRect(),l=t.getBoundingClientRect(),u=e.getBoundingClientRect();return document.body.removeChild(t),{top:u.top+(c.top-l.top)-e.scrollTop,left:u.left+(c.left-l.left)-e.scrollLeft,width:c.width}}var xS=Ps.filter((e)=>e.shortcut),bS=Ps.filter((e)=>!e.shortcut);function ll({textareaRef:e}){let[t,n]=L(!1),[o,r]=L({top:0,left:0}),s=M(null),a=M(null),c=O(()=>{let u=e.current;if(!u||u.selectionStart===u.selectionEnd){n(!1);return}let d=Bf(u);if(!d){n(!1);return}let p=380,m=Math.max(8,Math.min(d.left+d.width/2-p/2,window.innerWidth-p-8));r({top:d.top-40,left:m}),n(!0)},[e]);D(()=>{let u=e.current;if(!u)return;let d=()=>{if(a.current)clearTimeout(a.current);a.current=setTimeout(c,50)},p=()=>{a.current=setTimeout(()=>n(!1),200)},m=(f)=>{if(f.shiftKey||f.key.startsWith("Arrow"))d()};return u.addEventListener("select",d),u.addEventListener("mouseup",d),u.addEventListener("keyup",m),u.addEventListener("blur",p),()=>{if(u.removeEventListener("select",d),u.removeEventListener("mouseup",d),u.removeEventListener("keyup",m),u.removeEventListener("blur",p),a.current)clearTimeout(a.current)}},[e,c]);let l=O((u)=>{let d=e.current;if(d)u.action(d),d.focus()},[e]);if(!t)return null;return i("div",{ref:s,class:"md-format-bar",style:{top:`${o.top}px`,left:`${o.left}px`},onMouseDown:(u)=>u.preventDefault(),children:[xS.map((u)=>i("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,title:`${u.label} (${Ze(u.shortcut.toUpperCase())})`,onClick:()=>l(u),children:u.icon},u.key,!1,void 0,this)),i("div",{class:"md-format-divider"},void 0,!1,void 0,this),bS.map((u)=>i("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,title:u.label,onClick:()=>l(u),children:u.icon},u.key,!1,void 0,this))]},void 0,!0,void 0,this)}var wm=Uw(im(),1);function OS(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o))e[o]=n[o]}return e}function gl(e,t){return Array(t+1).join(e)}function cm(e){return e.replace(/^\n*/,"")}function lm(e){var t=e.length;while(t>0&&e[t-1]===`
53
+ `)t--;return e.substring(0,t)}function um(e){return lm(cm(e))}var LS=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function vl(e){return yl(e,LS)}var dm=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function pm(e){return yl(e,dm)}function DS(e){return mm(e,dm)}var fm=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function FS(e){return yl(e,fm)}function jS(e){return mm(e,fm)}function yl(e,t){return t.indexOf(e.nodeName)>=0}function mm(e,t){return e.getElementsByTagName&&t.some(function(n){return e.getElementsByTagName(n).length})}var ZS=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function hm(e){return ZS.reduce(function(t,n){return t.replace(n[0],n[1])},e)}var vt={};vt.paragraph={filter:"p",replacement:function(e){return`
54
54
 
55
55
  `+e+`
56
56
 
57
57
  `}};vt.lineBreak={filter:"br",replacement:function(e,t,n){return n.br+`
58
- `}};vt.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(e,t,n){var o=Number(t.nodeName.charAt(1));if(n.headingStyle==="setext"&&o<3){var r=fl(o===1?"=":"-",e.length);return`
58
+ `}};vt.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(e,t,n){var o=Number(t.nodeName.charAt(1));if(n.headingStyle==="setext"&&o<3){var r=gl(o===1?"=":"-",e.length);return`
59
59
 
60
60
  `+e+`
61
61
  `+r+`
62
62
 
63
63
  `}else return`
64
64
 
65
- `+fl("#",o)+" "+e+`
65
+ `+gl("#",o)+" "+e+`
66
66
 
67
- `}};vt.blockquote={filter:"blockquote",replacement:function(e){return e=lm(e).replace(/^/gm,"> "),`
67
+ `}};vt.blockquote={filter:"blockquote",replacement:function(e){return e=um(e).replace(/^/gm,"> "),`
68
68
 
69
69
  `+e+`
70
70
 
@@ -73,7 +73,7 @@ ${r}
73
73
 
74
74
  `+e+`
75
75
 
76
- `}};vt.listItem={filter:"li",replacement:function(e,t,n){var o=n.bulletListMarker+" ",r=t.parentNode;if(r.nodeName==="OL"){var s=r.getAttribute("start"),a=Array.prototype.indexOf.call(r.children,t);o=(s?Number(s)+a:a+1)+". "}var c=/\n$/.test(e);return e=lm(e)+(c?`
76
+ `}};vt.listItem={filter:"li",replacement:function(e,t,n){var o=n.bulletListMarker+" ",r=t.parentNode;if(r.nodeName==="OL"){var s=r.getAttribute("start"),a=Array.prototype.indexOf.call(r.children,t);o=(s?Number(s)+a:a+1)+". "}var c=/\n$/.test(e);return e=um(e)+(c?`
77
77
  `:""),e=e.replace(/\n/gm,`
78
78
  `+" ".repeat(o.length)),o+e+(t.nextSibling?`
79
79
  `:"")}};vt.indentedCodeBlock={filter:function(e,t){return t.codeBlockStyle==="indented"&&e.nodeName==="PRE"&&e.firstChild&&e.firstChild.nodeName==="CODE"},replacement:function(e,t,n){return`
@@ -81,7 +81,7 @@ ${r}
81
81
  `+t.firstChild.textContent.replace(/\n/g,`
82
82
  `)+`
83
83
 
84
- `}};vt.fencedCodeBlock={filter:function(e,t){return t.codeBlockStyle==="fenced"&&e.nodeName==="PRE"&&e.firstChild&&e.firstChild.nodeName==="CODE"},replacement:function(e,t,n){var o=t.firstChild.getAttribute("class")||"",r=(o.match(/language-(\S+)/)||[null,""])[1],s=t.firstChild.textContent,a=n.fence.charAt(0),c=3,l=new RegExp("^"+a+"{3,}","gm"),u;while(u=l.exec(s))if(u[0].length>=c)c=u[0].length+1;var d=fl(a,c);return`
84
+ `}};vt.fencedCodeBlock={filter:function(e,t){return t.codeBlockStyle==="fenced"&&e.nodeName==="PRE"&&e.firstChild&&e.firstChild.nodeName==="CODE"},replacement:function(e,t,n){var o=t.firstChild.getAttribute("class")||"",r=(o.match(/language-(\S+)/)||[null,""])[1],s=t.firstChild.textContent,a=n.fence.charAt(0),c=3,l=new RegExp("^"+a+"{3,}","gm"),u;while(u=l.exec(s))if(u[0].length>=c)c=u[0].length+1;var d=gl(a,c);return`
85
85
 
86
86
  `+d+r+`
87
87
  `+s.replace(/\n$/,"")+`
@@ -91,13 +91,13 @@ ${r}
91
91
 
92
92
  `+n.hr+`
93
93
 
94
- `}};vt.inlineLink={filter:function(e,t){return t.linkStyle==="inlined"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t){var n=gl(t.getAttribute("href")),o=vl(As(t.getAttribute("title"))),r=o?' "'+o+'"':"";return"["+e+"]("+n+r+")"}};vt.referenceLink={filter:function(e,t){return t.linkStyle==="referenced"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t,n){var o=gl(t.getAttribute("href")),r=As(t.getAttribute("title"));if(r)r=' "'+vl(r)+'"';var s,a;switch(n.linkReferenceStyle){case"collapsed":s="["+e+"][]",a="["+e+"]: "+o+r;break;case"shortcut":s="["+e+"]",a="["+e+"]: "+o+r;break;default:var c=this.references.length+1;s="["+e+"]["+c+"]",a="["+c+"]: "+o+r}return this.references.push(a),s},references:[],append:function(e){var t="";if(this.references.length)t=`
94
+ `}};vt.inlineLink={filter:function(e,t){return t.linkStyle==="inlined"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t){var n=xl(t.getAttribute("href")),o=bl(Ns(t.getAttribute("title"))),r=o?' "'+o+'"':"";return"["+e+"]("+n+r+")"}};vt.referenceLink={filter:function(e,t){return t.linkStyle==="referenced"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t,n){var o=xl(t.getAttribute("href")),r=Ns(t.getAttribute("title"));if(r)r=' "'+bl(r)+'"';var s,a;switch(n.linkReferenceStyle){case"collapsed":s="["+e+"][]",a="["+e+"]: "+o+r;break;case"shortcut":s="["+e+"]",a="["+e+"]: "+o+r;break;default:var c=this.references.length+1;s="["+e+"]["+c+"]",a="["+c+"]: "+o+r}return this.references.push(a),s},references:[],append:function(e){var t="";if(this.references.length)t=`
95
95
 
96
96
  `+this.references.join(`
97
97
  `)+`
98
98
 
99
- `,this.references=[];return t}};vt.emphasis={filter:["em","i"],replacement:function(e,t,n){if(!e.trim())return"";return n.emDelimiter+e+n.emDelimiter}};vt.strong={filter:["strong","b"],replacement:function(e,t,n){if(!e.trim())return"";return n.strongDelimiter+e+n.strongDelimiter}};vt.code={filter:function(e){var t=e.previousSibling||e.nextSibling,n=e.parentNode.nodeName==="PRE"&&!t;return e.nodeName==="CODE"&&!n},replacement:function(e){if(!e)return"";e=e.replace(/\r?\n|\r/g," ");var t=/^`|^ .*?[^ ].* $|`$/.test(e)?" ":"",n="`",o=e.match(/`+/gm)||[];while(o.indexOf(n)!==-1)n=n+"`";return n+t+e+t+n}};vt.image={filter:"img",replacement:function(e,t){var n=mm(As(t.getAttribute("alt"))),o=gl(t.getAttribute("src")||""),r=As(t.getAttribute("title")),s=r?' "'+vl(r)+'"':"";return o?"!["+n+"]("+o+s+")":""}};function As(e){return e?e.replace(/(\n+\s*)+/g,`
100
- `):""}function gl(e){var t=e.replace(/([<>()])/g,"\\$1");return t.indexOf(" ")>=0?"<"+t+">":t}function vl(e){return e.replace(/"/g,"\\\"")}function hm(e){this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[];for(var t in e.rules)this.array.push(e.rules[t])}hm.prototype={add:function(e,t){this.array.unshift(t)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return""}})},forNode:function(e){if(e.isBlank)return this.blankRule;var t;if(t=ul(this.array,e,this.options))return t;if(t=ul(this._keep,e,this.options))return t;if(t=ul(this._remove,e,this.options))return t;return this.defaultRule},forEach:function(e){for(var t=0;t<this.array.length;t++)e(this.array[t],t)}};function ul(e,t,n){for(var o=0;o<e.length;o++){var r=e[o];if(jS(r,t,n))return r}return}function jS(e,t,n){var o=e.filter;if(typeof o==="string"){if(o===t.nodeName.toLowerCase())return!0}else if(Array.isArray(o)){if(o.indexOf(t.nodeName.toLowerCase())>-1)return!0}else if(typeof o==="function"){if(o.call(e,t,n))return!0}else throw TypeError("`filter` needs to be a string, array, or function")}function ZS(e){var{element:t,isBlock:n,isVoid:o}=e,r=e.isPre||function(p){return p.nodeName==="PRE"};if(!t.firstChild||r(t))return;var s=null,a=!1,c=null,l=im(c,t,r);while(l!==t){if(l.nodeType===3||l.nodeType===4){var u=l.data.replace(/[ \r\n\t]+/g," ");if((!s||/ $/.test(s.data))&&!a&&u[0]===" ")u=u.substr(1);if(!u){l=dl(l);continue}l.data=u,s=l}else if(l.nodeType===1){if(n(l)||l.nodeName==="BR"){if(s)s.data=s.data.replace(/ $/,"");s=null,a=!1}else if(o(l)||r(l))s=null,a=!0;else if(s)a=!1}else{l=dl(l);continue}var d=im(c,l,r);c=l,l=d}if(s){if(s.data=s.data.replace(/ $/,""),!s.data)dl(s)}}function dl(e){var t=e.nextSibling||e.parentNode;return e.parentNode.removeChild(e),t}function im(e,t,n){if(e&&e.parentNode===t||n(t))return t.nextSibling||t.parentNode;return t.firstChild||t.nextSibling||t.parentNode}var yl=typeof window<"u"?window:{};function HS(){var e=yl.DOMParser,t=!1;try{if(new e().parseFromString("","text/html"))t=!0}catch(n){}return t}function BS(){var e=function(){};if(US())e.prototype.parseFromString=function(t){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(t),n.close(),n};else e.prototype.parseFromString=function(t){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(t),n.close(),n};return e}function US(){var e=!1;try{document.implementation.createHTMLDocument("").open()}catch(t){if(yl.ActiveXObject)e=!0}return e}var WS=HS()?yl.DOMParser:BS();function qS(e,t){var n;if(typeof e==="string"){var o=VS().parseFromString('<x-turndown id="turndown-root">'+e+"</x-turndown>","text/html");n=o.getElementById("turndown-root")}else n=e.cloneNode(!0);return ZS({element:n,isBlock:ml,isVoid:dm,isPre:t.preformattedCode?GS:null}),n}var pl;function VS(){return pl=pl||new WS,pl}function GS(e){return e.nodeName==="PRE"||e.nodeName==="CODE"}function XS(e,t){return e.isBlock=ml(e),e.isCode=e.nodeName==="CODE"||e.parentNode.isCode,e.isBlank=KS(e),e.flankingWhitespace=JS(e,t),e}function KS(e){return!dm(e)&&!LS(e)&&/^\s*$/i.test(e.textContent)&&!OS(e)&&!DS(e)}function JS(e,t){if(e.isBlock||t.preformattedCode&&e.isCode)return{leading:"",trailing:""};var n=YS(e.textContent);if(n.leadingAscii&&sm("left",e,t))n.leading=n.leadingNonAscii;if(n.trailingAscii&&sm("right",e,t))n.trailing=n.trailingNonAscii;return{leading:n.leading,trailing:n.trailing}}function YS(e){var t=e.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:t[1],leadingAscii:t[2],leadingNonAscii:t[3],trailing:t[4],trailingNonAscii:t[5],trailingAscii:t[6]}}function sm(e,t,n){var o,r,s;if(e==="left")o=t.previousSibling,r=/ $/;else o=t.nextSibling,r=/^ /;if(o){if(o.nodeType===3)s=r.test(o.nodeValue);else if(n.preformattedCode&&o.nodeName==="CODE")s=!1;else if(o.nodeType===1&&!ml(o))s=r.test(o.textContent)}return s}var QS=Array.prototype.reduce;function qr(e){if(!(this instanceof qr))return new qr(e);var t={rules:vt,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(n,o){return o.isBlock?`
99
+ `,this.references=[];return t}};vt.emphasis={filter:["em","i"],replacement:function(e,t,n){if(!e.trim())return"";return n.emDelimiter+e+n.emDelimiter}};vt.strong={filter:["strong","b"],replacement:function(e,t,n){if(!e.trim())return"";return n.strongDelimiter+e+n.strongDelimiter}};vt.code={filter:function(e){var t=e.previousSibling||e.nextSibling,n=e.parentNode.nodeName==="PRE"&&!t;return e.nodeName==="CODE"&&!n},replacement:function(e){if(!e)return"";e=e.replace(/\r?\n|\r/g," ");var t=/^`|^ .*?[^ ].* $|`$/.test(e)?" ":"",n="`",o=e.match(/`+/gm)||[];while(o.indexOf(n)!==-1)n=n+"`";return n+t+e+t+n}};vt.image={filter:"img",replacement:function(e,t){var n=hm(Ns(t.getAttribute("alt"))),o=xl(t.getAttribute("src")||""),r=Ns(t.getAttribute("title")),s=r?' "'+bl(r)+'"':"";return o?"!["+n+"]("+o+s+")":""}};function Ns(e){return e?e.replace(/(\n+\s*)+/g,`
100
+ `):""}function xl(e){var t=e.replace(/([<>()])/g,"\\$1");return t.indexOf(" ")>=0?"<"+t+">":t}function bl(e){return e.replace(/"/g,"\\\"")}function gm(e){this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[];for(var t in e.rules)this.array.push(e.rules[t])}gm.prototype={add:function(e,t){this.array.unshift(t)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return""}})},forNode:function(e){if(e.isBlank)return this.blankRule;var t;if(t=fl(this.array,e,this.options))return t;if(t=fl(this._keep,e,this.options))return t;if(t=fl(this._remove,e,this.options))return t;return this.defaultRule},forEach:function(e){for(var t=0;t<this.array.length;t++)e(this.array[t],t)}};function fl(e,t,n){for(var o=0;o<e.length;o++){var r=e[o];if(HS(r,t,n))return r}return}function HS(e,t,n){var o=e.filter;if(typeof o==="string"){if(o===t.nodeName.toLowerCase())return!0}else if(Array.isArray(o)){if(o.indexOf(t.nodeName.toLowerCase())>-1)return!0}else if(typeof o==="function"){if(o.call(e,t,n))return!0}else throw TypeError("`filter` needs to be a string, array, or function")}function BS(e){var{element:t,isBlock:n,isVoid:o}=e,r=e.isPre||function(p){return p.nodeName==="PRE"};if(!t.firstChild||r(t))return;var s=null,a=!1,c=null,l=sm(c,t,r);while(l!==t){if(l.nodeType===3||l.nodeType===4){var u=l.data.replace(/[ \r\n\t]+/g," ");if((!s||/ $/.test(s.data))&&!a&&u[0]===" ")u=u.substr(1);if(!u){l=ml(l);continue}l.data=u,s=l}else if(l.nodeType===1){if(n(l)||l.nodeName==="BR"){if(s)s.data=s.data.replace(/ $/,"");s=null,a=!1}else if(o(l)||r(l))s=null,a=!0;else if(s)a=!1}else{l=ml(l);continue}var d=sm(c,l,r);c=l,l=d}if(s){if(s.data=s.data.replace(/ $/,""),!s.data)ml(s)}}function ml(e){var t=e.nextSibling||e.parentNode;return e.parentNode.removeChild(e),t}function sm(e,t,n){if(e&&e.parentNode===t||n(t))return t.nextSibling||t.parentNode;return t.firstChild||t.nextSibling||t.parentNode}var wl=typeof window<"u"?window:{};function US(){var e=wl.DOMParser,t=!1;try{if(new e().parseFromString("","text/html"))t=!0}catch(n){}return t}function WS(){var e=function(){};if(qS())e.prototype.parseFromString=function(t){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(t),n.close(),n};else e.prototype.parseFromString=function(t){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(t),n.close(),n};return e}function qS(){var e=!1;try{document.implementation.createHTMLDocument("").open()}catch(t){if(wl.ActiveXObject)e=!0}return e}var VS=US()?wl.DOMParser:WS();function GS(e,t){var n;if(typeof e==="string"){var o=XS().parseFromString('<x-turndown id="turndown-root">'+e+"</x-turndown>","text/html");n=o.getElementById("turndown-root")}else n=e.cloneNode(!0);return BS({element:n,isBlock:vl,isVoid:pm,isPre:t.preformattedCode?KS:null}),n}var hl;function XS(){return hl=hl||new VS,hl}function KS(e){return e.nodeName==="PRE"||e.nodeName==="CODE"}function JS(e,t){return e.isBlock=vl(e),e.isCode=e.nodeName==="CODE"||e.parentNode.isCode,e.isBlank=YS(e),e.flankingWhitespace=QS(e,t),e}function YS(e){return!pm(e)&&!FS(e)&&/^\s*$/i.test(e.textContent)&&!DS(e)&&!jS(e)}function QS(e,t){if(e.isBlock||t.preformattedCode&&e.isCode)return{leading:"",trailing:""};var n=ek(e.textContent);if(n.leadingAscii&&am("left",e,t))n.leading=n.leadingNonAscii;if(n.trailingAscii&&am("right",e,t))n.trailing=n.trailingNonAscii;return{leading:n.leading,trailing:n.trailing}}function ek(e){var t=e.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:t[1],leadingAscii:t[2],leadingNonAscii:t[3],trailing:t[4],trailingNonAscii:t[5],trailingAscii:t[6]}}function am(e,t,n){var o,r,s;if(e==="left")o=t.previousSibling,r=/ $/;else o=t.nextSibling,r=/^ /;if(o){if(o.nodeType===3)s=r.test(o.nodeValue);else if(n.preformattedCode&&o.nodeName==="CODE")s=!1;else if(o.nodeType===1&&!vl(o))s=r.test(o.textContent)}return s}var tk=Array.prototype.reduce;function qr(e){if(!(this instanceof qr))return new qr(e);var t={rules:vt,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(n,o){return o.isBlock?`
101
101
 
102
102
  `:""},keepReplacement:function(n,o){return o.isBlock?`
103
103
 
@@ -107,11 +107,11 @@ ${r}
107
107
 
108
108
  `+n+`
109
109
 
110
- `:n}};this.options=$S({},t,e),this.rules=new hm(this.options)}qr.prototype={turndown:function(e){if(!nk(e))throw TypeError(e+" is not a string, or an element/document/fragment node.");if(e==="")return"";var t=gm.call(this,new qS(e,this.options));return ek.call(this,t)},use:function(e){if(Array.isArray(e))for(var t=0;t<e.length;t++)this.use(e[t]);else if(typeof e==="function")e(this);else throw TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(e,t){return this.rules.add(e,t),this},keep:function(e){return this.rules.keep(e),this},remove:function(e){return this.rules.remove(e),this},escape:function(e){return mm(e)}};function gm(e){var t=this;return QS.call(e.childNodes,function(n,o){o=new XS(o,t.options);var r="";if(o.nodeType===3)r=o.isCode?o.nodeValue:t.escape(o.nodeValue);else if(o.nodeType===1)r=tk.call(t,o);return vm(n,r)},"")}function ek(e){var t=this;return this.rules.forEach(function(n){if(typeof n.append==="function")e=vm(e,n.append(t.options))}),e.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function tk(e){var t=this.rules.forNode(e),n=gm.call(this,e),o=e.flankingWhitespace;if(o.leading||o.trailing)n=n.trim();return o.leading+t.replacement(n,e,this.options)+o.trailing}function vm(e,t){var n=cm(e),o=am(t),r=Math.max(e.length-n.length,t.length-o.length),s=`
110
+ `:n}};this.options=OS({},t,e),this.rules=new gm(this.options)}qr.prototype={turndown:function(e){if(!rk(e))throw TypeError(e+" is not a string, or an element/document/fragment node.");if(e==="")return"";var t=vm.call(this,new GS(e,this.options));return nk.call(this,t)},use:function(e){if(Array.isArray(e))for(var t=0;t<e.length;t++)this.use(e[t]);else if(typeof e==="function")e(this);else throw TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(e,t){return this.rules.add(e,t),this},keep:function(e){return this.rules.keep(e),this},remove:function(e){return this.rules.remove(e),this},escape:function(e){return hm(e)}};function vm(e){var t=this;return tk.call(e.childNodes,function(n,o){o=new JS(o,t.options);var r="";if(o.nodeType===3)r=o.isCode?o.nodeValue:t.escape(o.nodeValue);else if(o.nodeType===1)r=ok.call(t,o);return ym(n,r)},"")}function nk(e){var t=this;return this.rules.forEach(function(n){if(typeof n.append==="function")e=ym(e,n.append(t.options))}),e.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function ok(e){var t=this.rules.forNode(e),n=vm.call(this,e),o=e.flankingWhitespace;if(o.leading||o.trailing)n=n.trim();return o.leading+t.replacement(n,e,this.options)+o.trailing}function ym(e,t){var n=lm(e),o=cm(t),r=Math.max(e.length-n.length,t.length-o.length),s=`
111
111
 
112
- `.substring(0,r);return n+s+o}function nk(e){return e!=null&&(typeof e==="string"||e.nodeType&&(e.nodeType===1||e.nodeType===9||e.nodeType===11))}function zs(){let e=window.getSelection(),t=e&&e.rangeCount>0?e.getRangeAt(0).cloneRange():null;Yt("Link URL","https://example.com").then((n)=>{if(!n)return;let o=n.trim().toLowerCase();if(o.startsWith("javascript:")||o.startsWith("data:"))return;if(t){let r=window.getSelection();r?.removeAllRanges(),r?.addRange(t)}document.execCommand("createLink",!1,n)})}function ym(){let e=window.getSelection();if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(t.collapsed)return;let n=t.toString(),o=document.createElement("code");o.textContent=n,t.deleteContents(),t.insertNode(o);let r=document.createRange();r.setStartAfter(o),r.setEndAfter(o),e.removeAllRanges(),e.addRange(r)}var Ps=8,ok=[{kind:"exec",command:"bold",icon:"B",title:`Bold (${Ze("B")})`},{kind:"exec",command:"italic",icon:"I",title:`Italic (${Ze("I")})`},{kind:"exec",command:"strikeThrough",icon:"S",title:"Strikethrough"},{kind:"code",icon:"{ }",title:"Inline code",dividerBefore:!0},{kind:"block",tag:"H1",icon:"H1",title:"Heading 1",dividerBefore:!0},{kind:"block",tag:"H2",icon:"H2",title:"Heading 2"},{kind:"block",tag:"H3",icon:"H3",title:"Heading 3"},{kind:"block",tag:"P",icon:"¶",title:"Paragraph"},{kind:"block",tag:"BLOCKQUOTE",icon:"❝",title:"Quote",dividerBefore:!0},{kind:"exec",command:"insertUnorderedList",icon:"•",title:"Bullet list"},{kind:"exec",command:"insertOrderedList",icon:"1.",title:"Numbered list"},{kind:"link",icon:"\uD83D\uDD17",title:`Link (${Ze("K")})`,dividerBefore:!0}];function rk(e){switch(e.kind){case"exec":document.execCommand(e.command);return;case"block":document.execCommand("formatBlock",!1,e.tag);return;case"code":ym();return;case"link":zs();return}}function xm({hostRef:e,onChange:t}){let[n,o]=L(!1),[r,s]=L({top:0,left:0}),[a,c]=L(0),l=R(null),u=R(null),d=O(()=>{let f=e.current;if(!f){o(!1);return}let g=window.getSelection();if(!g||g.rangeCount===0||g.isCollapsed){o(!1);return}let y=g.getRangeAt(0);if(!f.contains(y.commonAncestorContainer)){o(!1);return}let x=y.getBoundingClientRect();if(x.width===0&&x.height===0){o(!1);return}let h=a||420,v=Math.max(Ps,Math.min(x.left+x.width/2-h/2,window.innerWidth-h-Ps)),b=Math.max(Ps,x.top-Ps-36);s({top:b,left:v}),o(!0)},[e,a]),p=O(()=>{if(u.current!==null)return;u.current=requestAnimationFrame(()=>{u.current=null,d()})},[d]);D(()=>(document.addEventListener("selectionchange",p),window.addEventListener("scroll",p,!0),window.addEventListener("resize",p),()=>{if(document.removeEventListener("selectionchange",p),window.removeEventListener("scroll",p,!0),window.removeEventListener("resize",p),u.current!==null)cancelAnimationFrame(u.current)}),[p]),Bi(()=>{if(!n)return;let f=l.current;if(!f)return;let g=f.getBoundingClientRect().width;if(g&&Math.abs(g-a)>1)c(g)},[n,a]);let m=O((f)=>{rk(f),t(),d()},[t,d]);if(!n)return null;return i("div",{ref:l,class:"md-inline-format-bar",style:{top:`${r.top}px`,left:`${r.left}px`},onMouseDown:(f)=>f.preventDefault(),children:ok.flatMap((f,g)=>{let y=i("button",{type:"button",class:"md-inline-format-btn",title:f.title,onClick:()=>m(f),children:f.icon},`btn-${g}`,!1,void 0,this);return f.dividerBefore?[i("span",{class:"md-inline-format-divider"},`div-${g}`,!1,void 0,this),y]:[y]})},void 0,!1,void 0,this)}var xl=null;function ik(){if(xl)return xl;let e=new qr({headingStyle:"atx",codeBlockStyle:"fenced",emDelimiter:"*",bulletListMarker:"-"});return e.use(bm.gfm),xl=e,e}function wm({initialHtml:e,className:t,onChange:n,onSave:o}){let r=R(null),s=R(e);D(()=>{let m=r.current;if(!m)return;m.innerHTML=s.current;for(let f of m.querySelectorAll('input[type="checkbox"][disabled]'))f.removeAttribute("disabled")},[]);let a=O(()=>{let m=r.current;if(!m)return"";return ik().turndown(m.innerHTML)},[]),c=O(()=>{n(a())},[n,a]),l=O(()=>{let m=r.current;if(!m||!m.isConnected||m.innerHTML==="")return;o?.(a())},[o,a]),u=O((m)=>{if(!(m.metaKey||m.ctrlKey))return;if(m.key==="s"){m.preventDefault(),l();return}if(m.key==="b"){m.preventDefault(),document.execCommand("bold"),c();return}if(m.key==="i"){m.preventDefault(),document.execCommand("italic"),c();return}if(m.key==="k")m.preventDefault(),zs(),c()},[c,l]),d=O((m)=>{let f=m.target;if(f instanceof HTMLInputElement&&f.type==="checkbox")f.toggleAttribute("checked",f.checked),c()},[c]),p=O((m)=>{let f=m.clipboardData?.getData("text/plain");if(f==null)return;m.preventDefault(),document.execCommand("insertText",!1,f),c()},[c]);return i(ve,{children:[i("div",{ref:r,class:t,contentEditable:!0,spellcheck:!1,onInput:c,onKeyDown:u,onPaste:p,onClick:d,onBlur:l},void 0,!1,void 0,this),i(xm,{hostRef:r,onChange:c},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bl({html:e,className:t,style:n,onTaskToggle:o}){let r=R(null),s=R(o);return s.current=o,D(()=>{let c=r.current;if(!c)return;if(c.replaceChildren(),!e)return;let l=document.createElement("template");if(l.innerHTML=e,c.append(l.content.cloneNode(!0)),s.current)for(let u of c.querySelectorAll('input[type="checkbox"][disabled]'))u.removeAttribute("disabled")},[e]),i("div",{ref:r,class:t,style:n,onClick:o?(c)=>{let l=s.current,u=r.current;if(!u||!l)return;let d=c.target,p=null;if(d instanceof HTMLInputElement&&d.type==="checkbox")p=d;else{let g=d.closest("li")?.querySelector(':scope > input[type="checkbox"]');if(g&&c.clientX<=g.getBoundingClientRect().right+6)p=g}if(!p)return;c.stopPropagation();let m=[...u.querySelectorAll('input[type="checkbox"]')].indexOf(p);if(m>=0)l(m)}:void 0},void 0,!1,void 0,this)}function sk(e,t){let n=-1;return e.replace(/^(\s*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\])/gm,(o,r,s,a)=>{if(n+=1,n!==t)return o;return`${r}${s===" "?"x":" "}${a}`})}function Ns({node:e,expanded:t=!1}){let n=e.data.path,[o,r]=L(""),[s,a]=L(""),[c,l]=L(!1),[u,d]=L(!1),[p,m]=L(!1),[f,g]=L(!1),y=R(null),x=R(null),h=R(""),v=R(null),b=e.data.reviewActive;D(()=>{let j=!1;return(async()=>{let E;if(n){let W=await Or(n);if(j)return;E=W.content}else if(e.data.content)E=e.data.content;else{l(!0);return}r(E);let B=await an(E);if(j)return;a(B),l(!0),oe(e.id,{content:E,rendered:B})})(),()=>{j=!0}},[n,e.id,e.data.content]);let z=O(async(j)=>{let E=j.target.value;r(E),g(!0);let B=await an(E);a(B)},[]),F=O(async(j)=>{if(!n){let B=await an(j);a(B),g(!1),oe(e.id,{content:j,rendered:B}),await rt(e.id,{content:j,data:{rendered:B}});return}m(!0);let E=await Lp(n,j);if(m(!1),E.ok){let B=await an(j);a(B),g(!1),oe(e.id,{content:j,rendered:B,savedAt:E.updatedAt}),await rt(e.id,{content:j,data:{rendered:B,savedAt:E.updatedAt}})}},[n,e.id]),_=O(async()=>{if(!f)return;await F(o)},[f,o,F]),k=O((j)=>{if((j.metaKey||j.ctrlKey)&&j.key==="s"){j.preventDefault(),_();return}let E=y.current;if(E&&Zf(j,E))return;if(E&&j.key==="Tab")j.preventDefault(),jf(E,j.shiftKey)},[_]);v.current=F;let T=O((j)=>{if(r(j),g(!0),h.current=j,x.current!==null)window.clearTimeout(x.current);x.current=window.setTimeout(()=>{x.current=null,F(j)},800)},[F]),P=O((j)=>{if(r(j),h.current=j,x.current!==null)window.clearTimeout(x.current),x.current=null;F(j)},[F]);D(()=>()=>{if(x.current===null)return;window.clearTimeout(x.current),x.current=null;let j=v.current;if(j)j(h.current)},[e.id]);let Z=b?i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-ok-10)",color:"var(--c-ok)",borderBottom:"1px solid var(--c-ok-20)",textTransform:"uppercase",letterSpacing:"0.05em",fontWeight:600},children:"Review active"},void 0,!1,void 0,this):null;if(u&&t)return i("div",{class:"md-editor-expanded",onKeyDown:k,children:[i("div",{class:"md-editor-toolbar",children:[i("button",{type:"button",class:"md-toolbar-btn",onClick:()=>d(!1),children:"← Back to document"},void 0,!1,void 0,this),i("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[n&&i("span",{class:"md-toolbar-path",children:n.split("/").pop()},void 0,!1,void 0,this),i("button",{type:"button",class:`md-toolbar-btn${f?" md-toolbar-btn-primary":""}`,onClick:_,disabled:!f||p,children:p?"Saving…":f?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"md-editor-split",children:[i("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[i("textarea",{ref:y,value:o,onInput:z,spellcheck:!1},void 0,!1,void 0,this),i(sl,{textareaRef:y},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(bl,{html:s,className:"md-preview"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(u)return i("div",{class:"md-editor-split",style:{height:"100%"},onKeyDown:k,children:[i("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[i("textarea",{ref:y,value:o,onInput:z,spellcheck:!1},void 0,!1,void 0,this),i(sl,{textareaRef:y},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(bl,{html:s,className:"md-preview"},void 0,!1,void 0,this),i("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[i("button",{type:"button",onClick:()=>d(!1),style:{padding:"4px 10px",fontSize:"11px",background:"var(--c-input-bg)",border:"1px solid var(--c-line)",borderRadius:"6px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Document"},void 0,!1,void 0,this),i("button",{type:"button",onClick:_,disabled:!f||p,style:{padding:"4px 10px",fontSize:"11px",background:f?"var(--c-accent-25)":"var(--c-input-bg)",border:`1px solid ${f?"var(--c-accent)":"var(--c-line)"}`,borderRadius:"6px",color:f?"var(--c-text)":"var(--c-dim)",cursor:f?"pointer":"default"},children:p?"Saving…":f?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(t)return i("div",{style:{height:"100%",position:"relative"},children:[Z,i("div",{class:"md-reader",children:c?i(wm,{initialHtml:s||"<p><br></p>",className:"md-reader-content md-reader-editable",onChange:T,onSave:P},e.id,!1,void 0,this):i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"24px"},children:"Loading…"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"md-edit-fab",onClick:()=>d(!0),children:"</> Source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{style:{height:"100%",position:"relative"},children:[Z,i(bl,{html:s,style:{padding:s?"0":"12px",color:s?void 0:"var(--c-dim)"},onTaskToggle:(j)=>{let E=sk(o,j);if(E!==o)P(E)}},void 0,!1,void 0,this),!c&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Loading…"},void 0,!1,void 0,this),c&&!s&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Empty node"},void 0,!1,void 0,this),i("button",{type:"button",class:"md-edit-btn",onClick:()=>en(e.id),children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Rs="pmx-canvas-ax",$s="pmx-canvas-ax-ack",Mt="pmx-canvas-html-node",Ms="pmx-canvas-ext-app-alive",wl="pmx-canvas-ext-app-paint-probe";function _m(e,t){switch(e){case"html":return typeof t.html==="string"&&t.html.length>0||typeof t.content==="string"&&t.content.length>0;case"mermaid":return typeof t.content==="string"&&t.content.trim().length>0;case"json-render":case"graph":return!0;case"mcp-app":return t.viewerType==="web-artifact"&&typeof t.path==="string"&&t.path.length>0||typeof t.url==="string"&&t.url.length>0;case"webpage":return typeof t.url==="string"&&t.url.length>0;default:return!1}}var _l="allow-scripts allow-popups allow-popups-to-escape-sandbox";function tr(e){let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Vr(e,t={}){let n=new URLSearchParams;if(n.set("theme",t.theme??Xe.value),t.themeToken)n.set("themeToken",t.themeToken);if(t.present)n.set("present","1");if(t.presentToken)n.set("presentToken",t.presentToken);if(t.v)n.set("v",t.v);if(t.axToken)n.set("axToken",t.axToken);if(t.frameToken)n.set("frameToken",t.frameToken);return`/api/canvas/surface/${encodeURIComponent(e)}?${n.toString()}`}function Os(e){return _m(e.type,e.data)}async function Ls(e){let t=Vr(e.id);if(!(await Hp(e.id,t)).opened)window.open(t,"_blank","noopener")}var ak={markdown:{width:360,height:180},context:{width:360,height:180},file:{width:360,height:200},diff:{width:420,height:240},mermaid:{width:360,height:240},status:{width:280,height:120},ledger:{width:320,height:200},image:{width:240,height:180},html:{width:420,height:280},webpage:{width:420,height:280},"json-render":{width:420,height:280},graph:{width:420,height:280},"mcp-app":{width:480,height:320}};function Sm(e){return ak[e]}var nr=37,ck=600,lk=1400,uk=24;function dk(e){return e.type==="html"||e.type==="mermaid"||e.type==="json-render"||e.type==="graph"||e.type==="mcp-app"||e.type==="webpage"}function pk(e){if(e.type==="html")return e.data.presentation!==!0;if(e.type==="mermaid")return!0;if(e.type==="json-render"||e.type==="graph")return!0;if(e.type==="mcp-app")return e.data.viewerType==="web-artifact";return!1}function km(e){return e.collapsed===!0||e.data.strictSize===!0||e.data.userResized===!0||e.type==="group"}function Sl(e){return!km(e)&&!dk(e)}function Cm(e,t){if(!Sl(e)||t<=0)return null;let n=Math.min(t+nr,ck),o=Sm(e.type);return o?Math.max(n,o.height):n}function kl(e){return pk(e)&&!km(e)}function Tm(e,t){if(!kl(e)||t<=0)return null;let n=Math.min(t+nr+uk,lk);return n>e.size.height+8?n:null}function or(e,t,n){let o=R(e);o.current=e;let r=R(null);D(()=>{if(!n)return;function s(a){if(a.source!==t.current?.contentWindow)return;let c=a.data;if(!c||c.source!=="pmx-canvas-frame"||c.type!=="content-height"||c.token!==n)return;let l=o.current,u=typeof c.height==="number"?c.height:0,d=Tm(l,u);if(d===null)return;if(Ko(l.id,{width:l.size.width,height:d}),r.current!==null)window.clearTimeout(r.current);r.current=window.setTimeout(()=>{Ye({recordHistory:!1}),r.current=null},300)}return window.addEventListener("message",s),()=>{if(window.removeEventListener("message",s),r.current!==null)window.clearTimeout(r.current),r.current=null}},[e.id,n])}function fk(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function rr(e){let t=gt.value,[n,o]=L(null),r=Boolean(e)&&fk(e),s=t==="srcdoc"&&r;if(D(()=>{if(!s)return;let a=!1;return fetch(`${e}${e.includes("?")?"&":"?"}inline-assets=1`,{credentials:"same-origin"}).then((c)=>c.ok?c.text():Promise.reject(Error(`HTTP ${c.status}`))).then((c)=>{if(!a)o({url:e,html:c})}).catch((c)=>{if(console.error("[surface-frame] srcdoc fetch failed, falling back to src:",e,c),!a)o({url:e,html:""})}),()=>{a=!0}},[s,e]),!e)return{};if(!s)return t===null&&r?{}:{src:e};if(n)return n.html?{srcdoc:n.html}:{src:n.url};return{}}function Ds({node:e,expanded:t=!1}){let n=R(null),o=Xe.value,r=Ae(()=>`theme-${crypto.randomUUID()}`,[]),s=Ae(()=>`frame-${crypto.randomUUID()}`,[]),a=typeof e.data.content==="string"?e.data.content:"",c=Ae(()=>tr(a),[a]),l=Ae(()=>a?Vr(e.id,{theme:o,themeToken:r,v:c,frameToken:s}):"",[a,r,c,e.id,s]),u=rr(l);or(e,n,t?"":s);let d=()=>{n.current?.contentWindow?.postMessage({source:Mt,type:"theme-update",token:r,theme:o},"*")};if(D(d,[o,r]),!a)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No diagram source set"},void 0,!1,void 0,this);return i("iframe",{ref:n,class:"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"Mermaid diagram",sandbox:"allow-scripts",...u,onLoad:d,style:{width:"100%",height:"100%",minHeight:t?"70vh":"300px",border:"none",background:"var(--c-bg)",borderRadius:"6px",display:"block"}},void 0,!1,void 0,this)}var Cl=["dark","light","high-contrast","midnight","sepia","arctic","ember","forest","volt"];function Gr(e){return typeof e==="string"&&Cl.includes(e)}function Tl(e,t="dark"){return Gr(e)?e:t}var ir={dark:{label:"Dark",scheme:"dark",swatchBg:"#081524",swatchAccent:"#4BBCFF"},light:{label:"Light",scheme:"light",swatchBg:"#F4EFE6",swatchAccent:"#1A7ABF"},"high-contrast":{label:"High contrast",scheme:"dark",swatchBg:"#000000",swatchAccent:"#00ffff"},midnight:{label:"Midnight",scheme:"dark",swatchBg:"#0A0D1C",swatchAccent:"#8B96FF"},sepia:{label:"Sepia",scheme:"light",swatchBg:"#F2E7D5",swatchAccent:"#B4632C"},arctic:{label:"Arctic",scheme:"dark",swatchBg:"#20242E",swatchAccent:"#7FC8DE"},ember:{label:"Ember",scheme:"dark",swatchBg:"#0B0B0C",swatchAccent:"#F34E1C"},forest:{label:"Forest",scheme:"dark",swatchBg:"#0C1712",swatchAccent:"#5CCF8F"},volt:{label:"Volt",scheme:"dark",swatchBg:"#0B0D0B",swatchAccent:"#DFDFC1"}};function sr(e){return ir[Tl(e)].scheme}var xP=Object.freeze({status:"aborted"});function A(e,t,n){function o(c,l){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:l,constr:a,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);let u=a.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){let m=d[p];if(!(m in c))c[m]=u[m].bind(c)}}let r=n?.Parent??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function a(c){var l;let u=n?.Parent?new s:this;o(u,c),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:(c)=>{if(n?.Parent&&c instanceof n.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}var bP=Symbol("zod_brand");class mn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Xr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}var Fs={};function Ot(e){if(e)Object.assign(Fs,e);return Fs}function Zs(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,r])=>t.indexOf(+o)===-1).map(([o,r])=>r)}function Il(e,t="|"){return e.map((n)=>Nl(n)).join(t)}function Kr(e,t){if(typeof t==="bigint")return t.toString();return t}function Jr(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Hs(e){return e===null||e===void 0}function Bs(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Im(e,t){let n=(e.toString().split(".")[1]||"").length,o=t.toString(),r=(o.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(o)){let l=o.match(/\d?e-(\d?)/);if(l?.[1])r=Number.parseInt(l[1])}let s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),c=Number.parseInt(t.toFixed(s).replace(".",""));return a%c/10**s}var Em=Symbol("evaluating");function be(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===Em)return;if(o===void 0)o=Em,o=n();return o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function fo(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function On(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Al(e){return JSON.stringify(e)}function Am(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ar(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var zm=Jr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function mo(e){if(ar(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(ar(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Pl(e){if(mo(e))return{...e};if(Array.isArray(e))return[...e];return e}var Pm=new Set(["string","number","symbol"]);function Ln(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nn(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function X(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Nl(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Nm(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Rm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function mk(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=On(e._zod.def,{get shape(){let a={};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;a[c]=n.shape[c]}return fo(this,"shape",a),a},checks:[]});return nn(e,s)}function hk(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=On(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete a[c]}return fo(this,"shape",a),a},checks:[]});return nn(e,s)}function gk(e,t){if(!mo(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let s=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=On(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return fo(this,"shape",s),s}});return nn(e,r)}function vk(e,t){if(!mo(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=On(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return fo(this,"shape",o),o}});return nn(e,n)}function yk(e,t){let n=On(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return fo(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return nn(e,n)}function xk(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=On(t._zod.def,{get shape(){let c=t._zod.def.shape,l={...c};if(n)for(let u in n){if(!(u in c))throw Error(`Unrecognized key: "${u}"`);if(!n[u])continue;l[u]=e?new e({type:"optional",innerType:c[u]}):c[u]}else for(let u in c)l[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return fo(this,"shape",l),l},checks:[]});return nn(t,a)}function bk(e,t,n){let o=On(t._zod.def,{get shape(){let r=t._zod.def.shape,s={...r};if(n)for(let a in n){if(!(a in s))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;s[a]=new e({type:"nonoptional",innerType:r[a]})}else for(let a in r)s[a]=new e({type:"nonoptional",innerType:r[a]});return fo(this,"shape",s),s}});return nn(t,o)}function ho(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Dn(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function js(e){return typeof e==="string"?e:e?.message}function on(e,t,n){let o={...e,path:e.path??[]};if(!e.message){let r=js(e.inst?._zod.def?.error?.(e))??js(t?.error?.(e))??js(n.customError?.(e))??js(n.localeError?.(e))??"Invalid input";o.message=r}if(delete o.inst,delete o.continue,!t?.reportInput)delete o.input;return o}function Us(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function $m(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function go(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}var Mm=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Kr,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ws=A("$ZodError",Mm),Rl=A("$ZodError",Mm,{Parent:Error});function Om(e,t=(n)=>n.message){let n={},o=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else o.push(t(r));return{formErrors:o,fieldErrors:n}}function Lm(e,t=(n)=>n.message){let n={_errors:[]},o=(r)=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let a=n,c=0;while(c<s.path.length){let l=s.path[c];if(c!==s.path.length-1)a[l]=a[l]||{_errors:[]};else a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(s));a=a[l],c++}}};return o(e),n}var qs=(e)=>(t,n,o,r)=>{let s=o?Object.assign(o,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new mn;if(a.issues.length){let c=new(r?.Err??e)(a.issues.map((l)=>on(l,s,Ot())));throw zl(c,r?.callee),c}return a.value};var Vs=(e)=>async(t,n,o,r)=>{let s=o?Object.assign(o,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(r?.Err??e)(a.issues.map((l)=>on(l,s,Ot())));throw zl(c,r?.callee),c}return a.value};var Yr=(e)=>(t,n,o)=>{let r=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new mn;return s.issues.length?{success:!1,error:new(e??Ws)(s.issues.map((a)=>on(a,r,Ot())))}:{success:!0,data:s.value}},Qr=Yr(Rl),ei=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>on(a,r,Ot())))}:{success:!0,data:s.value}},Gs=ei(Rl),Dm=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return qs(e)(t,n,r)};var Fm=(e)=>(t,n,o)=>qs(e)(t,n,o);var jm=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Vs(e)(t,n,r)};var Zm=(e)=>async(t,n,o)=>Vs(e)(t,n,o);var Hm=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Yr(e)(t,n,r)};var Bm=(e)=>(t,n,o)=>Yr(e)(t,n,o);var Um=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ei(e)(t,n,r)};var Wm=(e)=>async(t,n,o)=>ei(e)(t,n,o);var qm=/^[cC][^\s-]{8,}$/,Vm=/^[0-9a-z]+$/,Gm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xm=/^[0-9a-vA-V]{20}$/,Km=/^[A-Za-z0-9]{27}$/,Jm=/^[a-zA-Z0-9_-]{21}$/,Ym=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Qm=/^([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})$/,$l=(e)=>{if(!e)return/^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return 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})$`)};var eh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var _k="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function th(){return new RegExp(_k,"u")}var nh=/^(?:(?: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])$/,oh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var rh=/^((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])$/,ih=/^(([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])$/,sh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ml=/^[A-Za-z0-9_-]*$/;var ah=/^\+[1-9]\d{6,14}$/,ch="(?:(?:\\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])))",lh=new RegExp(`^${ch}$`);function uh(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function dh(e){return new RegExp(`^${uh(e)}$`)}function ph(e){let t=uh({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${n.join("|")})`;return new RegExp(`^${ch}T(?:${o})$`)}var fh=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var mh=/^-?\d+$/,Ol=/^-?\d+(?:\.\d+)?$/,hh=/^(?:true|false)$/i,gh=/^null$/i;var vh=/^undefined$/i;var yh=/^[^A-Z]*$/,xh=/^[^a-z]*$/;var at=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),bh={number:"number",bigint:"bigint",object:"date"},Ll=A("$ZodCheckLessThan",(e,t)=>{at.init(e,t);let n=bh[typeof t.value];e._zod.onattach.push((o)=>{let r=o._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dl=A("$ZodCheckGreaterThan",(e,t)=>{at.init(e,t);let n=bh[typeof t.value];e._zod.onattach.push((o)=>{let r=o._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),wh=A("$ZodCheckMultipleOf",(e,t)=>{at.init(e,t),e._zod.onattach.push((n)=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):Im(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),_h=A("$ZodCheckNumberFormat",(e,t)=>{at.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[r,s]=Rm[t.format];e._zod.onattach.push((a)=>{let c=a._zod.bag;if(c.format=t.format,c.minimum=r,c.maximum=s,n)c.pattern=mh}),e._zod.check=(a)=>{let c=a.value;if(n){if(!Number.isInteger(c)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(c<r)a.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(c>s)a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Sh=A("$ZodCheckMaxLength",(e,t)=>{var n;at.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Hs(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let r=o.value;if(r.length<=t.maximum)return;let a=Us(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),kh=A("$ZodCheckMinLength",(e,t)=>{var n;at.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Hs(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let r=o.value;if(r.length>=t.minimum)return;let a=Us(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ch=A("$ZodCheckLengthEquals",(e,t)=>{var n;at.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Hs(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(o)=>{let r=o.value,s=r.length;if(s===t.length)return;let a=Us(r),c=s>t.length;o.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ti=A("$ZodCheckStringFormat",(e,t)=>{var n,o;if(at.init(e,t),e._zod.onattach.push((r)=>{let s=r._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),Th=A("$ZodCheckRegex",(e,t)=>{ti.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Eh=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=yh),ti.init(e,t)}),Ih=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=xh),ti.init(e,t)}),Ah=A("$ZodCheckIncludes",(e,t)=>{at.init(e,t);let n=Ln(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=o,e._zod.onattach.push((r)=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),zh=A("$ZodCheckStartsWith",(e,t)=>{at.init(e,t);let n=new RegExp(`^${Ln(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Ph=A("$ZodCheckEndsWith",(e,t)=>{at.init(e,t);let n=new RegExp(`.*${Ln(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var Nh=A("$ZodCheckOverwrite",(e,t)=>{at.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Fl{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
112
+ `.substring(0,r);return n+s+o}function rk(e){return e!=null&&(typeof e==="string"||e.nodeType&&(e.nodeType===1||e.nodeType===9||e.nodeType===11))}function Rs(){let e=window.getSelection(),t=e&&e.rangeCount>0?e.getRangeAt(0).cloneRange():null;Yt("Link URL","https://example.com").then((n)=>{if(!n)return;let o=n.trim().toLowerCase();if(o.startsWith("javascript:")||o.startsWith("data:"))return;if(t){let r=window.getSelection();r?.removeAllRanges(),r?.addRange(t)}document.execCommand("createLink",!1,n)})}function xm(){let e=window.getSelection();if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(t.collapsed)return;let n=t.toString(),o=document.createElement("code");o.textContent=n,t.deleteContents(),t.insertNode(o);let r=document.createRange();r.setStartAfter(o),r.setEndAfter(o),e.removeAllRanges(),e.addRange(r)}var $s=8,ik=[{kind:"exec",command:"bold",icon:"B",title:`Bold (${Ze("B")})`},{kind:"exec",command:"italic",icon:"I",title:`Italic (${Ze("I")})`},{kind:"exec",command:"strikeThrough",icon:"S",title:"Strikethrough"},{kind:"code",icon:"{ }",title:"Inline code",dividerBefore:!0},{kind:"block",tag:"H1",icon:"H1",title:"Heading 1",dividerBefore:!0},{kind:"block",tag:"H2",icon:"H2",title:"Heading 2"},{kind:"block",tag:"H3",icon:"H3",title:"Heading 3"},{kind:"block",tag:"P",icon:"¶",title:"Paragraph"},{kind:"block",tag:"BLOCKQUOTE",icon:"❝",title:"Quote",dividerBefore:!0},{kind:"exec",command:"insertUnorderedList",icon:"•",title:"Bullet list"},{kind:"exec",command:"insertOrderedList",icon:"1.",title:"Numbered list"},{kind:"link",icon:"\uD83D\uDD17",title:`Link (${Ze("K")})`,dividerBefore:!0}];function sk(e){switch(e.kind){case"exec":document.execCommand(e.command);return;case"block":document.execCommand("formatBlock",!1,e.tag);return;case"code":xm();return;case"link":Rs();return}}function bm({hostRef:e,onChange:t}){let[n,o]=L(!1),[r,s]=L({top:0,left:0}),[a,c]=L(0),l=M(null),u=M(null),d=O(()=>{let f=e.current;if(!f){o(!1);return}let g=window.getSelection();if(!g||g.rangeCount===0||g.isCollapsed){o(!1);return}let y=g.getRangeAt(0);if(!f.contains(y.commonAncestorContainer)){o(!1);return}let x=y.getBoundingClientRect();if(x.width===0&&x.height===0){o(!1);return}let h=a||420,v=Math.max($s,Math.min(x.left+x.width/2-h/2,window.innerWidth-h-$s)),b=Math.max($s,x.top-$s-36);s({top:b,left:v}),o(!0)},[e,a]),p=O(()=>{if(u.current!==null)return;u.current=requestAnimationFrame(()=>{u.current=null,d()})},[d]);D(()=>(document.addEventListener("selectionchange",p),window.addEventListener("scroll",p,!0),window.addEventListener("resize",p),()=>{if(document.removeEventListener("selectionchange",p),window.removeEventListener("scroll",p,!0),window.removeEventListener("resize",p),u.current!==null)cancelAnimationFrame(u.current)}),[p]),Ui(()=>{if(!n)return;let f=l.current;if(!f)return;let g=f.getBoundingClientRect().width;if(g&&Math.abs(g-a)>1)c(g)},[n,a]);let m=O((f)=>{sk(f),t(),d()},[t,d]);if(!n)return null;return i("div",{ref:l,class:"md-inline-format-bar",style:{top:`${r.top}px`,left:`${r.left}px`},onMouseDown:(f)=>f.preventDefault(),children:ik.flatMap((f,g)=>{let y=i("button",{type:"button",class:"md-inline-format-btn",title:f.title,onClick:()=>m(f),children:f.icon},`btn-${g}`,!1,void 0,this);return f.dividerBefore?[i("span",{class:"md-inline-format-divider"},`div-${g}`,!1,void 0,this),y]:[y]})},void 0,!1,void 0,this)}var _l=null;function ak(){if(_l)return _l;let e=new qr({headingStyle:"atx",codeBlockStyle:"fenced",emDelimiter:"*",bulletListMarker:"-"});return e.use(wm.gfm),_l=e,e}function _m({initialHtml:e,className:t,onChange:n,onSave:o}){let r=M(null),s=M(e);D(()=>{let m=r.current;if(!m)return;m.innerHTML=s.current;for(let f of m.querySelectorAll('input[type="checkbox"][disabled]'))f.removeAttribute("disabled")},[]);let a=O(()=>{let m=r.current;if(!m)return"";return ak().turndown(m.innerHTML)},[]),c=O(()=>{n(a())},[n,a]),l=O(()=>{let m=r.current;if(!m||!m.isConnected||m.innerHTML==="")return;o?.(a())},[o,a]),u=O((m)=>{if(!(m.metaKey||m.ctrlKey))return;if(m.key==="s"){m.preventDefault(),l();return}if(m.key==="b"){m.preventDefault(),document.execCommand("bold"),c();return}if(m.key==="i"){m.preventDefault(),document.execCommand("italic"),c();return}if(m.key==="k")m.preventDefault(),Rs(),c()},[c,l]),d=O((m)=>{let f=m.target;if(f instanceof HTMLInputElement&&f.type==="checkbox")f.toggleAttribute("checked",f.checked),c()},[c]),p=O((m)=>{let f=m.clipboardData?.getData("text/plain");if(f==null)return;m.preventDefault(),document.execCommand("insertText",!1,f),c()},[c]);return i(ve,{children:[i("div",{ref:r,class:t,contentEditable:!0,spellcheck:!1,onInput:c,onKeyDown:u,onPaste:p,onClick:d,onBlur:l},void 0,!1,void 0,this),i(bm,{hostRef:r,onChange:c},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Sl({html:e,className:t,style:n,onTaskToggle:o}){let r=M(null),s=M(o);return s.current=o,D(()=>{let c=r.current;if(!c)return;if(c.replaceChildren(),!e)return;let l=document.createElement("template");if(l.innerHTML=e,c.append(l.content.cloneNode(!0)),s.current)for(let u of c.querySelectorAll('input[type="checkbox"][disabled]'))u.removeAttribute("disabled")},[e]),i("div",{ref:r,class:t,style:n,onClick:o?(c)=>{let l=s.current,u=r.current;if(!u||!l)return;let d=c.target,p=null;if(d instanceof HTMLInputElement&&d.type==="checkbox")p=d;else{let g=d.closest("li")?.querySelector(':scope > input[type="checkbox"]');if(g&&c.clientX<=g.getBoundingClientRect().right+6)p=g}if(!p)return;c.stopPropagation();let m=[...u.querySelectorAll('input[type="checkbox"]')].indexOf(p);if(m>=0)l(m)}:void 0},void 0,!1,void 0,this)}function ck(e,t){let n=-1;return e.replace(/^(\s*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\])/gm,(o,r,s,a)=>{if(n+=1,n!==t)return o;return`${r}${s===" "?"x":" "}${a}`})}function Ms({node:e,expanded:t=!1}){let n=e.data.path,[o,r]=L(""),[s,a]=L(""),[c,l]=L(!1),[u,d]=L(!1),[p,m]=L(!1),[f,g]=L(!1),y=M(null),x=M(null),h=M(""),v=M(null),b=e.data.reviewActive;D(()=>{let j=!1;return(async()=>{let E;if(n){let W=await Or(n);if(j)return;E=W.content}else if(e.data.content)E=e.data.content;else{l(!0);return}r(E);let B=await an(E);if(j)return;a(B),l(!0),oe(e.id,{content:E,rendered:B})})(),()=>{j=!0}},[n,e.id,e.data.content]);let z=O(async(j)=>{let E=j.target.value;r(E),g(!0);let B=await an(E);a(B)},[]),F=O(async(j)=>{if(!n){let B=await an(j);a(B),g(!1),oe(e.id,{content:j,rendered:B}),await it(e.id,{content:j,data:{rendered:B}});return}m(!0);let E=await Fp(n,j);if(m(!1),E.ok){let B=await an(j);a(B),g(!1),oe(e.id,{content:j,rendered:B,savedAt:E.updatedAt}),await it(e.id,{content:j,data:{rendered:B,savedAt:E.updatedAt}})}},[n,e.id]),_=O(async()=>{if(!f)return;await F(o)},[f,o,F]),k=O((j)=>{if((j.metaKey||j.ctrlKey)&&j.key==="s"){j.preventDefault(),_();return}let E=y.current;if(E&&Hf(j,E))return;if(E&&j.key==="Tab")j.preventDefault(),Zf(E,j.shiftKey)},[_]);v.current=F;let T=O((j)=>{if(r(j),g(!0),h.current=j,x.current!==null)window.clearTimeout(x.current);x.current=window.setTimeout(()=>{x.current=null,F(j)},800)},[F]),P=O((j)=>{if(r(j),h.current=j,x.current!==null)window.clearTimeout(x.current),x.current=null;F(j)},[F]);D(()=>()=>{if(x.current===null)return;window.clearTimeout(x.current),x.current=null;let j=v.current;if(j)j(h.current)},[e.id]);let Z=b?i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-ok-10)",color:"var(--c-ok)",borderBottom:"1px solid var(--c-ok-20)",textTransform:"uppercase",letterSpacing:"0.05em",fontWeight:600},children:"Review active"},void 0,!1,void 0,this):null;if(u&&t)return i("div",{class:"md-editor-expanded",onKeyDown:k,children:[i("div",{class:"md-editor-toolbar",children:[i("button",{type:"button",class:"md-toolbar-btn",onClick:()=>d(!1),children:"← Back to document"},void 0,!1,void 0,this),i("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[n&&i("span",{class:"md-toolbar-path",children:n.split("/").pop()},void 0,!1,void 0,this),i("button",{type:"button",class:`md-toolbar-btn${f?" md-toolbar-btn-primary":""}`,onClick:_,disabled:!f||p,children:p?"Saving…":f?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"md-editor-split",children:[i("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[i("textarea",{ref:y,value:o,onInput:z,spellcheck:!1},void 0,!1,void 0,this),i(ll,{textareaRef:y},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Sl,{html:s,className:"md-preview"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(u)return i("div",{class:"md-editor-split",style:{height:"100%"},onKeyDown:k,children:[i("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[i("textarea",{ref:y,value:o,onInput:z,spellcheck:!1},void 0,!1,void 0,this),i(ll,{textareaRef:y},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Sl,{html:s,className:"md-preview"},void 0,!1,void 0,this),i("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[i("button",{type:"button",onClick:()=>d(!1),style:{padding:"4px 10px",fontSize:"11px",background:"var(--c-input-bg)",border:"1px solid var(--c-line)",borderRadius:"6px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Document"},void 0,!1,void 0,this),i("button",{type:"button",onClick:_,disabled:!f||p,style:{padding:"4px 10px",fontSize:"11px",background:f?"var(--c-accent-25)":"var(--c-input-bg)",border:`1px solid ${f?"var(--c-accent)":"var(--c-line)"}`,borderRadius:"6px",color:f?"var(--c-text)":"var(--c-dim)",cursor:f?"pointer":"default"},children:p?"Saving…":f?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(t)return i("div",{style:{height:"100%",position:"relative"},children:[Z,i("div",{class:"md-reader",children:c?i(_m,{initialHtml:s||"<p><br></p>",className:"md-reader-content md-reader-editable",onChange:T,onSave:P},e.id,!1,void 0,this):i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"24px"},children:"Loading…"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"md-edit-fab",onClick:()=>d(!0),children:"</> Source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{style:{height:"100%",position:"relative"},children:[Z,i(Sl,{html:s,style:{padding:s?"0":"12px",color:s?void 0:"var(--c-dim)"},onTaskToggle:(j)=>{let E=ck(o,j);if(E!==o)P(E)}},void 0,!1,void 0,this),!c&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Loading…"},void 0,!1,void 0,this),c&&!s&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Empty node"},void 0,!1,void 0,this),i("button",{type:"button",class:"md-edit-btn",onClick:()=>en(e.id),children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Os="pmx-canvas-ax",Ls="pmx-canvas-ax-ack",Ot="pmx-canvas-html-node",Ds="pmx-canvas-ext-app-alive",kl="pmx-canvas-ext-app-paint-probe";function Sm(e,t){switch(e){case"html":return typeof t.html==="string"&&t.html.length>0||typeof t.content==="string"&&t.content.length>0;case"mermaid":return typeof t.content==="string"&&t.content.trim().length>0;case"json-render":case"graph":return!0;case"mcp-app":return t.viewerType==="web-artifact"&&typeof t.path==="string"&&t.path.length>0||typeof t.url==="string"&&t.url.length>0;case"webpage":return typeof t.url==="string"&&t.url.length>0;default:return!1}}var Cl="allow-scripts allow-popups allow-popups-to-escape-sandbox";function er(e){let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Vr(e,t={}){let n=new URLSearchParams;if(n.set("theme",t.theme??Xe.value),t.themeToken)n.set("themeToken",t.themeToken);if(t.present)n.set("present","1");if(t.presentToken)n.set("presentToken",t.presentToken);if(t.v)n.set("v",t.v);if(t.axToken)n.set("axToken",t.axToken);if(t.frameToken)n.set("frameToken",t.frameToken);return`/api/canvas/surface/${encodeURIComponent(e)}?${n.toString()}`}function Fs(e){return Sm(e.type,e.data)}async function js(e){let t=Vr(e.id);if(!(await Bp(e.id,t)).opened)window.open(t,"_blank","noopener")}var km=30000;var Tl=80;var Ve=V(new Map),nr=V(null),lk=480,uk=320,dk=650,Gr=new Map,tr=new Map,Zs=new Map,mn=null;function El(e){Ve.value=e,pk()}function Il(e){let t=Gr.get(e);if(t)clearTimeout(t),Gr.delete(e)}function Al(e){let t=tr.get(e);if(t)clearTimeout(t),tr.delete(e)}function Tm(e){if(Il(e.id),Al(e.id),!Ve.value.has(e.id))Zs.set(e.id,Date.now());let t=new Map(Ve.value);t.set(e.id,{...e,phase:"forming"}),El(t)}function Xr(e){if(Il(e),Al(e),Zs.delete(e),!Ve.value.has(e))return;let t=new Map(Ve.value);t.delete(e),El(t)}function Cm(e,t,n,o){let r=Ve.value.get(e);if(!r||r.phase===t)return;let s=new Map(Ve.value);s.set(e,{...r,phase:t,...o?{settledNodeId:o}:{}}),El(s),Il(e),Gr.set(e,setTimeout(()=>Xr(e),n))}function Em(e,t,n,o){Al(e);let r=Date.now()-(Zs.get(e)??0),s=Math.max(0,dk-r);if(s===0){Cm(e,t,n,o);return}tr.set(e,setTimeout(()=>{tr.delete(e),Cm(e,t,n,o)},s))}function Im(e,t){Em(e,"settling",lk,t)}function zl(e){Em(e,"dissolving",uk)}function Pl(){for(let e of Gr.values())clearTimeout(e);Gr.clear();for(let e of tr.values())clearTimeout(e);if(tr.clear(),Zs.clear(),mn)clearInterval(mn),mn=null;nr.value=null,Ve.value=new Map}function pk(){if(mn||Ve.value.size===0)return;mn=setInterval(()=>{let e=Date.now();for(let t of Ve.value.values())if(t.phase==="forming"&&t.expiresAt<=e)zl(t.id);if(Ve.value.size===0&&mn)clearInterval(mn),mn=null},1000),mn.unref?.()}function fk(e,t){try{let n=window.sessionStorage.getItem(e);if(n)return n;let o=t();return window.sessionStorage.setItem(e,o),o}catch{return t()}}var Us=fk("pmx-canvas-human-client",()=>`tab-${Math.random().toString(36).slice(2,8)}`);function mk(){try{let e=new URLSearchParams(window.location.search).get("name")?.trim();if(e)return window.localStorage.setItem("pmx-canvas-human-name",e),e;let t=window.localStorage.getItem("pmx-canvas-human-name")?.trim();if(t)return t}catch{}return`guest-${Us.slice(-4)}`}var zm=V(mk()),Pm=V([]),Jr=Oe(()=>Pm.value.filter((e)=>e.clientId!==Us)),fo=V(new Map);function Nl(e){if(!e||!Array.isArray(e.humans))return;Pm.value=e.humans}var or=V(null),Ws=null,Nm=0,Kr=null;function Bs(e){Bt("humanPresence","/api/canvas/human-presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:Us,name:zm.value,...e})})}function Am(){Kr=null,Nm=Date.now(),Bs({cursor:Ws,grabbingNodeId:or.value})}function qs(e){Ws=e;let t=Date.now()-Nm;if(t>=Tl){if(Kr)clearTimeout(Kr);Am()}else if(!Kr)Kr=setTimeout(Am,Tl-t)}function Rl(e){or.value=e,Bs({cursor:Ws,grabbingNodeId:e})}function hk(e,t){let n=new Map(fo.value);n.set(e,t),fo.value=n,setTimeout(()=>{let o=new Map(fo.value);if(o.get(e)===t)o.delete(e),fo.value=o},6000)}function Rm(e,t){let n=[...Ve.value.values()].filter((r)=>r.nodeId===e&&!r.auto&&r.phase==="forming");if(n.length===0)return;let o=zm.value;hk(e,o);for(let r of n)io({id:r.id,kind:r.kind,label:r.label,reason:`${o} took over “${t}” mid-edit — yield and requeue the change once it is released`}).then((s)=>{if(s)Xr(r.id)});Bt("yieldEvent","/api/canvas/ax/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"yield",summary:`${o} grabbed “${t}” mid-edit — agent yielded, change requeued`,nodeIds:[e],source:"browser"})})}var Hs=null;function $m(){Bs({cursor:Ws,grabbingNodeId:or.value}),Hs=setInterval(()=>Bs({grabbingNodeId:or.value}),3000);let e=()=>{try{navigator.sendBeacon?.("/api/canvas/human-presence",new Blob([JSON.stringify({clientId:Us,left:!0})],{type:"application/json"}))}catch{}};return window.addEventListener("pagehide",e),()=>{if(Hs)clearInterval(Hs);Hs=null,window.removeEventListener("pagehide",e)}}var gk={markdown:{width:360,height:180},context:{width:360,height:180},file:{width:360,height:200},diff:{width:420,height:240},mermaid:{width:360,height:240},status:{width:280,height:120},ledger:{width:320,height:200},image:{width:240,height:180},html:{width:420,height:280},webpage:{width:420,height:280},"json-render":{width:420,height:280},graph:{width:420,height:280},"mcp-app":{width:480,height:320}};function Mm(e){return gk[e]}function Om(e,t,n,o,r){return e.x<o.position.x+o.size.width+r&&e.x+t+r>o.position.x&&e.y<o.position.y+o.size.height+r&&e.y+n+r>o.position.y}function vk(e,t,n,o,r){return o.some((s)=>Om(e,t,n,s,r))}function Vs(e,t,n,o,r){return o.find((s)=>Om(e,t,n,s,r))}function Gs(e,t,n,o=24){if(e.length===0)return{x:40,y:80};let r=e[e.length-1],s={x:r.position.x+r.size.width+o,y:r.position.y};if(!vk(s,t,n,e,o))return s;let a=40,c=80,l=3000,u=c;for(let p=0;p<20;p++){let m=a;while(m+t<l){let y=Vs({x:m,y:u},t,n,e,o);if(!y)return{x:m,y:u};m=y.position.x+y.size.width+o}u=e.filter((y)=>y.position.y<=u+n+o&&y.position.y+y.size.height+o>u).reduce((y,x)=>Math.max(y,x.position.y+x.size.height),u)+o}let d=e.reduce((p,m)=>Math.max(p,m.position.y+m.size.height),0);return{x:a,y:d+o}}var rr=37,yk=600,xk=1400,bk=24;function wk(e){return e.type==="html"||e.type==="mermaid"||e.type==="json-render"||e.type==="graph"||e.type==="mcp-app"||e.type==="webpage"}function _k(e){if(e.type==="html")return e.data.presentation!==!0;if(e.type==="mermaid")return!0;if(e.type==="json-render"||e.type==="graph")return!0;if(e.type==="mcp-app")return e.data.viewerType==="web-artifact";return!1}function Lm(e){return e.collapsed===!0||e.data.strictSize===!0||e.data.userResized===!0||e.type==="group"}function $l(e){return!Lm(e)&&!wk(e)}function Dm(e,t){if(!$l(e)||t<=0)return null;let n=Math.min(t+rr,yk),o=Mm(e.type);return o?Math.max(n,o.height):n}function Ml(e){return _k(e)&&!Lm(e)}function Fm(e,t){if(!Ml(e)||!Number.isFinite(t)||t<=0)return null;let n=Math.min(t+rr+bk,xk);return n>e.size.height+8?n:null}function jm(e,t,n){if(t<=e.size.height||e.pinned||e.data.parentGroup)return e.position;let o=n.filter((a)=>a.id!==e.id&&!a.pinned&&a.type!=="group"),r={...e.position},s=Vs(r,e.size.width,t,o,24);while(s)r.y=s.position.y+s.size.height+24,s=Vs(r,e.size.width,t,o,24);return r}function ir(e,t,n){D(()=>{if(!n)return;let o=null,r=null,s=()=>or.value===e.id||Jr.value.some((d)=>d.grabbingNodeId===e.id);function a(){if(o=null,s()||r===null)return;let d=r;r=null;let p=R.value.get(e.id);if(!p)return;let m=Fm(p,d);if(m===null)return;let f=jm(p,m,Array.from(R.value.values())),g=f.x!==p.position.x||f.y!==p.position.y,y={size:{width:p.size.width,height:m},...g?{position:f}:{}};et(p.id,y),ss([{id:p.id,...y}],{recordHistory:g})}function c(){if(o!==null)clearTimeout(o);o=r!==null&&!s()?setTimeout(a,300):null}let l=Mt(()=>{s(),c()});function u(d){if(d.source!==t.current?.contentWindow)return;let p=d.data;if(!p||p.source!=="pmx-canvas-frame"||p.type!=="content-height"||p.token!==n)return;if(typeof p.height!=="number"||!Number.isFinite(p.height)||p.height<=0)return;r=p.height,c()}return window.addEventListener("message",u),()=>{if(window.removeEventListener("message",u),l(),o!==null)clearTimeout(o)}},[e.id,n])}function Sk(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function sr(e){let t=gt.value,[n,o]=L(null),r=Boolean(e)&&Sk(e),s=t==="srcdoc"&&r;if(D(()=>{if(!s)return;let a=!1;return fetch(`${e}${e.includes("?")?"&":"?"}inline-assets=1`,{credentials:"same-origin"}).then((c)=>c.ok?c.text():Promise.reject(Error(`HTTP ${c.status}`))).then((c)=>{if(!a)o({url:e,html:c})}).catch((c)=>{if(console.error("[surface-frame] srcdoc fetch failed, falling back to src:",e,c),!a)o({url:e,html:""})}),()=>{a=!0}},[s,e]),!e)return{};if(!s)return t===null&&r?{}:{src:e};if(n)return n.html?{srcdoc:n.html}:{src:n.url};return{}}function Xs({node:e,expanded:t=!1}){let n=M(null),o=Xe.value,r=Ae(()=>`theme-${crypto.randomUUID()}`,[]),s=Ae(()=>`frame-${crypto.randomUUID()}`,[]),a=typeof e.data.content==="string"?e.data.content:"",c=Ae(()=>er(a),[a]),l=Ae(()=>a?Vr(e.id,{theme:o,themeToken:r,v:c,frameToken:s}):"",[a,r,c,e.id,s]),u=sr(l);ir(e,n,t?"":s);let d=()=>{n.current?.contentWindow?.postMessage({source:Ot,type:"theme-update",token:r,theme:o},"*")};if(D(d,[o,r]),!a)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No diagram source set"},void 0,!1,void 0,this);return i("iframe",{ref:n,class:"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"Mermaid diagram",sandbox:"allow-scripts",...u,onLoad:d,style:{width:"100%",height:"100%",minHeight:t?"70vh":"300px",border:"none",background:"var(--c-bg)",borderRadius:"6px",display:"block"}},void 0,!1,void 0,this)}var Ol=["dark","light","high-contrast","midnight","sepia","arctic","ember","forest","volt"];function Yr(e){return typeof e==="string"&&Ol.includes(e)}function Ll(e,t="dark"){return Yr(e)?e:t}var ar={dark:{label:"Dark",scheme:"dark",swatchBg:"#081524",swatchAccent:"#4BBCFF"},light:{label:"Light",scheme:"light",swatchBg:"#F4EFE6",swatchAccent:"#1A7ABF"},"high-contrast":{label:"High contrast",scheme:"dark",swatchBg:"#000000",swatchAccent:"#00ffff"},midnight:{label:"Midnight",scheme:"dark",swatchBg:"#0A0D1C",swatchAccent:"#8B96FF"},sepia:{label:"Sepia",scheme:"light",swatchBg:"#F2E7D5",swatchAccent:"#B4632C"},arctic:{label:"Arctic",scheme:"dark",swatchBg:"#20242E",swatchAccent:"#7FC8DE"},ember:{label:"Ember",scheme:"dark",swatchBg:"#0B0B0C",swatchAccent:"#F34E1C"},forest:{label:"Forest",scheme:"dark",swatchBg:"#0C1712",swatchAccent:"#5CCF8F"},volt:{label:"Volt",scheme:"dark",swatchBg:"#0B0D0B",swatchAccent:"#DFDFC1"}};function cr(e){return ar[Ll(e)].scheme}var RP=Object.freeze({status:"aborted"});function A(e,t,n){function o(c,l){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:l,constr:a,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);let u=a.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){let m=d[p];if(!(m in c))c[m]=u[m].bind(c)}}let r=n?.Parent??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function a(c){var l;let u=n?.Parent?new s:this;o(u,c),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:(c)=>{if(n?.Parent&&c instanceof n.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}var $P=Symbol("zod_brand");class hn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Qr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}var Ks={};function Lt(e){if(e)Object.assign(Ks,e);return Ks}function Ys(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,r])=>t.indexOf(+o)===-1).map(([o,r])=>r)}function Fl(e,t="|"){return e.map((n)=>Bl(n)).join(t)}function ei(e,t){if(typeof t==="bigint")return t.toString();return t}function ti(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Qs(e){return e===null||e===void 0}function ea(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Hm(e,t){let n=(e.toString().split(".")[1]||"").length,o=t.toString(),r=(o.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(o)){let l=o.match(/\d?e-(\d?)/);if(l?.[1])r=Number.parseInt(l[1])}let s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),c=Number.parseInt(t.toFixed(s).replace(".",""));return a%c/10**s}var Zm=Symbol("evaluating");function be(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===Zm)return;if(o===void 0)o=Zm,o=n();return o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function mo(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function On(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function jl(e){return JSON.stringify(e)}function Bm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Zl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function lr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Um=ti(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function ho(e){if(lr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(lr(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Hl(e){if(ho(e))return{...e};if(Array.isArray(e))return[...e];return e}var Wm=new Set(["string","number","symbol"]);function Ln(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nn(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function X(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Bl(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function qm(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Vm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function kk(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=On(e._zod.def,{get shape(){let a={};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;a[c]=n.shape[c]}return mo(this,"shape",a),a},checks:[]});return nn(e,s)}function Ck(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=On(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let c in t){if(!(c in n.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete a[c]}return mo(this,"shape",a),a},checks:[]});return nn(e,s)}function Tk(e,t){if(!ho(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let s=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=On(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return mo(this,"shape",s),s}});return nn(e,r)}function Ek(e,t){if(!ho(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=On(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return mo(this,"shape",o),o}});return nn(e,n)}function Ik(e,t){let n=On(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return mo(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return nn(e,n)}function Ak(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=On(t._zod.def,{get shape(){let c=t._zod.def.shape,l={...c};if(n)for(let u in n){if(!(u in c))throw Error(`Unrecognized key: "${u}"`);if(!n[u])continue;l[u]=e?new e({type:"optional",innerType:c[u]}):c[u]}else for(let u in c)l[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return mo(this,"shape",l),l},checks:[]});return nn(t,a)}function zk(e,t,n){let o=On(t._zod.def,{get shape(){let r=t._zod.def.shape,s={...r};if(n)for(let a in n){if(!(a in s))throw Error(`Unrecognized key: "${a}"`);if(!n[a])continue;s[a]=new e({type:"nonoptional",innerType:r[a]})}else for(let a in r)s[a]=new e({type:"nonoptional",innerType:r[a]});return mo(this,"shape",s),s}});return nn(t,o)}function go(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Dn(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Js(e){return typeof e==="string"?e:e?.message}function on(e,t,n){let o={...e,path:e.path??[]};if(!e.message){let r=Js(e.inst?._zod.def?.error?.(e))??Js(t?.error?.(e))??Js(n.customError?.(e))??Js(n.localeError?.(e))??"Invalid input";o.message=r}if(delete o.inst,delete o.continue,!t?.reportInput)delete o.input;return o}function ta(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Gm(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function vo(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}var Xm=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ei,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},na=A("$ZodError",Xm),Ul=A("$ZodError",Xm,{Parent:Error});function Km(e,t=(n)=>n.message){let n={},o=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else o.push(t(r));return{formErrors:o,fieldErrors:n}}function Jm(e,t=(n)=>n.message){let n={_errors:[]},o=(r)=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let a=n,c=0;while(c<s.path.length){let l=s.path[c];if(c!==s.path.length-1)a[l]=a[l]||{_errors:[]};else a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(s));a=a[l],c++}}};return o(e),n}var oa=(e)=>(t,n,o,r)=>{let s=o?Object.assign(o,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new hn;if(a.issues.length){let c=new(r?.Err??e)(a.issues.map((l)=>on(l,s,Lt())));throw Zl(c,r?.callee),c}return a.value};var ra=(e)=>async(t,n,o,r)=>{let s=o?Object.assign(o,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(r?.Err??e)(a.issues.map((l)=>on(l,s,Lt())));throw Zl(c,r?.callee),c}return a.value};var ni=(e)=>(t,n,o)=>{let r=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new hn;return s.issues.length?{success:!1,error:new(e??na)(s.issues.map((a)=>on(a,r,Lt())))}:{success:!0,data:s.value}},oi=ni(Ul),ri=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>on(a,r,Lt())))}:{success:!0,data:s.value}},ia=ri(Ul),Ym=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return oa(e)(t,n,r)};var Qm=(e)=>(t,n,o)=>oa(e)(t,n,o);var eh=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ra(e)(t,n,r)};var th=(e)=>async(t,n,o)=>ra(e)(t,n,o);var nh=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ni(e)(t,n,r)};var oh=(e)=>(t,n,o)=>ni(e)(t,n,o);var rh=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ri(e)(t,n,r)};var ih=(e)=>async(t,n,o)=>ri(e)(t,n,o);var sh=/^[cC][^\s-]{8,}$/,ah=/^[0-9a-z]+$/,ch=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lh=/^[0-9a-vA-V]{20}$/,uh=/^[A-Za-z0-9]{27}$/,dh=/^[a-zA-Z0-9_-]{21}$/,ph=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var fh=/^([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})$/,Wl=(e)=>{if(!e)return/^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return 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})$`)};var mh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Nk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hh(){return new RegExp(Nk,"u")}var gh=/^(?:(?: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])$/,vh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var yh=/^((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])$/,xh=/^(([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])$/,bh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ql=/^[A-Za-z0-9_-]*$/;var wh=/^\+[1-9]\d{6,14}$/,_h="(?:(?:\\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])))",Sh=new RegExp(`^${_h}$`);function kh(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Ch(e){return new RegExp(`^${kh(e)}$`)}function Th(e){let t=kh({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${n.join("|")})`;return new RegExp(`^${_h}T(?:${o})$`)}var Eh=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ih=/^-?\d+$/,Vl=/^-?\d+(?:\.\d+)?$/,Ah=/^(?:true|false)$/i,zh=/^null$/i;var Ph=/^undefined$/i;var Nh=/^[^A-Z]*$/,Rh=/^[^a-z]*$/;var at=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),$h={number:"number",bigint:"bigint",object:"date"},Gl=A("$ZodCheckLessThan",(e,t)=>{at.init(e,t);let n=$h[typeof t.value];e._zod.onattach.push((o)=>{let r=o._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xl=A("$ZodCheckGreaterThan",(e,t)=>{at.init(e,t);let n=$h[typeof t.value];e._zod.onattach.push((o)=>{let r=o._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mh=A("$ZodCheckMultipleOf",(e,t)=>{at.init(e,t),e._zod.onattach.push((n)=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):Hm(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Oh=A("$ZodCheckNumberFormat",(e,t)=>{at.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[r,s]=Vm[t.format];e._zod.onattach.push((a)=>{let c=a._zod.bag;if(c.format=t.format,c.minimum=r,c.maximum=s,n)c.pattern=Ih}),e._zod.check=(a)=>{let c=a.value;if(n){if(!Number.isInteger(c)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(c<r)a.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(c>s)a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Lh=A("$ZodCheckMaxLength",(e,t)=>{var n;at.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Qs(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let r=o.value;if(r.length<=t.maximum)return;let a=ta(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Dh=A("$ZodCheckMinLength",(e,t)=>{var n;at.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Qs(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let r=o.value;if(r.length>=t.minimum)return;let a=ta(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Fh=A("$ZodCheckLengthEquals",(e,t)=>{var n;at.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Qs(r)&&r.length!==void 0}),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(o)=>{let r=o.value,s=r.length;if(s===t.length)return;let a=ta(r),c=s>t.length;o.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ii=A("$ZodCheckStringFormat",(e,t)=>{var n,o;if(at.init(e,t),e._zod.onattach.push((r)=>{let s=r._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),jh=A("$ZodCheckRegex",(e,t)=>{ii.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Zh=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Nh),ii.init(e,t)}),Hh=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Rh),ii.init(e,t)}),Bh=A("$ZodCheckIncludes",(e,t)=>{at.init(e,t);let n=Ln(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=o,e._zod.onattach.push((r)=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Uh=A("$ZodCheckStartsWith",(e,t)=>{at.init(e,t);let n=new RegExp(`^${Ln(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Wh=A("$ZodCheckEndsWith",(e,t)=>{at.init(e,t);let n=new RegExp(`.*${Ln(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var qh=A("$ZodCheckOverwrite",(e,t)=>{at.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Kl{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
113
113
  `).filter((s)=>s),o=Math.min(...n.map((s)=>s.length-s.trimStart().length)),r=n.map((s)=>s.slice(o)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of r)this.content.push(s)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((r)=>` ${r}`)];return new e(...t,o.join(`
114
- `))}}var $h={major:4,minor:3,patch:6};var $e=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=$h;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let r of o)for(let s of r._zod.onattach)s(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(a,c,l)=>{let u=ho(a),d;for(let p of c){if(p._zod.def.when){if(!p._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,f=p._zod.check(a);if(f instanceof Promise&&l?.async===!1)throw new mn;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await f,a.issues.length===m)return;if(!u)u=ho(a,m)});else{if(a.issues.length===m)continue;if(!u)u=ho(a,m)}}if(d)return d.then(()=>a);return a},s=(a,c,l)=>{if(ho(a))return a.aborted=!0,a;let u=r(c,o,l);if(u instanceof Promise){if(l.async===!1)throw new mn;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,a,c));return s(u,a,c)}let l=e._zod.parse(a,c);if(l instanceof Promise){if(c.async===!1)throw new mn;return l.then((u)=>r(u,o,c))}return r(l,o,c)}}be(e,"~standard",()=>({validate:(r)=>{try{let s=Qr(e,r);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Gs(e,r).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Ys=A("$ZodString",(e,t)=>{$e.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??fh(e._zod.bag),e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Le=A("$ZodStringFormat",(e,t)=>{ti.init(e,t),Ys.init(e,t)}),Bh=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Qm),Le.init(e,t)}),Uh=A("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=$l(o))}else t.pattern??(t.pattern=$l());Le.init(e,t)}),Wh=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=eh),Le.init(e,t)}),qh=A("$ZodURL",(e,t)=>{Le.init(e,t),e._zod.check=(n)=>{try{let o=n.value.trim(),r=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=o;return}catch(o){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Vh=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=th()),Le.init(e,t)}),Gh=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Jm),Le.init(e,t)}),Xh=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=qm),Le.init(e,t)}),Kh=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Vm),Le.init(e,t)}),Jh=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Gm),Le.init(e,t)}),Yh=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Xm),Le.init(e,t)}),Qh=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Km),Le.init(e,t)}),eg=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ph(t)),Le.init(e,t)}),tg=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=lh),Le.init(e,t)}),ng=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=dh(t)),Le.init(e,t)}),og=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ym),Le.init(e,t)}),rg=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=nh),Le.init(e,t),e._zod.bag.format="ipv4"}),ig=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=oh),Le.init(e,t),e._zod.bag.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})}}});var sg=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=rh),Le.init(e,t)}),ag=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ih),Le.init(e,t),e._zod.check=(n)=>{let o=n.value.split("/");try{if(o.length!==2)throw Error();let[r,s]=o;if(!s)throw Error();let a=Number(s);if(`${a}`!==s)throw Error();if(a<0||a>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function cg(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var lg=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=sh),Le.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(cg(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Ck(e){if(!Ml.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return cg(n)}var ug=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ml),Le.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(Ck(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),dg=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ah),Le.init(e,t)});function Tk(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let r=JSON.parse(atob(o));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var pg=A("$ZodJWT",(e,t)=>{Le.init(e,t),e._zod.check=(n)=>{if(Tk(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Zl=A("$ZodNumber",(e,t)=>{$e.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ol,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let s=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),fg=A("$ZodNumberFormat",(e,t)=>{_h.init(e,t),Zl.init(e,t)}),mg=A("$ZodBoolean",(e,t)=>{$e.init(e,t),e._zod.pattern=hh,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}});var hg=A("$ZodUndefined",(e,t)=>{$e.init(e,t),e._zod.pattern=vh,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,o)=>{let r=n.value;if(typeof r>"u")return n;return n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),gg=A("$ZodNull",(e,t)=>{$e.init(e,t),e._zod.pattern=gh,e._zod.values=new Set([null]),e._zod.parse=(n,o)=>{let r=n.value;if(r===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}});var vg=A("$ZodUnknown",(e,t)=>{$e.init(e,t),e._zod.parse=(n)=>n}),yg=A("$ZodNever",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Mh(e,t,n){if(e.issues.length)t.issues.push(...Dn(n,e.issues));t.value[n]=e.value}var xg=A("$ZodArray",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=t.element._zod.run({value:c,issues:[]},o);if(l instanceof Promise)s.push(l.then((u)=>Mh(u,n,a)));else Mh(l,n,a)}if(s.length)return Promise.all(s).then(()=>n);return n}});function Js(e,t,n,o,r){if(e.issues.length){if(r&&!(n in o))return;t.issues.push(...Dn(n,e.issues))}if(e.value===void 0){if(n in o)t.value[n]=void 0}else t.value[n]=e.value}function bg(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let n=Nm(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function wg(e,t,n,o,r,s){let a=[],c=r.keySet,l=r.catchall._zod,u=l.def.type,d=l.optout==="optional";for(let p in t){if(c.has(p))continue;if(u==="never"){a.push(p);continue}let m=l.run({value:t[p],issues:[]},o);if(m instanceof Promise)e.push(m.then((f)=>Js(f,n,p,t,d)));else Js(m,n,p,t,d)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Ek=A("$ZodObject",(e,t)=>{if($e.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=Jr(()=>bg(t));be(e._zod,"propValues",()=>{let c=t.shape,l={};for(let u in c){let d=c[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let p of d.values)l[u].add(p)}}return l});let r=ar,s=t.catchall,a;e._zod.parse=(c,l)=>{a??(a=o.value);let u=c.value;if(!r(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};let d=[],p=a.shape;for(let m of a.keys){let f=p[m],g=f._zod.optout==="optional",y=f._zod.run({value:u[m],issues:[]},l);if(y instanceof Promise)d.push(y.then((x)=>Js(x,c,m,u,g)));else Js(y,c,m,u,g)}if(!s)return d.length?Promise.all(d).then(()=>c):c;return wg(d,u,c,l,o.value,e)}}),_g=A("$ZodObjectJIT",(e,t)=>{Ek.init(e,t);let n=e._zod.parse,o=Jr(()=>bg(t)),r=(m)=>{let f=new Fl(["shape","payload","ctx"]),g=o.value,y=(b)=>{let z=Al(b);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};f.write("const input = payload.value;");let x=Object.create(null),h=0;for(let b of g.keys)x[b]=`key_${h++}`;f.write("const newResult = {};");for(let b of g.keys){let z=x[b],F=Al(b),k=m[b]?._zod?.optout==="optional";if(f.write(`const ${z} = ${y(b)};`),k)f.write(`
114
+ `))}}var Gh={major:4,minor:3,patch:6};var $e=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Gh;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let r of o)for(let s of r._zod.onattach)s(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(a,c,l)=>{let u=go(a),d;for(let p of c){if(p._zod.def.when){if(!p._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,f=p._zod.check(a);if(f instanceof Promise&&l?.async===!1)throw new hn;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await f,a.issues.length===m)return;if(!u)u=go(a,m)});else{if(a.issues.length===m)continue;if(!u)u=go(a,m)}}if(d)return d.then(()=>a);return a},s=(a,c,l)=>{if(go(a))return a.aborted=!0,a;let u=r(c,o,l);if(u instanceof Promise){if(l.async===!1)throw new hn;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,a,c));return s(u,a,c)}let l=e._zod.parse(a,c);if(l instanceof Promise){if(c.async===!1)throw new hn;return l.then((u)=>r(u,o,c))}return r(l,o,c)}}be(e,"~standard",()=>({validate:(r)=>{try{let s=oi(e,r);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return ia(e,r).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),la=A("$ZodString",(e,t)=>{$e.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Eh(e._zod.bag),e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Le=A("$ZodStringFormat",(e,t)=>{ii.init(e,t),la.init(e,t)}),og=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fh),Le.init(e,t)}),rg=A("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Wl(o))}else t.pattern??(t.pattern=Wl());Le.init(e,t)}),ig=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=mh),Le.init(e,t)}),sg=A("$ZodURL",(e,t)=>{Le.init(e,t),e._zod.check=(n)=>{try{let o=n.value.trim(),r=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=o;return}catch(o){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ag=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=hh()),Le.init(e,t)}),cg=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=dh),Le.init(e,t)}),lg=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=sh),Le.init(e,t)}),ug=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ah),Le.init(e,t)}),dg=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ch),Le.init(e,t)}),pg=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=lh),Le.init(e,t)}),fg=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=uh),Le.init(e,t)}),mg=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Th(t)),Le.init(e,t)}),hg=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Sh),Le.init(e,t)}),gg=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ch(t)),Le.init(e,t)}),vg=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ph),Le.init(e,t)}),yg=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=gh),Le.init(e,t),e._zod.bag.format="ipv4"}),xg=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vh),Le.init(e,t),e._zod.bag.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})}}});var bg=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=yh),Le.init(e,t)}),wg=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=xh),Le.init(e,t),e._zod.check=(n)=>{let o=n.value.split("/");try{if(o.length!==2)throw Error();let[r,s]=o;if(!s)throw Error();let a=Number(s);if(`${a}`!==s)throw Error();if(a<0||a>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function _g(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Sg=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=bh),Le.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(_g(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Mk(e){if(!ql.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return _g(n)}var kg=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ql),Le.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(Mk(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Cg=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=wh),Le.init(e,t)});function Ok(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let r=JSON.parse(atob(o));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var Tg=A("$ZodJWT",(e,t)=>{Le.init(e,t),e._zod.check=(n)=>{if(Ok(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Yl=A("$ZodNumber",(e,t)=>{$e.init(e,t),e._zod.pattern=e._zod.bag.pattern??Vl,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let s=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),Eg=A("$ZodNumberFormat",(e,t)=>{Oh.init(e,t),Yl.init(e,t)}),Ig=A("$ZodBoolean",(e,t)=>{$e.init(e,t),e._zod.pattern=Ah,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}});var Ag=A("$ZodUndefined",(e,t)=>{$e.init(e,t),e._zod.pattern=Ph,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,o)=>{let r=n.value;if(typeof r>"u")return n;return n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),zg=A("$ZodNull",(e,t)=>{$e.init(e,t),e._zod.pattern=zh,e._zod.values=new Set([null]),e._zod.parse=(n,o)=>{let r=n.value;if(r===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}});var Pg=A("$ZodUnknown",(e,t)=>{$e.init(e,t),e._zod.parse=(n)=>n}),Ng=A("$ZodNever",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Xh(e,t,n){if(e.issues.length)t.issues.push(...Dn(n,e.issues));t.value[n]=e.value}var Rg=A("$ZodArray",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=t.element._zod.run({value:c,issues:[]},o);if(l instanceof Promise)s.push(l.then((u)=>Xh(u,n,a)));else Xh(l,n,a)}if(s.length)return Promise.all(s).then(()=>n);return n}});function ca(e,t,n,o,r){if(e.issues.length){if(r&&!(n in o))return;t.issues.push(...Dn(n,e.issues))}if(e.value===void 0){if(n in o)t.value[n]=void 0}else t.value[n]=e.value}function $g(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let n=qm(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Mg(e,t,n,o,r,s){let a=[],c=r.keySet,l=r.catchall._zod,u=l.def.type,d=l.optout==="optional";for(let p in t){if(c.has(p))continue;if(u==="never"){a.push(p);continue}let m=l.run({value:t[p],issues:[]},o);if(m instanceof Promise)e.push(m.then((f)=>ca(f,n,p,t,d)));else ca(m,n,p,t,d)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Lk=A("$ZodObject",(e,t)=>{if($e.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=ti(()=>$g(t));be(e._zod,"propValues",()=>{let c=t.shape,l={};for(let u in c){let d=c[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let p of d.values)l[u].add(p)}}return l});let r=lr,s=t.catchall,a;e._zod.parse=(c,l)=>{a??(a=o.value);let u=c.value;if(!r(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};let d=[],p=a.shape;for(let m of a.keys){let f=p[m],g=f._zod.optout==="optional",y=f._zod.run({value:u[m],issues:[]},l);if(y instanceof Promise)d.push(y.then((x)=>ca(x,c,m,u,g)));else ca(y,c,m,u,g)}if(!s)return d.length?Promise.all(d).then(()=>c):c;return Mg(d,u,c,l,o.value,e)}}),Og=A("$ZodObjectJIT",(e,t)=>{Lk.init(e,t);let n=e._zod.parse,o=ti(()=>$g(t)),r=(m)=>{let f=new Kl(["shape","payload","ctx"]),g=o.value,y=(b)=>{let z=jl(b);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};f.write("const input = payload.value;");let x=Object.create(null),h=0;for(let b of g.keys)x[b]=`key_${h++}`;f.write("const newResult = {};");for(let b of g.keys){let z=x[b],F=jl(b),k=m[b]?._zod?.optout==="optional";if(f.write(`const ${z} = ${y(b)};`),k)f.write(`
115
115
  if (${z}.issues.length) {
116
116
  if (${F} in input) {
117
117
  payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
@@ -145,15 +145,15 @@ ${r}
145
145
  newResult[${F}] = ${z}.value;
146
146
  }
147
147
 
148
- `)}f.write("payload.value = newResult;"),f.write("return payload;");let v=f.compile();return(b,z)=>v(m,b,z)},s,a=ar,c=!Fs.jitless,u=c&&zm.value,d=t.catchall,p;e._zod.parse=(m,f)=>{p??(p=o.value);let g=m.value;if(!a(g))return m.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),m;if(c&&u&&f?.async===!1&&f.jitless!==!0){if(!s)s=r(t.shape);if(m=s(m,f),!d)return m;return wg([],g,m,f,p,e)}return n(m,f)}});function Oh(e,t,n,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let r=e.filter((s)=>!ho(s));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((a)=>on(a,o,Ot())))}),t}var Hl=A("$ZodUnion",(e,t)=>{$e.init(e,t),be(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),be(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),be(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),be(e._zod,"pattern",()=>{if(t.options.every((r)=>r._zod.pattern)){let r=t.options.map((s)=>s._zod.pattern);return new RegExp(`^(${r.map((s)=>Bs(s.source)).join("|")})$`)}return});let n=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(r,s)=>{if(n)return o(r,s);let a=!1,c=[];for(let l of t.options){let u=l._zod.run({value:r.value,issues:[]},s);if(u instanceof Promise)c.push(u),a=!0;else{if(u.issues.length===0)return u;c.push(u)}}if(!a)return Oh(c,r,e,s);return Promise.all(c).then((l)=>Oh(l,r,e,s))}});var Sg=A("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Hl.init(e,t);let n=e._zod.parse;be(e._zod,"propValues",()=>{let r={};for(let s of t.options){let a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[c,l]of Object.entries(a)){if(!r[c])r[c]=new Set;for(let u of l)r[c].add(u)}}return r});let o=Jr(()=>{let r=t.options,s=new Map;for(let a of r){let c=a._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let l of c){if(s.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(r,s)=>{let a=r.value;if(!ar(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;let c=o.value.get(a?.[t.discriminator]);if(c)return c._zod.run(r,s);if(t.unionFallback)return n(r,s);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),r}}),kg=A("$ZodIntersection",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{let r=n.value,s=t.left._zod.run({value:r,issues:[]},o),a=t.right._zod.run({value:r,issues:[]},o);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([l,u])=>Lh(n,l,u));return Lh(n,s,a)}});function jl(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(mo(e)&&mo(t)){let n=Object.keys(t),o=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),r={...e,...t};for(let s of o){let a=jl(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r[s]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let o=0;o<e.length;o++){let r=e[o],s=t[o],a=jl(r,s);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Lh(e,t,n){let o=new Map,r;for(let c of t.issues)if(c.code==="unrecognized_keys"){r??(r=c);for(let l of c.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(c);for(let c of n.issues)if(c.code==="unrecognized_keys")for(let l of c.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(c);let s=[...o].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&r)e.issues.push({...r,keys:s});if(ho(e))return e;let a=jl(t.value,n.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Cg=A("$ZodRecord",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{let r=n.value;if(!mo(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a){n.value={};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){c.add(typeof u==="number"?u.toString():u);let d=t.valueType._zod.run({value:r[u],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Dn(u,p.issues));n.value[u]=p.value}));else{if(d.issues.length)n.issues.push(...Dn(u,d.issues));n.value[u]=d.value}}let l;for(let u in r)if(!c.has(u))l=l??[],l.push(u);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:l})}else{n.value={};for(let c of Reflect.ownKeys(r)){if(c==="__proto__")continue;let l=t.keyType._zod.run({value:c,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&Ol.test(c)&&l.issues.length){let p=t.keyType._zod.run({value:Number(c),issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)l=p}if(l.issues.length){if(t.mode==="loose")n.value[c]=r[c];else n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((p)=>on(p,o,Ot())),input:c,path:[c],inst:e});continue}let d=t.valueType._zod.run({value:r[c],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Dn(c,p.issues));n.value[l.value]=p.value}));else{if(d.issues.length)n.issues.push(...Dn(c,d.issues));n.value[l.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var Tg=A("$ZodEnum",(e,t)=>{$e.init(e,t);let n=Zs(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Pm.has(typeof r)).map((r)=>typeof r==="string"?Ln(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{let a=r.value;if(o.has(a))return r;return r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),Eg=A("$ZodLiteral",(e,t)=>{if($e.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Ln(o):o?Ln(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,r)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});var Ig=A("$ZodTransform",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Xr(e.constructor.name);let r=t.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then((a)=>(n.value=a,n));if(r instanceof Promise)throw new mn;return n.value=r,n}});function Dh(e,t){if(e.issues.length&&t===void 0)return{issues:[],value:void 0};return e}var Bl=A("$ZodOptional",(e,t)=>{$e.init(e,t),e._zod.optin="optional",e._zod.optout="optional",be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),be(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bs(n.source)})?$`):void 0}),e._zod.parse=(n,o)=>{if(t.innerType._zod.optin==="optional"){let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Dh(s,n.value));return Dh(r,n.value)}if(n.value===void 0)return n;return t.innerType._zod.run(n,o)}}),Ag=A("$ZodExactOptional",(e,t)=>{Bl.init(e,t),be(e._zod,"values",()=>t.innerType._zod.values),be(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),zg=A("$ZodNullable",(e,t)=>{$e.init(e,t),be(e._zod,"optin",()=>t.innerType._zod.optin),be(e._zod,"optout",()=>t.innerType._zod.optout),be(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bs(n.source)}|null)$`):void 0}),be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,o)=>{if(n.value===null)return n;return t.innerType._zod.run(n,o)}}),Pg=A("$ZodDefault",(e,t)=>{$e.init(e,t),e._zod.optin="optional",be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Fh(s,t));return Fh(r,t)}});function Fh(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Ng=A("$ZodPrefault",(e,t)=>{$e.init(e,t),e._zod.optin="optional",be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,o)}}),Rg=A("$ZodNonOptional",(e,t)=>{$e.init(e,t),be(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,o)=>{let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>jh(s,e));return jh(r,e)}});function jh(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var $g=A("$ZodCatch",(e,t)=>{$e.init(e,t),be(e._zod,"optin",()=>t.innerType._zod.optin),be(e._zod,"optout",()=>t.innerType._zod.optout),be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>{if(n.value=s.value,s.issues.length)n.value=t.catchValue({...n,error:{issues:s.issues.map((a)=>on(a,o,Ot()))},input:n.value}),n.issues=[];return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((s)=>on(s,o,Ot()))},input:n.value}),n.issues=[];return n}});var Mg=A("$ZodPipe",(e,t)=>{$e.init(e,t),be(e._zod,"values",()=>t.in._zod.values),be(e._zod,"optin",()=>t.in._zod.optin),be(e._zod,"optout",()=>t.out._zod.optout),be(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(n,o);if(s instanceof Promise)return s.then((a)=>Ks(a,t.in,o));return Ks(s,t.in,o)}let r=t.in._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Ks(s,t.out,o));return Ks(r,t.out,o)}});function Ks(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var Og=A("$ZodReadonly",(e,t)=>{$e.init(e,t),be(e._zod,"propValues",()=>t.innerType._zod.propValues),be(e._zod,"values",()=>t.innerType._zod.values),be(e._zod,"optin",()=>t.innerType?._zod?.optin),be(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then(Zh);return Zh(r)}});function Zh(e){return e.value=Object.freeze(e.value),e}var Lg=A("$ZodCustom",(e,t)=>{at.init(e,t),$e.init(e,t),e._zod.parse=(n,o)=>n,e._zod.check=(n)=>{let o=n.value,r=t.fn(o);if(r instanceof Promise)return r.then((s)=>Hh(s,n,o,e));Hh(r,n,o,e);return}});function Hh(e,t,n,o){if(!e){let r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)r.params=o._zod.def.params;t.issues.push(go(r))}}var Ik=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(r){return e[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(r)=>{switch(r.code){case"invalid_type":{let s=o[r.expected]??r.expected,a=$m(r.input),c=o[a]??a;return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":if(r.values.length===1)return`Invalid input: expected ${Nl(r.values[0])}`;return`Invalid option: expected one of ${Il(r.values,"|")}`;case"too_big":{let s=r.inclusive?"<=":"<",a=t(r.origin);if(a)return`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{let s=r.inclusive?">=":">",a=t(r.origin);if(a)return`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${a.unit}`;return`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{let s=r;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Il(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Ul(){return{localeError:Ik()}}var Dg,LP=Symbol("ZodOutput"),DP=Symbol("ZodInput");class Fg{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Ak(){return new Fg}(Dg=globalThis).__zod_globalRegistry??(Dg.__zod_globalRegistry=Ak());var vo=globalThis.__zod_globalRegistry;function jg(e,t){return new e({type:"string",...X(t)})}function Zg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...X(t)})}function Wl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...X(t)})}function Hg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...X(t)})}function Bg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(t)})}function Ug(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(t)})}function Wg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(t)})}function qg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...X(t)})}function Vg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...X(t)})}function Gg(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(t)})}function Xg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...X(t)})}function Kg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(t)})}function Jg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...X(t)})}function Yg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...X(t)})}function Qg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(t)})}function ev(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(t)})}function tv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(t)})}function nv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(t)})}function ov(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(t)})}function rv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...X(t)})}function iv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...X(t)})}function sv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...X(t)})}function av(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...X(t)})}function cv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(t)})}function lv(e,t){return new e({type:"string",format:"date",check:"string_format",...X(t)})}function uv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...X(t)})}function dv(e,t){return new e({type:"string",format:"duration",check:"string_format",...X(t)})}function pv(e,t){return new e({type:"number",checks:[],...X(t)})}function fv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...X(t)})}function mv(e,t){return new e({type:"boolean",...X(t)})}function hv(e,t){return new e({type:"undefined",...X(t)})}function gv(e,t){return new e({type:"null",...X(t)})}function vv(e){return new e({type:"unknown"})}function yv(e,t){return new e({type:"never",...X(t)})}function Qs(e,t){return new Ll({check:"less_than",...X(t),value:e,inclusive:!1})}function ni(e,t){return new Ll({check:"less_than",...X(t),value:e,inclusive:!0})}function ea(e,t){return new Dl({check:"greater_than",...X(t),value:e,inclusive:!1})}function oi(e,t){return new Dl({check:"greater_than",...X(t),value:e,inclusive:!0})}function ta(e,t){return new wh({check:"multiple_of",...X(t),value:e})}function na(e,t){return new Sh({check:"max_length",...X(t),maximum:e})}function cr(e,t){return new kh({check:"min_length",...X(t),minimum:e})}function oa(e,t){return new Ch({check:"length_equals",...X(t),length:e})}function ql(e,t){return new Th({check:"string_format",format:"regex",...X(t),pattern:e})}function Vl(e){return new Eh({check:"string_format",format:"lowercase",...X(e)})}function Gl(e){return new Ih({check:"string_format",format:"uppercase",...X(e)})}function Xl(e,t){return new Ah({check:"string_format",format:"includes",...X(t),includes:e})}function Kl(e,t){return new zh({check:"string_format",format:"starts_with",...X(t),prefix:e})}function Jl(e,t){return new Ph({check:"string_format",format:"ends_with",...X(t),suffix:e})}function Fn(e){return new Nh({check:"overwrite",tx:e})}function Yl(e){return Fn((t)=>t.normalize(e))}function Ql(){return Fn((e)=>e.trim())}function eu(){return Fn((e)=>e.toLowerCase())}function tu(){return Fn((e)=>e.toUpperCase())}function nu(){return Fn((e)=>Am(e))}function xv(e,t,n){return new e({type:"array",element:t,...X(n)})}function bv(e,t,n){let o=X(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function wv(e,t,n){return new e({type:"custom",check:"custom",fn:t,...X(n)})}function _v(e){let t=zk((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(go(o,n.value,t._zod.def));else{let r=o;if(r.fatal)r.continue=!1;r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(go(r))}},e(n.value,n)));return t}function zk(e,t){let n=new at({check:"custom",...X(t)});return n._zod.check=e,n}function ou(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??vo,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Ke(e,t,n={path:[],schemaPath:[]}){var o;let r=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let m=a.schema,f=t.processors[r.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);f(e,t,m,d)}let p=e._zod.parent;if(p){if(!a.ref)a.ref=p;Ke(p,t,d),t.seen.get(p).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(a.schema,l);if(t.io==="input"&&xt(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&a.schema._prefault)(o=a.schema).default??(o.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function ru(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let a of e.seen.entries()){let c=e.metadataRegistry.get(a[0])?.id;if(c){let l=o.get(c);if(l&&l!==a[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(c,a[0])}}let r=(a)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,m=e.external.uri??((g)=>g);if(p)return{ref:m(p)};let f=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=f,{defId:f,ref:`${m("__shared")}#/${c}/${f}`}}if(a[1]===n)return{ref:"#"};let u=`${"#"}/${c}/`,d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(a)=>{if(a[1].schema.$ref)return;let c=a[1],{ref:l,defId:u}=r(a);if(c.def={...c.schema},u)c.defId=u;let d=c.schema;for(let p in d)delete d[p];d.$ref=l};if(e.cycles==="throw")for(let a of e.seen.entries()){let c=a[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
148
+ `)}f.write("payload.value = newResult;"),f.write("return payload;");let v=f.compile();return(b,z)=>v(m,b,z)},s,a=lr,c=!Ks.jitless,u=c&&Um.value,d=t.catchall,p;e._zod.parse=(m,f)=>{p??(p=o.value);let g=m.value;if(!a(g))return m.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),m;if(c&&u&&f?.async===!1&&f.jitless!==!0){if(!s)s=r(t.shape);if(m=s(m,f),!d)return m;return Mg([],g,m,f,p,e)}return n(m,f)}});function Kh(e,t,n,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let r=e.filter((s)=>!go(s));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((a)=>on(a,o,Lt())))}),t}var Ql=A("$ZodUnion",(e,t)=>{$e.init(e,t),be(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),be(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),be(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),be(e._zod,"pattern",()=>{if(t.options.every((r)=>r._zod.pattern)){let r=t.options.map((s)=>s._zod.pattern);return new RegExp(`^(${r.map((s)=>ea(s.source)).join("|")})$`)}return});let n=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(r,s)=>{if(n)return o(r,s);let a=!1,c=[];for(let l of t.options){let u=l._zod.run({value:r.value,issues:[]},s);if(u instanceof Promise)c.push(u),a=!0;else{if(u.issues.length===0)return u;c.push(u)}}if(!a)return Kh(c,r,e,s);return Promise.all(c).then((l)=>Kh(l,r,e,s))}});var Lg=A("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ql.init(e,t);let n=e._zod.parse;be(e._zod,"propValues",()=>{let r={};for(let s of t.options){let a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[c,l]of Object.entries(a)){if(!r[c])r[c]=new Set;for(let u of l)r[c].add(u)}}return r});let o=ti(()=>{let r=t.options,s=new Map;for(let a of r){let c=a._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let l of c){if(s.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(r,s)=>{let a=r.value;if(!lr(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;let c=o.value.get(a?.[t.discriminator]);if(c)return c._zod.run(r,s);if(t.unionFallback)return n(r,s);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),r}}),Dg=A("$ZodIntersection",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{let r=n.value,s=t.left._zod.run({value:r,issues:[]},o),a=t.right._zod.run({value:r,issues:[]},o);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([l,u])=>Jh(n,l,u));return Jh(n,s,a)}});function Jl(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(ho(e)&&ho(t)){let n=Object.keys(t),o=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),r={...e,...t};for(let s of o){let a=Jl(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r[s]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let o=0;o<e.length;o++){let r=e[o],s=t[o],a=Jl(r,s);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Jh(e,t,n){let o=new Map,r;for(let c of t.issues)if(c.code==="unrecognized_keys"){r??(r=c);for(let l of c.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(c);for(let c of n.issues)if(c.code==="unrecognized_keys")for(let l of c.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(c);let s=[...o].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&r)e.issues.push({...r,keys:s});if(go(e))return e;let a=Jl(t.value,n.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Fg=A("$ZodRecord",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{let r=n.value;if(!ho(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a){n.value={};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){c.add(typeof u==="number"?u.toString():u);let d=t.valueType._zod.run({value:r[u],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Dn(u,p.issues));n.value[u]=p.value}));else{if(d.issues.length)n.issues.push(...Dn(u,d.issues));n.value[u]=d.value}}let l;for(let u in r)if(!c.has(u))l=l??[],l.push(u);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:l})}else{n.value={};for(let c of Reflect.ownKeys(r)){if(c==="__proto__")continue;let l=t.keyType._zod.run({value:c,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&Vl.test(c)&&l.issues.length){let p=t.keyType._zod.run({value:Number(c),issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)l=p}if(l.issues.length){if(t.mode==="loose")n.value[c]=r[c];else n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((p)=>on(p,o,Lt())),input:c,path:[c],inst:e});continue}let d=t.valueType._zod.run({value:r[c],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Dn(c,p.issues));n.value[l.value]=p.value}));else{if(d.issues.length)n.issues.push(...Dn(c,d.issues));n.value[l.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var jg=A("$ZodEnum",(e,t)=>{$e.init(e,t);let n=Ys(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Wm.has(typeof r)).map((r)=>typeof r==="string"?Ln(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{let a=r.value;if(o.has(a))return r;return r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),Zg=A("$ZodLiteral",(e,t)=>{if($e.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Ln(o):o?Ln(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,r)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});var Hg=A("$ZodTransform",(e,t)=>{$e.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Qr(e.constructor.name);let r=t.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then((a)=>(n.value=a,n));if(r instanceof Promise)throw new hn;return n.value=r,n}});function Yh(e,t){if(e.issues.length&&t===void 0)return{issues:[],value:void 0};return e}var eu=A("$ZodOptional",(e,t)=>{$e.init(e,t),e._zod.optin="optional",e._zod.optout="optional",be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),be(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${ea(n.source)})?$`):void 0}),e._zod.parse=(n,o)=>{if(t.innerType._zod.optin==="optional"){let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Yh(s,n.value));return Yh(r,n.value)}if(n.value===void 0)return n;return t.innerType._zod.run(n,o)}}),Bg=A("$ZodExactOptional",(e,t)=>{eu.init(e,t),be(e._zod,"values",()=>t.innerType._zod.values),be(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),Ug=A("$ZodNullable",(e,t)=>{$e.init(e,t),be(e._zod,"optin",()=>t.innerType._zod.optin),be(e._zod,"optout",()=>t.innerType._zod.optout),be(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${ea(n.source)}|null)$`):void 0}),be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,o)=>{if(n.value===null)return n;return t.innerType._zod.run(n,o)}}),Wg=A("$ZodDefault",(e,t)=>{$e.init(e,t),e._zod.optin="optional",be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Qh(s,t));return Qh(r,t)}});function Qh(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var qg=A("$ZodPrefault",(e,t)=>{$e.init(e,t),e._zod.optin="optional",be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,o)}}),Vg=A("$ZodNonOptional",(e,t)=>{$e.init(e,t),be(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,o)=>{let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>eg(s,e));return eg(r,e)}});function eg(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var Gg=A("$ZodCatch",(e,t)=>{$e.init(e,t),be(e._zod,"optin",()=>t.innerType._zod.optin),be(e._zod,"optout",()=>t.innerType._zod.optout),be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>{if(n.value=s.value,s.issues.length)n.value=t.catchValue({...n,error:{issues:s.issues.map((a)=>on(a,o,Lt()))},input:n.value}),n.issues=[];return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((s)=>on(s,o,Lt()))},input:n.value}),n.issues=[];return n}});var Xg=A("$ZodPipe",(e,t)=>{$e.init(e,t),be(e._zod,"values",()=>t.in._zod.values),be(e._zod,"optin",()=>t.in._zod.optin),be(e._zod,"optout",()=>t.out._zod.optout),be(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,o)=>{if(o.direction==="backward"){let s=t.out._zod.run(n,o);if(s instanceof Promise)return s.then((a)=>aa(a,t.in,o));return aa(s,t.in,o)}let r=t.in._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>aa(s,t.out,o));return aa(r,t.out,o)}});function aa(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var Kg=A("$ZodReadonly",(e,t)=>{$e.init(e,t),be(e._zod,"propValues",()=>t.innerType._zod.propValues),be(e._zod,"values",()=>t.innerType._zod.values),be(e._zod,"optin",()=>t.innerType?._zod?.optin),be(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let r=t.innerType._zod.run(n,o);if(r instanceof Promise)return r.then(tg);return tg(r)}});function tg(e){return e.value=Object.freeze(e.value),e}var Jg=A("$ZodCustom",(e,t)=>{at.init(e,t),$e.init(e,t),e._zod.parse=(n,o)=>n,e._zod.check=(n)=>{let o=n.value,r=t.fn(o);if(r instanceof Promise)return r.then((s)=>ng(s,n,o,e));ng(r,n,o,e);return}});function ng(e,t,n,o){if(!e){let r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)r.params=o._zod.def.params;t.issues.push(vo(r))}}var Dk=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(r){return e[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(r)=>{switch(r.code){case"invalid_type":{let s=o[r.expected]??r.expected,a=Gm(r.input),c=o[a]??a;return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":if(r.values.length===1)return`Invalid input: expected ${Bl(r.values[0])}`;return`Invalid option: expected one of ${Fl(r.values,"|")}`;case"too_big":{let s=r.inclusive?"<=":"<",a=t(r.origin);if(a)return`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{let s=r.inclusive?">=":">",a=t(r.origin);if(a)return`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${a.unit}`;return`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{let s=r;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Fl(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function tu(){return{localeError:Dk()}}var Yg,JP=Symbol("ZodOutput"),YP=Symbol("ZodInput");class Qg{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Fk(){return new Qg}(Yg=globalThis).__zod_globalRegistry??(Yg.__zod_globalRegistry=Fk());var yo=globalThis.__zod_globalRegistry;function ev(e,t){return new e({type:"string",...X(t)})}function tv(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...X(t)})}function nu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...X(t)})}function nv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...X(t)})}function ov(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(t)})}function rv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(t)})}function iv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(t)})}function sv(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...X(t)})}function av(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...X(t)})}function cv(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(t)})}function lv(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...X(t)})}function uv(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(t)})}function dv(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...X(t)})}function pv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...X(t)})}function fv(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(t)})}function mv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(t)})}function hv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(t)})}function gv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(t)})}function vv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(t)})}function yv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...X(t)})}function xv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...X(t)})}function bv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...X(t)})}function wv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...X(t)})}function _v(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(t)})}function Sv(e,t){return new e({type:"string",format:"date",check:"string_format",...X(t)})}function kv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...X(t)})}function Cv(e,t){return new e({type:"string",format:"duration",check:"string_format",...X(t)})}function Tv(e,t){return new e({type:"number",checks:[],...X(t)})}function Ev(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...X(t)})}function Iv(e,t){return new e({type:"boolean",...X(t)})}function Av(e,t){return new e({type:"undefined",...X(t)})}function zv(e,t){return new e({type:"null",...X(t)})}function Pv(e){return new e({type:"unknown"})}function Nv(e,t){return new e({type:"never",...X(t)})}function ua(e,t){return new Gl({check:"less_than",...X(t),value:e,inclusive:!1})}function si(e,t){return new Gl({check:"less_than",...X(t),value:e,inclusive:!0})}function da(e,t){return new Xl({check:"greater_than",...X(t),value:e,inclusive:!1})}function ai(e,t){return new Xl({check:"greater_than",...X(t),value:e,inclusive:!0})}function pa(e,t){return new Mh({check:"multiple_of",...X(t),value:e})}function fa(e,t){return new Lh({check:"max_length",...X(t),maximum:e})}function ur(e,t){return new Dh({check:"min_length",...X(t),minimum:e})}function ma(e,t){return new Fh({check:"length_equals",...X(t),length:e})}function ou(e,t){return new jh({check:"string_format",format:"regex",...X(t),pattern:e})}function ru(e){return new Zh({check:"string_format",format:"lowercase",...X(e)})}function iu(e){return new Hh({check:"string_format",format:"uppercase",...X(e)})}function su(e,t){return new Bh({check:"string_format",format:"includes",...X(t),includes:e})}function au(e,t){return new Uh({check:"string_format",format:"starts_with",...X(t),prefix:e})}function cu(e,t){return new Wh({check:"string_format",format:"ends_with",...X(t),suffix:e})}function Fn(e){return new qh({check:"overwrite",tx:e})}function lu(e){return Fn((t)=>t.normalize(e))}function uu(){return Fn((e)=>e.trim())}function du(){return Fn((e)=>e.toLowerCase())}function pu(){return Fn((e)=>e.toUpperCase())}function fu(){return Fn((e)=>Bm(e))}function Rv(e,t,n){return new e({type:"array",element:t,...X(n)})}function $v(e,t,n){let o=X(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Mv(e,t,n){return new e({type:"custom",check:"custom",fn:t,...X(n)})}function Ov(e){let t=jk((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(vo(o,n.value,t._zod.def));else{let r=o;if(r.fatal)r.continue=!1;r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(vo(r))}},e(n.value,n)));return t}function jk(e,t){let n=new at({check:"custom",...X(t)});return n._zod.check=e,n}function mu(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??yo,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Ke(e,t,n={path:[],schemaPath:[]}){var o;let r=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let m=a.schema,f=t.processors[r.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);f(e,t,m,d)}let p=e._zod.parent;if(p){if(!a.ref)a.ref=p;Ke(p,t,d),t.seen.get(p).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(a.schema,l);if(t.io==="input"&&xt(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&a.schema._prefault)(o=a.schema).default??(o.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function hu(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let a of e.seen.entries()){let c=e.metadataRegistry.get(a[0])?.id;if(c){let l=o.get(c);if(l&&l!==a[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(c,a[0])}}let r=(a)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,m=e.external.uri??((g)=>g);if(p)return{ref:m(p)};let f=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=f,{defId:f,ref:`${m("__shared")}#/${c}/${f}`}}if(a[1]===n)return{ref:"#"};let u=`${"#"}/${c}/`,d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(a)=>{if(a[1].schema.$ref)return;let c=a[1],{ref:l,defId:u}=r(a);if(c.def={...c.schema},u)c.defId=u;let d=c.schema;for(let p in d)delete d[p];d.$ref=l};if(e.cycles==="throw")for(let a of e.seen.entries()){let c=a[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
149
149
 
150
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let c=a[1];if(t===a[0]){s(a);continue}if(e.external){let u=e.external.registry.get(a[0])?.id;if(t!==a[0]&&u){s(a);continue}}if(e.metadataRegistry.get(a[0])?.id){s(a);continue}if(c.cycle){s(a);continue}if(c.count>1){if(e.reused==="ref"){s(a);continue}}}}function iu(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){o(d);let m=e.seen.get(d),f=m.schema;if(f.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(f);else Object.assign(l,f);if(Object.assign(l,u),a._zod.parent===d)for(let y in l){if(y==="$ref"||y==="allOf")continue;if(!(y in u))delete l[y]}if(f.$ref&&m.def)for(let y in l){if(y==="$ref"||y==="allOf")continue;if(y in m.def&&JSON.stringify(l[y])===JSON.stringify(m.def[y]))delete l[y]}}let p=a._zod.parent;if(p&&p!==d){o(p);let m=e.seen.get(p);if(m?.schema.$ref){if(l.$ref=m.schema.$ref,m.def)for(let f in l){if(f==="$ref"||f==="allOf")continue;if(f in m.def&&JSON.stringify(l[f])===JSON.stringify(m.def[f]))delete l[f]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let s=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId)s[c.defId]=c.def}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")r.$defs=s;else r.definitions=s;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ri(t,"input",e.processors),output:ri(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function xt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return xt(o.element,n);if(o.type==="set")return xt(o.valueType,n);if(o.type==="lazy")return xt(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return xt(o.innerType,n);if(o.type==="intersection")return xt(o.left,n)||xt(o.right,n);if(o.type==="record"||o.type==="map")return xt(o.keyType,n)||xt(o.valueType,n);if(o.type==="pipe")return xt(o.in,n)||xt(o.out,n);if(o.type==="object"){for(let r in o.shape)if(xt(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(let r of o.options)if(xt(r,n))return!0;return!1}if(o.type==="tuple"){for(let r of o.items)if(xt(r,n))return!0;if(o.rest&&xt(o.rest,n))return!0;return!1}return!1}var Sv=(e,t={})=>(n)=>{let o=ou({...n,processors:t});return Ke(e,o),ru(o,e),iu(o,e)},ri=(e,t,n={})=>(o)=>{let{libraryOptions:r,target:s}=o??{},a=ou({...r??{},target:s,io:t,processors:n});return Ke(e,a),ru(a,e),iu(a,e)};var Pk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},kv=(e,t,n,o)=>{let r=n;r.type="string";let{minimum:s,maximum:a,format:c,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s==="number")r.minLength=s;if(typeof a==="number")r.maxLength=a;if(c){if(r.format=Pk[c]??c,r.format==="")delete r.format;if(c==="time")delete r.format}if(u)r.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Cv=(e,t,n,o)=>{let r=n,{minimum:s,maximum:a,format:c,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))r.type="integer";else r.type="number";if(typeof d==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")r.minimum=d,r.exclusiveMinimum=!0;else r.exclusiveMinimum=d;if(typeof s==="number"){if(r.minimum=s,typeof d==="number"&&t.target!=="draft-04")if(d>=s)delete r.minimum;else delete r.exclusiveMinimum}if(typeof u==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")r.maximum=u,r.exclusiveMaximum=!0;else r.exclusiveMaximum=u;if(typeof a==="number"){if(r.maximum=a,typeof u==="number"&&t.target!=="draft-04")if(u<=a)delete r.maximum;else delete r.exclusiveMaximum}if(typeof l==="number")r.multipleOf=l},Tv=(e,t,n,o)=>{n.type="boolean"};var Ev=(e,t,n,o)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Iv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")};var Av=(e,t,n,o)=>{n.not={}};var zv=(e,t,n,o)=>{};var Pv=(e,t,n,o)=>{let r=e._zod.def,s=Zs(r.entries);if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";n.enum=s},Nv=(e,t,n,o)=>{let r=e._zod.def,s=[];for(let a of r.values)if(a===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(a));else s.push(a);if(s.length===0);else if(s.length===1){let a=s[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";if(s.every((a)=>typeof a==="boolean"))n.type="boolean";if(s.every((a)=>a===null))n.type="null";n.enum=s}};var Rv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var $v=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Mv=(e,t,n,o)=>{let r=n,s=e._zod.def,{minimum:a,maximum:c}=e._zod.bag;if(typeof a==="number")r.minItems=a;if(typeof c==="number")r.maxItems=c;r.type="array",r.items=Ke(s.element,t,{...o,path:[...o.path,"items"]})},Ov=(e,t,n,o)=>{let r=n,s=e._zod.def;r.type="object",r.properties={};let a=s.shape;for(let u in a)r.properties[u]=Ke(a[u],t,{...o,path:[...o.path,"properties",u]});let c=new Set(Object.keys(a)),l=new Set([...c].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)r.required=Array.from(l);if(s.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")r.additionalProperties=!1}else if(s.catchall)r.additionalProperties=Ke(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Lv=(e,t,n,o)=>{let r=e._zod.def,s=r.inclusive===!1,a=r.options.map((c,l)=>Ke(c,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)n.oneOf=a;else n.anyOf=a},Dv=(e,t,n,o)=>{let r=e._zod.def,s=Ke(r.left,t,{...o,path:[...o.path,"allOf",0]}),a=Ke(r.right,t,{...o,path:[...o.path,"allOf",1]}),c=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...c(s)?s.allOf:[s],...c(a)?a.allOf:[a]];n.allOf=l};var Fv=(e,t,n,o)=>{let r=n,s=e._zod.def;r.type="object";let a=s.keyType,l=a._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=Ke(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let p of l)r.patternProperties[p.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=Ke(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});r.additionalProperties=Ke(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values;if(u){let d=[...u].filter((p)=>typeof p==="string"||typeof p==="number");if(d.length>0)r.required=d}},jv=(e,t,n,o)=>{let r=e._zod.def,s=Ke(r.innerType,t,o),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=r.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},Zv=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType},Hv=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Bv=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);if(s.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},Uv=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},Wv=(e,t,n,o)=>{let r=e._zod.def,s=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;Ke(s,t,o);let a=t.seen.get(e);a.ref=s},qv=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var su=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType};var Fk=A("ZodISODateTime",(e,t)=>{eg.init(e,t),He.init(e,t)});function au(e){return cv(Fk,e)}var jk=A("ZodISODate",(e,t)=>{tg.init(e,t),He.init(e,t)});function Vv(e){return lv(jk,e)}var Zk=A("ZodISOTime",(e,t)=>{ng.init(e,t),He.init(e,t)});function Gv(e){return uv(Zk,e)}var Hk=A("ZodISODuration",(e,t)=>{og.init(e,t),He.init(e,t)});function Xv(e){return dv(Hk,e)}var Kv=(e,t)=>{Ws.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Lm(e,n)},flatten:{value:(n)=>Om(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Kr,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Kr,2)}},isEmpty:{get(){return e.issues.length===0}}})},mN=A("ZodError",Kv),At=A("ZodError",Kv,{Parent:Error});var Jv=qs(At),Yv=Vs(At),Qv=Yr(At),ey=ei(At),ty=Dm(At),ny=Fm(At),oy=jm(At),ry=Zm(At),iy=Hm(At),sy=Bm(At),ay=Um(At),cy=Wm(At);var De=A("ZodType",(e,t)=>($e.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ri(e,"input"),output:ri(e,"output")}}),e.toJSONSchema=Sv(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(On(t,{checks:[...t.checks??[],...n.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0}),e.with=e.check,e.clone=(n,o)=>nn(e,n,o),e.brand=()=>e,e.register=(n,o)=>(n.add(e,o),e),e.parse=(n,o)=>Jv(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>Qv(e,n,o),e.parseAsync=async(n,o)=>Yv(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>ey(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>ty(e,n,o),e.decode=(n,o)=>ny(e,n,o),e.encodeAsync=async(n,o)=>oy(e,n,o),e.decodeAsync=async(n,o)=>ry(e,n,o),e.safeEncode=(n,o)=>iy(e,n,o),e.safeDecode=(n,o)=>sy(e,n,o),e.safeEncodeAsync=async(n,o)=>ay(e,n,o),e.safeDecodeAsync=async(n,o)=>cy(e,n,o),e.refine=(n,o)=>e.check(M0(n,o)),e.superRefine=(n)=>e.check(O0(n)),e.overwrite=(n)=>e.check(Fn(n)),e.optional=()=>Ue(e),e.exactOptional=()=>S0(e),e.nullable=()=>dy(e),e.nullish=()=>Ue(dy(e)),e.nonoptional=(n)=>A0(e,n),e.array=()=>ie(e),e.or=(n)=>ue([e,n]),e.and=(n)=>ia(e,n),e.transform=(n)=>uu(e,gy(n)),e.default=(n)=>T0(e,n),e.prefault=(n)=>I0(e,n),e.catch=(n)=>P0(e,n),e.pipe=(n)=>uu(e,n),e.readonly=()=>$0(e),e.describe=(n)=>{let o=e.clone();return vo.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return vo.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return vo.get(e);let o=e.clone();return vo.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),py=A("_ZodString",(e,t)=>{Ys.init(e,t),De.init(e,t),e._zod.processJSONSchema=(o,r,s)=>kv(e,o,r,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...o)=>e.check(ql(...o)),e.includes=(...o)=>e.check(Xl(...o)),e.startsWith=(...o)=>e.check(Kl(...o)),e.endsWith=(...o)=>e.check(Jl(...o)),e.min=(...o)=>e.check(cr(...o)),e.max=(...o)=>e.check(na(...o)),e.length=(...o)=>e.check(oa(...o)),e.nonempty=(...o)=>e.check(cr(1,...o)),e.lowercase=(o)=>e.check(Vl(o)),e.uppercase=(o)=>e.check(Gl(o)),e.trim=()=>e.check(Ql()),e.normalize=(...o)=>e.check(Yl(...o)),e.toLowerCase=()=>e.check(eu()),e.toUpperCase=()=>e.check(tu()),e.slugify=()=>e.check(nu())}),Wk=A("ZodString",(e,t)=>{Ys.init(e,t),py.init(e,t),e.email=(n)=>e.check(Zg(qk,n)),e.url=(n)=>e.check(qg(Vk,n)),e.jwt=(n)=>e.check(av(c0,n)),e.emoji=(n)=>e.check(Vg(Gk,n)),e.guid=(n)=>e.check(Wl(ly,n)),e.uuid=(n)=>e.check(Hg(ra,n)),e.uuidv4=(n)=>e.check(Bg(ra,n)),e.uuidv6=(n)=>e.check(Ug(ra,n)),e.uuidv7=(n)=>e.check(Wg(ra,n)),e.nanoid=(n)=>e.check(Gg(Xk,n)),e.guid=(n)=>e.check(Wl(ly,n)),e.cuid=(n)=>e.check(Xg(Kk,n)),e.cuid2=(n)=>e.check(Kg(Jk,n)),e.ulid=(n)=>e.check(Jg(Yk,n)),e.base64=(n)=>e.check(rv(i0,n)),e.base64url=(n)=>e.check(iv(s0,n)),e.xid=(n)=>e.check(Yg(Qk,n)),e.ksuid=(n)=>e.check(Qg(e0,n)),e.ipv4=(n)=>e.check(ev(t0,n)),e.ipv6=(n)=>e.check(tv(n0,n)),e.cidrv4=(n)=>e.check(nv(o0,n)),e.cidrv6=(n)=>e.check(ov(r0,n)),e.e164=(n)=>e.check(sv(a0,n)),e.datetime=(n)=>e.check(au(n)),e.date=(n)=>e.check(Vv(n)),e.time=(n)=>e.check(Gv(n)),e.duration=(n)=>e.check(Xv(n))});function S(e){return jg(Wk,e)}var He=A("ZodStringFormat",(e,t)=>{Le.init(e,t),py.init(e,t)}),qk=A("ZodEmail",(e,t)=>{Wh.init(e,t),He.init(e,t)});var ly=A("ZodGUID",(e,t)=>{Bh.init(e,t),He.init(e,t)});var ra=A("ZodUUID",(e,t)=>{Uh.init(e,t),He.init(e,t)});var Vk=A("ZodURL",(e,t)=>{qh.init(e,t),He.init(e,t)});var Gk=A("ZodEmoji",(e,t)=>{Vh.init(e,t),He.init(e,t)});var Xk=A("ZodNanoID",(e,t)=>{Gh.init(e,t),He.init(e,t)});var Kk=A("ZodCUID",(e,t)=>{Xh.init(e,t),He.init(e,t)});var Jk=A("ZodCUID2",(e,t)=>{Kh.init(e,t),He.init(e,t)});var Yk=A("ZodULID",(e,t)=>{Jh.init(e,t),He.init(e,t)});var Qk=A("ZodXID",(e,t)=>{Yh.init(e,t),He.init(e,t)});var e0=A("ZodKSUID",(e,t)=>{Qh.init(e,t),He.init(e,t)});var t0=A("ZodIPv4",(e,t)=>{rg.init(e,t),He.init(e,t)});var n0=A("ZodIPv6",(e,t)=>{ig.init(e,t),He.init(e,t)});var o0=A("ZodCIDRv4",(e,t)=>{sg.init(e,t),He.init(e,t)});var r0=A("ZodCIDRv6",(e,t)=>{ag.init(e,t),He.init(e,t)});var i0=A("ZodBase64",(e,t)=>{lg.init(e,t),He.init(e,t)});var s0=A("ZodBase64URL",(e,t)=>{ug.init(e,t),He.init(e,t)});var a0=A("ZodE164",(e,t)=>{dg.init(e,t),He.init(e,t)});var c0=A("ZodJWT",(e,t)=>{pg.init(e,t),He.init(e,t)});var fy=A("ZodNumber",(e,t)=>{Zl.init(e,t),De.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Cv(e,o,r,s),e.gt=(o,r)=>e.check(ea(o,r)),e.gte=(o,r)=>e.check(oi(o,r)),e.min=(o,r)=>e.check(oi(o,r)),e.lt=(o,r)=>e.check(Qs(o,r)),e.lte=(o,r)=>e.check(ni(o,r)),e.max=(o,r)=>e.check(ni(o,r)),e.int=(o)=>e.check(uy(o)),e.safe=(o)=>e.check(uy(o)),e.positive=(o)=>e.check(ea(0,o)),e.nonnegative=(o)=>e.check(oi(0,o)),e.negative=(o)=>e.check(Qs(0,o)),e.nonpositive=(o)=>e.check(ni(0,o)),e.multipleOf=(o,r)=>e.check(ta(o,r)),e.step=(o,r)=>e.check(ta(o,r)),e.finite=()=>e;let 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??0.5),e.isFinite=!0,e.format=n.format??null});function ce(e){return pv(fy,e)}var l0=A("ZodNumberFormat",(e,t)=>{fg.init(e,t),fy.init(e,t)});function uy(e){return fv(l0,e)}var u0=A("ZodBoolean",(e,t)=>{mg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Tv(e,n,o,r)});function ze(e){return mv(u0,e)}var d0=A("ZodUndefined",(e,t)=>{hg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Iv(e,n,o,r)});function du(e){return hv(d0,e)}var p0=A("ZodNull",(e,t)=>{gg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ev(e,n,o,r)});function pu(e){return gv(p0,e)}var f0=A("ZodUnknown",(e,t)=>{vg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>zv(e,n,o,r)});function Ie(){return vv(f0)}var m0=A("ZodNever",(e,t)=>{yg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Av(e,n,o,r)});function h0(e){return yv(m0,e)}var g0=A("ZodArray",(e,t)=>{xg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Mv(e,n,o,r),e.element=t.element,e.min=(n,o)=>e.check(cr(n,o)),e.nonempty=(n)=>e.check(cr(1,n)),e.max=(n,o)=>e.check(na(n,o)),e.length=(n,o)=>e.check(oa(n,o)),e.unwrap=()=>e.element});function ie(e,t){return xv(g0,e,t)}var my=A("ZodObject",(e,t)=>{_g.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ov(e,n,o,r),be(e,"shape",()=>t.shape),e.keyof=()=>St(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ie()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ie()}),e.strict=()=>e.clone({...e._zod.def,catchall:h0()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>gk(e,n),e.safeExtend=(n)=>vk(e,n),e.merge=(n)=>yk(e,n),e.pick=(n)=>mk(e,n),e.omit=(n)=>hk(e,n),e.partial=(...n)=>xk(vy,e,n[0]),e.required=(...n)=>bk(yy,e,n[0])});function C(e,t){let n={type:"object",shape:e??{},...X(t)};return new my(n)}function bt(e,t){return new my({type:"object",shape:e,catchall:Ie(),...X(t)})}var hy=A("ZodUnion",(e,t)=>{Hl.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Lv(e,n,o,r),e.options=t.options});function ue(e,t){return new hy({type:"union",options:e,...X(t)})}var v0=A("ZodDiscriminatedUnion",(e,t)=>{hy.init(e,t),Sg.init(e,t)});function fu(e,t,n){return new v0({type:"union",options:t,discriminator:e,...X(n)})}var y0=A("ZodIntersection",(e,t)=>{kg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Dv(e,n,o,r)});function ia(e,t){return new y0({type:"intersection",left:e,right:t})}var x0=A("ZodRecord",(e,t)=>{Cg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Fv(e,n,o,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ce(e,t,n){return new x0({type:"record",keyType:e,valueType:t,...X(n)})}var lu=A("ZodEnum",(e,t)=>{Tg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Pv(e,o,r,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(o,r)=>{let s={};for(let a of o)if(n.has(a))s[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new lu({...t,checks:[],...X(r),entries:s})},e.exclude=(o,r)=>{let s={...t.entries};for(let a of o)if(n.has(a))delete s[a];else throw Error(`Key ${a} not found in enum`);return new lu({...t,checks:[],...X(r),entries:s})}});function St(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new lu({type:"enum",entries:n,...X(t)})}var b0=A("ZodLiteral",(e,t)=>{Eg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Nv(e,n,o,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function w(e,t){return new b0({type:"literal",values:Array.isArray(e)?e:[e],...X(t)})}var w0=A("ZodTransform",(e,t)=>{Ig.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>$v(e,n,o,r),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Xr(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(go(s,n.value,t));else{let a=s;if(a.fatal)a.continue=!1;a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),n.issues.push(go(a))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((s)=>(n.value=s,n));return n.value=r,n}});function gy(e){return new w0({type:"transform",transform:e})}var vy=A("ZodOptional",(e,t)=>{Bl.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>su(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Ue(e){return new vy({type:"optional",innerType:e})}var _0=A("ZodExactOptional",(e,t)=>{Ag.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>su(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function S0(e){return new _0({type:"optional",innerType:e})}var k0=A("ZodNullable",(e,t)=>{zg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>jv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function dy(e){return new k0({type:"nullable",innerType:e})}var C0=A("ZodDefault",(e,t)=>{Pg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Hv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function T0(e,t){return new C0({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Pl(t)}})}var E0=A("ZodPrefault",(e,t)=>{Ng.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Bv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function I0(e,t){return new E0({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Pl(t)}})}var yy=A("ZodNonOptional",(e,t)=>{Rg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Zv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function A0(e,t){return new yy({type:"nonoptional",innerType:e,...X(t)})}var z0=A("ZodCatch",(e,t)=>{$g.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Uv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function P0(e,t){return new z0({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var N0=A("ZodPipe",(e,t)=>{Mg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Wv(e,n,o,r),e.in=t.in,e.out=t.out});function uu(e,t){return new N0({type:"pipe",in:e,out:t})}var R0=A("ZodReadonly",(e,t)=>{Og.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>qv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function $0(e){return new R0({type:"readonly",innerType:e})}var xy=A("ZodCustom",(e,t)=>{Lg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Rv(e,n,o,r)});function by(e,t){return bv(xy,e??(()=>!0),t)}function M0(e,t={}){return wv(xy,e,t)}function O0(e){return _v(e)}function mu(e,t){return uu(gy(e),t)}Ot(Ul());var jn="io.modelcontextprotocol/related-task",aa="2.0",ct=by((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),_y=ue([S(),ce().int()]),Sy=S(),AR=bt({ttl:ue([ce(),pu()]).optional(),pollInterval:ce().optional()}),L0=C({ttl:ce().optional()}),D0=C({taskId:S()}),hu=bt({progressToken:_y.optional(),[jn]:D0.optional()}),zt=C({_meta:hu.optional()}),si=zt.extend({task:L0.optional()}),ky=(e)=>si.safeParse(e).success,lt=C({method:S(),params:zt.loose().optional()}),Lt=C({_meta:hu.optional()}),Dt=C({method:S(),params:Lt.loose().optional()}),ut=bt({_meta:hu.optional()}),ur=ue([S(),ce().int()]),Cy=C({jsonrpc:w(aa),id:ur,...lt.shape}).strict(),gu=(e)=>Cy.safeParse(e).success,Ty=C({jsonrpc:w(aa),...Dt.shape}).strict(),Ey=(e)=>Ty.safeParse(e).success,vu=C({jsonrpc:w(aa),id:ur,result:ut}).strict(),ai=(e)=>vu.safeParse(e).success;var Se;(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Se||(Se={}));var yu=C({jsonrpc:w(aa),id:ur.optional(),error:C({code:ce().int(),message:S(),data:Ie().optional()})}).strict();var Iy=(e)=>yu.safeParse(e).success;var Ay=ue([Cy,Ty,vu,yu]),zR=ue([vu,yu]),xu=ut.strict(),F0=Lt.extend({requestId:ur.optional(),reason:S().optional()}),ca=Dt.extend({method:w("notifications/cancelled"),params:F0}),j0=C({src:S(),mimeType:S().optional(),sizes:ie(S()).optional(),theme:St(["light","dark"]).optional()}),ci=C({icons:ie(j0).optional()}),lr=C({name:S(),title:S().optional()}),li=lr.extend({...lr.shape,...ci.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),Z0=ia(C({applyDefaults:ze().optional()}),Ce(S(),Ie())),H0=mu((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},ia(C({form:Z0.optional(),url:ct.optional()}),Ce(S(),Ie()).optional())),B0=bt({list:ct.optional(),cancel:ct.optional(),requests:bt({sampling:bt({createMessage:ct.optional()}).optional(),elicitation:bt({create:ct.optional()}).optional()}).optional()}),U0=bt({list:ct.optional(),cancel:ct.optional(),requests:bt({tools:bt({call:ct.optional()}).optional()}).optional()}),W0=C({experimental:Ce(S(),ct).optional(),sampling:C({context:ct.optional(),tools:ct.optional()}).optional(),elicitation:H0.optional(),roots:C({listChanged:ze().optional()}).optional(),tasks:B0.optional()}),q0=zt.extend({protocolVersion:S(),capabilities:W0,clientInfo:li}),V0=lt.extend({method:w("initialize"),params:q0});var G0=C({experimental:Ce(S(),ct).optional(),logging:ct.optional(),completions:ct.optional(),prompts:C({listChanged:ze().optional()}).optional(),resources:C({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:C({listChanged:ze().optional()}).optional(),tasks:U0.optional()}),X0=ut.extend({protocolVersion:S(),capabilities:G0,serverInfo:li,instructions:S().optional()}),K0=Dt.extend({method:w("notifications/initialized"),params:Lt.optional()});var yo=lt.extend({method:w("ping"),params:zt.optional()}),J0=C({progress:ce(),total:Ue(ce()),message:Ue(S())}),Y0=C({...Lt.shape,...J0.shape,progressToken:_y}),la=Dt.extend({method:w("notifications/progress"),params:Y0}),Q0=zt.extend({cursor:Sy.optional()}),ui=lt.extend({params:Q0.optional()}),di=ut.extend({nextCursor:Sy.optional()}),eC=St(["working","input_required","completed","failed","cancelled"]),pi=C({taskId:S(),status:eC,ttl:ue([ce(),pu()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ue(ce()),statusMessage:Ue(S())}),ua=ut.extend({task:pi}),tC=Lt.merge(pi),fi=Dt.extend({method:w("notifications/tasks/status"),params:tC}),da=lt.extend({method:w("tasks/get"),params:zt.extend({taskId:S()})}),pa=ut.merge(pi),fa=lt.extend({method:w("tasks/result"),params:zt.extend({taskId:S()})}),PR=ut.loose(),ma=ui.extend({method:w("tasks/list")}),ha=di.extend({tasks:ie(pi)}),ga=lt.extend({method:w("tasks/cancel"),params:zt.extend({taskId:S()})}),zy=ut.merge(pi),Py=C({uri:S(),mimeType:Ue(S()),_meta:Ce(S(),Ie()).optional()}),Ny=Py.extend({text:S()}),bu=S().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ry=Py.extend({blob:bu}),mi=St(["user","assistant"]),dr=C({audience:ie(mi).optional(),priority:ce().min(0).max(1).optional(),lastModified:au({offset:!0}).optional()}),$y=C({...lr.shape,...ci.shape,uri:S(),description:Ue(S()),mimeType:Ue(S()),annotations:dr.optional(),_meta:Ue(bt({}))}),nC=C({...lr.shape,...ci.shape,uriTemplate:S(),description:Ue(S()),mimeType:Ue(S()),annotations:dr.optional(),_meta:Ue(bt({}))}),wu=ui.extend({method:w("resources/list")}),va=di.extend({resources:ie($y)}),_u=ui.extend({method:w("resources/templates/list")}),Su=di.extend({resourceTemplates:ie(nC)}),ku=zt.extend({uri:S()}),oC=ku,Cu=lt.extend({method:w("resources/read"),params:oC}),ya=ut.extend({contents:ie(ue([Ny,Ry]))}),Tu=Dt.extend({method:w("notifications/resources/list_changed"),params:Lt.optional()}),rC=ku,iC=lt.extend({method:w("resources/subscribe"),params:rC}),sC=ku,aC=lt.extend({method:w("resources/unsubscribe"),params:sC}),cC=Lt.extend({uri:S()}),lC=Dt.extend({method:w("notifications/resources/updated"),params:cC}),uC=C({name:S(),description:Ue(S()),required:Ue(ze())}),dC=C({...lr.shape,...ci.shape,description:Ue(S()),arguments:Ue(ie(uC)),_meta:Ue(bt({}))}),Eu=ui.extend({method:w("prompts/list")}),Iu=di.extend({prompts:ie(dC)}),pC=zt.extend({name:S(),arguments:Ce(S(),S()).optional()}),fC=lt.extend({method:w("prompts/get"),params:pC}),Au=C({type:w("text"),text:S(),annotations:dr.optional(),_meta:Ce(S(),Ie()).optional()}),zu=C({type:w("image"),data:bu,mimeType:S(),annotations:dr.optional(),_meta:Ce(S(),Ie()).optional()}),Pu=C({type:w("audio"),data:bu,mimeType:S(),annotations:dr.optional(),_meta:Ce(S(),Ie()).optional()}),mC=C({type:w("tool_use"),name:S(),id:S(),input:Ce(S(),Ie()),_meta:Ce(S(),Ie()).optional()}),Nu=C({type:w("resource"),resource:ue([Ny,Ry]),annotations:dr.optional(),_meta:Ce(S(),Ie()).optional()}),Ru=$y.extend({type:w("resource_link")}),pr=ue([Au,zu,Pu,Ru,Nu]),hC=C({role:mi,content:pr}),gC=ut.extend({description:S().optional(),messages:ie(hC)}),$u=Dt.extend({method:w("notifications/prompts/list_changed"),params:Lt.optional()}),vC=C({title:S().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),yC=C({taskSupport:St(["required","optional","forbidden"]).optional()}),xa=C({...lr.shape,...ci.shape,description:S().optional(),inputSchema:C({type:w("object"),properties:Ce(S(),ct).optional(),required:ie(S()).optional()}).catchall(Ie()),outputSchema:C({type:w("object"),properties:Ce(S(),ct).optional(),required:ie(S()).optional()}).catchall(Ie()).optional(),annotations:vC.optional(),execution:yC.optional(),_meta:Ce(S(),Ie()).optional()}),ba=ui.extend({method:w("tools/list")}),xC=di.extend({tools:ie(xa)}),xo=ut.extend({content:ie(pr).default([]),structuredContent:Ce(S(),Ie()).optional(),isError:ze().optional()}),NR=xo.or(ut.extend({toolResult:Ie()})),bC=si.extend({name:S(),arguments:Ce(S(),Ie()).optional()}),wa=lt.extend({method:w("tools/call"),params:bC}),Mu=Dt.extend({method:w("notifications/tools/list_changed"),params:Lt.optional()}),RR=C({autoRefresh:ze().default(!0),debounceMs:ce().int().nonnegative().default(300)}),My=St(["debug","info","notice","warning","error","critical","alert","emergency"]),wC=zt.extend({level:My}),_C=lt.extend({method:w("logging/setLevel"),params:wC}),SC=Lt.extend({level:My,logger:S().optional(),data:Ie()}),Ou=Dt.extend({method:w("notifications/message"),params:SC}),kC=C({name:S().optional()}),CC=C({hints:ie(kC).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),TC=C({mode:St(["auto","required","none"]).optional()}),EC=C({type:w("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ie(pr).default([]),structuredContent:C({}).loose().optional(),isError:ze().optional(),_meta:Ce(S(),Ie()).optional()}),IC=fu("type",[Au,zu,Pu]),sa=fu("type",[Au,zu,Pu,mC,EC]),AC=C({role:mi,content:ue([sa,ie(sa)]),_meta:Ce(S(),Ie()).optional()}),zC=si.extend({messages:ie(AC),modelPreferences:CC.optional(),systemPrompt:S().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:ie(S()).optional(),metadata:ct.optional(),tools:ie(xa).optional(),toolChoice:TC.optional()}),PC=lt.extend({method:w("sampling/createMessage"),params:zC}),NC=ut.extend({model:S(),stopReason:Ue(St(["endTurn","stopSequence","maxTokens"]).or(S())),role:mi,content:IC}),RC=ut.extend({model:S(),stopReason:Ue(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:mi,content:ue([sa,ie(sa)])}),$C=C({type:w("boolean"),title:S().optional(),description:S().optional(),default:ze().optional()}),MC=C({type:w("string"),title:S().optional(),description:S().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:St(["email","uri","date","date-time"]).optional(),default:S().optional()}),OC=C({type:St(["number","integer"]),title:S().optional(),description:S().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),LC=C({type:w("string"),title:S().optional(),description:S().optional(),enum:ie(S()),default:S().optional()}),DC=C({type:w("string"),title:S().optional(),description:S().optional(),oneOf:ie(C({const:S(),title:S()})),default:S().optional()}),FC=C({type:w("string"),title:S().optional(),description:S().optional(),enum:ie(S()),enumNames:ie(S()).optional(),default:S().optional()}),jC=ue([LC,DC]),ZC=C({type:w("array"),title:S().optional(),description:S().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:C({type:w("string"),enum:ie(S())}),default:ie(S()).optional()}),HC=C({type:w("array"),title:S().optional(),description:S().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:C({anyOf:ie(C({const:S(),title:S()}))}),default:ie(S()).optional()}),BC=ue([ZC,HC]),UC=ue([FC,jC,BC]),WC=ue([UC,$C,MC,OC]),qC=si.extend({mode:w("form").optional(),message:S(),requestedSchema:C({type:w("object"),properties:Ce(S(),WC),required:ie(S()).optional()})}),VC=si.extend({mode:w("url"),message:S(),elicitationId:S(),url:S().url()}),GC=ue([qC,VC]),XC=lt.extend({method:w("elicitation/create"),params:GC}),KC=Lt.extend({elicitationId:S()}),JC=Dt.extend({method:w("notifications/elicitation/complete"),params:KC}),YC=ut.extend({action:St(["accept","decline","cancel"]),content:mu((e)=>e===null?void 0:e,Ce(S(),ue([S(),ce(),ze(),ie(S())])).optional())}),QC=C({type:w("ref/resource"),uri:S()});var eT=C({type:w("ref/prompt"),name:S()}),tT=zt.extend({ref:ue([eT,QC]),argument:C({name:S(),value:S()}),context:C({arguments:Ce(S(),S()).optional()}).optional()}),nT=lt.extend({method:w("completion/complete"),params:tT});var oT=ut.extend({completion:bt({values:ie(S()).max(100),total:Ue(ce().int()),hasMore:Ue(ze())})}),rT=C({uri:S().startsWith("file://"),name:S().optional(),_meta:Ce(S(),Ie()).optional()}),iT=lt.extend({method:w("roots/list"),params:zt.optional()}),sT=ut.extend({roots:ie(rT)}),aT=Dt.extend({method:w("notifications/roots/list_changed"),params:Lt.optional()}),$R=ue([yo,V0,nT,_C,fC,Eu,wu,_u,Cu,iC,aC,wa,ba,da,fa,ma,ga]),MR=ue([ca,la,K0,aT,fi]),OR=ue([xu,NC,RC,YC,sT,pa,ha,ua]),LR=ue([yo,PC,XC,iT,da,fa,ma,ga]),DR=ue([ca,la,Ou,lC,Tu,Mu,$u,fi,JC]),FR=ue([xu,X0,oT,gC,Iu,va,Su,ya,xo,xC,pa,ha,ua]);class fe extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`);this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===Se.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Oy(o.elicitations,t)}return new fe(e,t,n)}}class Oy extends fe{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Se.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function _a(e){return!!e._zod}function Sa(e,t){if(_a(e))return Qr(e,t);return e.safeParse(t)}function Ly(e){if(!e)return;let t;if(_a(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function Dy(e){if(_a(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let o=e.value;if(o!==void 0)return o;return}function Zn(e){return e==="completed"||e==="failed"||e==="cancelled"}var cT=Symbol("Let zodToJsonSchema decide on which parser to use");var P$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Lu(e){let n=Ly(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=Dy(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function Du(e,t){let n=Sa(e,t);if(!n.success)throw n.error;return n.data}var mT=60000;class ka{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ca,(t)=>{this._oncancel(t)}),this.setNotificationHandler(la,(t)=>{this._onprogress(t)}),this.setRequestHandler(yo,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(da,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new fe(Se.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(fa,async(t,n)=>{let o=async()=>{let r=t.params.taskId;if(this._taskMessageQueue){let a;while(a=await this._taskMessageQueue.dequeue(r,n.sessionId)){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,p=new fe(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(r,n.sessionId);if(!s)throw new fe(Se.InvalidParams,`Task not found: ${r}`);if(!Zn(s.status))return await this._waitForTaskUpdate(r,n.signal),await o();if(Zn(s.status)){let a=await this._taskStore.getTaskResult(r,n.sessionId);return this._clearTaskQueue(r),{...a,_meta:{...a._meta,[jn]:{taskId:r}}}}return await o()};return await o()}),this.setRequestHandler(ma,async(t,n)=>{try{let{tasks:o,nextCursor:r}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:o,nextCursor:r,_meta:{}}}catch(o){throw new fe(Se.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ga,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new fe(Se.InvalidParams,`Task not found: ${t.params.taskId}`);if(Zn(o.status))throw new fe(Se.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);let r=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!r)throw new fe(Se.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...r}}catch(o){if(o instanceof fe)throw o;throw new fe(Se.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,o,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),fe.fromError(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=(r)=>{n?.(r),this._onerror(r)};let o=this._transport?.onmessage;this._transport.onmessage=(r,s)=>{if(o?.(r,s),ai(r)||Iy(r))this._onresponse(r);else if(gu(r))this._onrequest(r,s);else if(Ey(r))this._onnotification(r);else this._onerror(Error(`Unknown message type: ${JSON.stringify(r)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let t=fe.fromError(Se.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((n)=>this._onerror(Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,r=e.params?._meta?.[jn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Se.MethodNotFound,message:"Method not found"}};if(r&&this._taskMessageQueue)this._enqueueTaskMessage(r,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=ky(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(s.signal.aborted)return;let d={relatedRequestId:e.id};if(r)d.relatedTask={taskId:r};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(s.signal.aborted)throw new fe(Se.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(r&&!m.relatedTask)m.relatedTask={taskId:r};let f=m.relatedTask?.taskId??r;if(f&&c)await c.updateTaskStatus(f,"input_required");return await this.request(u,d,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:r,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(a)this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async(u)=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Se.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===s)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),r=this._progressHandlers.get(o);if(!r){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}r(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),ai(e))n(e);else{let s=new fe(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(t);if(o===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let r=!1;if(ai(e)&&e.result&&typeof e.result==="object"){let s=e.result;if(s.task&&typeof s.task==="object"){let a=s.task;if(typeof a.taskId==="string")r=!0,this._taskProgressTokens.set(a.taskId,t)}}if(!r)this._progressHandlers.delete(t);if(ai(e))o(e);else{let s=fe.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,t,n)}}catch(s){yield{type:"error",error:s instanceof fe?s:new fe(Se.InternalError,String(s))}}return}let r;try{let s=await this.request(e,ua,n);if(s.task)r=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new fe(Se.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:a},Zn(a.status)){if(a.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:r},t,n)};else if(a.status==="failed")yield{type:"error",error:new fe(Se.InternalError,`Task ${r} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new fe(Se.InternalError,`Task ${r} was cancelled`)};return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:r},t,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((l)=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof fe?s:new fe(Se.InternalError,String(s))}}}request(e,t,n){let{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=(h)=>{u(h)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(h){d(h);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(n?.onprogress)this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(a)m.params={...m.params,task:a};if(c)m.params={...m.params,_meta:{...m.params?._meta||{},[jn]:c}};let f=(h)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(h)}},{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((b)=>this._onerror(Error(`Failed to send cancellation: ${b}`)));let v=h instanceof fe?h:new fe(Se.RequestTimeout,String(h));u(v)};this._responseHandlers.set(p,(h)=>{if(n?.signal?.aborted)return;if(h instanceof Error)return u(h);try{let v=Sa(t,h.result);if(!v.success)u(v.error);else l(v.data)}catch(v){u(v)}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??mT,y=()=>f(fe.fromError(Se.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let h=(v)=>{let b=this._responseHandlers.get(p);if(b)b(v);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,h),this._enqueueTaskMessage(x,{type:"request",message:m,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(p),u(v)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((h)=>{this._cleanupTimeout(p),u(h)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},pa,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},ha,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},zy,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[jn]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};if(t?.relatedTask)a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[jn]:t.relatedTask}}};this._transport?.send(a,t).catch((c)=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[jn]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let n=Lu(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,r)=>{let s=Du(e,o);return Promise.resolve(t(s,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Lu(e);this._notificationHandlers.set(n,(o)=>{let r=Du(e,o);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let o of n)if(o.type==="request"&&gu(o.message)){let r=o.message.id,s=this._requestResolvers.get(r);if(s)s(new fe(Se.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r);else this._onerror(Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e);if(o?.pollInterval)n=o.pollInterval}catch{}return new Promise((o,r)=>{if(t.aborted){r(new fe(Se.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new fe(Se.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error("No task store configured");return{createTask:async(o)=>{if(!e)throw Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async(o)=>{let r=await n.getTask(o,t);if(!r)throw new fe(Se.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(o,r,s)=>{await n.storeTaskResult(o,r,s,t);let a=await n.getTask(o,t);if(a){let c=fi.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Zn(a.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>n.getTaskResult(o,t),updateTaskStatus:async(o,r,s)=>{let a=await n.getTask(o,t);if(!a)throw new fe(Se.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Zn(a.status))throw new fe(Se.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,r,s,t);let c=await n.getTask(o,t);if(c){let l=fi.parse({method:"notifications/tasks/status",params:c});if(await this.notification(l),Zn(c.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>n.listTasks(o,t)}}}var Zy="2026-01-26";var hT="ui/notifications/tool-input-partial";var gT=ue([w("light"),w("dark")]).describe("Color theme preference for the host environment."),gi=ue([w("inline"),w("fullscreen"),w("pip")]).describe("Display mode for UI presentation."),vT=ue([w("--color-background-primary"),w("--color-background-secondary"),w("--color-background-tertiary"),w("--color-background-inverse"),w("--color-background-ghost"),w("--color-background-info"),w("--color-background-danger"),w("--color-background-success"),w("--color-background-warning"),w("--color-background-disabled"),w("--color-text-primary"),w("--color-text-secondary"),w("--color-text-tertiary"),w("--color-text-inverse"),w("--color-text-ghost"),w("--color-text-info"),w("--color-text-danger"),w("--color-text-success"),w("--color-text-warning"),w("--color-text-disabled"),w("--color-border-primary"),w("--color-border-secondary"),w("--color-border-tertiary"),w("--color-border-inverse"),w("--color-border-ghost"),w("--color-border-info"),w("--color-border-danger"),w("--color-border-success"),w("--color-border-warning"),w("--color-border-disabled"),w("--color-ring-primary"),w("--color-ring-secondary"),w("--color-ring-inverse"),w("--color-ring-info"),w("--color-ring-danger"),w("--color-ring-success"),w("--color-ring-warning"),w("--font-sans"),w("--font-mono"),w("--font-weight-normal"),w("--font-weight-medium"),w("--font-weight-semibold"),w("--font-weight-bold"),w("--font-text-xs-size"),w("--font-text-sm-size"),w("--font-text-md-size"),w("--font-text-lg-size"),w("--font-heading-xs-size"),w("--font-heading-sm-size"),w("--font-heading-md-size"),w("--font-heading-lg-size"),w("--font-heading-xl-size"),w("--font-heading-2xl-size"),w("--font-heading-3xl-size"),w("--font-text-xs-line-height"),w("--font-text-sm-line-height"),w("--font-text-md-line-height"),w("--font-text-lg-line-height"),w("--font-heading-xs-line-height"),w("--font-heading-sm-line-height"),w("--font-heading-md-line-height"),w("--font-heading-lg-line-height"),w("--font-heading-xl-line-height"),w("--font-heading-2xl-line-height"),w("--font-heading-3xl-line-height"),w("--border-radius-xs"),w("--border-radius-sm"),w("--border-radius-md"),w("--border-radius-lg"),w("--border-radius-xl"),w("--border-radius-full"),w("--border-width-regular"),w("--shadow-hairline"),w("--shadow-sm"),w("--shadow-md"),w("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),yT=Ce(vT.describe(`Style variables for theming MCP apps.
150
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let c=a[1];if(t===a[0]){s(a);continue}if(e.external){let u=e.external.registry.get(a[0])?.id;if(t!==a[0]&&u){s(a);continue}}if(e.metadataRegistry.get(a[0])?.id){s(a);continue}if(c.cycle){s(a);continue}if(c.count>1){if(e.reused==="ref"){s(a);continue}}}}function gu(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){o(d);let m=e.seen.get(d),f=m.schema;if(f.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(f);else Object.assign(l,f);if(Object.assign(l,u),a._zod.parent===d)for(let y in l){if(y==="$ref"||y==="allOf")continue;if(!(y in u))delete l[y]}if(f.$ref&&m.def)for(let y in l){if(y==="$ref"||y==="allOf")continue;if(y in m.def&&JSON.stringify(l[y])===JSON.stringify(m.def[y]))delete l[y]}}let p=a._zod.parent;if(p&&p!==d){o(p);let m=e.seen.get(p);if(m?.schema.$ref){if(l.$ref=m.schema.$ref,m.def)for(let f in l){if(f==="$ref"||f==="allOf")continue;if(f in m.def&&JSON.stringify(l[f])===JSON.stringify(m.def[f]))delete l[f]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let s=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId)s[c.defId]=c.def}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")r.$defs=s;else r.definitions=s;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ci(t,"input",e.processors),output:ci(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function xt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return xt(o.element,n);if(o.type==="set")return xt(o.valueType,n);if(o.type==="lazy")return xt(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return xt(o.innerType,n);if(o.type==="intersection")return xt(o.left,n)||xt(o.right,n);if(o.type==="record"||o.type==="map")return xt(o.keyType,n)||xt(o.valueType,n);if(o.type==="pipe")return xt(o.in,n)||xt(o.out,n);if(o.type==="object"){for(let r in o.shape)if(xt(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(let r of o.options)if(xt(r,n))return!0;return!1}if(o.type==="tuple"){for(let r of o.items)if(xt(r,n))return!0;if(o.rest&&xt(o.rest,n))return!0;return!1}return!1}var Lv=(e,t={})=>(n)=>{let o=mu({...n,processors:t});return Ke(e,o),hu(o,e),gu(o,e)},ci=(e,t,n={})=>(o)=>{let{libraryOptions:r,target:s}=o??{},a=mu({...r??{},target:s,io:t,processors:n});return Ke(e,a),hu(a,e),gu(a,e)};var Zk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Dv=(e,t,n,o)=>{let r=n;r.type="string";let{minimum:s,maximum:a,format:c,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s==="number")r.minLength=s;if(typeof a==="number")r.maxLength=a;if(c){if(r.format=Zk[c]??c,r.format==="")delete r.format;if(c==="time")delete r.format}if(u)r.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Fv=(e,t,n,o)=>{let r=n,{minimum:s,maximum:a,format:c,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))r.type="integer";else r.type="number";if(typeof d==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")r.minimum=d,r.exclusiveMinimum=!0;else r.exclusiveMinimum=d;if(typeof s==="number"){if(r.minimum=s,typeof d==="number"&&t.target!=="draft-04")if(d>=s)delete r.minimum;else delete r.exclusiveMinimum}if(typeof u==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")r.maximum=u,r.exclusiveMaximum=!0;else r.exclusiveMaximum=u;if(typeof a==="number"){if(r.maximum=a,typeof u==="number"&&t.target!=="draft-04")if(u<=a)delete r.maximum;else delete r.exclusiveMaximum}if(typeof l==="number")r.multipleOf=l},jv=(e,t,n,o)=>{n.type="boolean"};var Zv=(e,t,n,o)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Hv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")};var Bv=(e,t,n,o)=>{n.not={}};var Uv=(e,t,n,o)=>{};var Wv=(e,t,n,o)=>{let r=e._zod.def,s=Ys(r.entries);if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";n.enum=s},qv=(e,t,n,o)=>{let r=e._zod.def,s=[];for(let a of r.values)if(a===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(a));else s.push(a);if(s.length===0);else if(s.length===1){let a=s[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";if(s.every((a)=>typeof a==="boolean"))n.type="boolean";if(s.every((a)=>a===null))n.type="null";n.enum=s}};var Vv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var Gv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Xv=(e,t,n,o)=>{let r=n,s=e._zod.def,{minimum:a,maximum:c}=e._zod.bag;if(typeof a==="number")r.minItems=a;if(typeof c==="number")r.maxItems=c;r.type="array",r.items=Ke(s.element,t,{...o,path:[...o.path,"items"]})},Kv=(e,t,n,o)=>{let r=n,s=e._zod.def;r.type="object",r.properties={};let a=s.shape;for(let u in a)r.properties[u]=Ke(a[u],t,{...o,path:[...o.path,"properties",u]});let c=new Set(Object.keys(a)),l=new Set([...c].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)r.required=Array.from(l);if(s.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")r.additionalProperties=!1}else if(s.catchall)r.additionalProperties=Ke(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Jv=(e,t,n,o)=>{let r=e._zod.def,s=r.inclusive===!1,a=r.options.map((c,l)=>Ke(c,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)n.oneOf=a;else n.anyOf=a},Yv=(e,t,n,o)=>{let r=e._zod.def,s=Ke(r.left,t,{...o,path:[...o.path,"allOf",0]}),a=Ke(r.right,t,{...o,path:[...o.path,"allOf",1]}),c=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...c(s)?s.allOf:[s],...c(a)?a.allOf:[a]];n.allOf=l};var Qv=(e,t,n,o)=>{let r=n,s=e._zod.def;r.type="object";let a=s.keyType,l=a._zod.bag?.patterns;if(s.mode==="loose"&&l&&l.size>0){let d=Ke(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let p of l)r.patternProperties[p.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=Ke(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});r.additionalProperties=Ke(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values;if(u){let d=[...u].filter((p)=>typeof p==="string"||typeof p==="number");if(d.length>0)r.required=d}},ey=(e,t,n,o)=>{let r=e._zod.def,s=Ke(r.innerType,t,o),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=r.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},ty=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType},ny=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},oy=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);if(s.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},ry=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},iy=(e,t,n,o)=>{let r=e._zod.def,s=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;Ke(s,t,o);let a=t.seen.get(e);a.ref=s},sy=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var vu=(e,t,n,o)=>{let r=e._zod.def;Ke(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType};var Xk=A("ZodISODateTime",(e,t)=>{mg.init(e,t),He.init(e,t)});function yu(e){return _v(Xk,e)}var Kk=A("ZodISODate",(e,t)=>{hg.init(e,t),He.init(e,t)});function ay(e){return Sv(Kk,e)}var Jk=A("ZodISOTime",(e,t)=>{gg.init(e,t),He.init(e,t)});function cy(e){return kv(Jk,e)}var Yk=A("ZodISODuration",(e,t)=>{vg.init(e,t),He.init(e,t)});function ly(e){return Cv(Yk,e)}var uy=(e,t)=>{na.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Jm(e,n)},flatten:{value:(n)=>Km(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ei,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ei,2)}},isEmpty:{get(){return e.issues.length===0}}})},IN=A("ZodError",uy),At=A("ZodError",uy,{Parent:Error});var dy=oa(At),py=ra(At),fy=ni(At),my=ri(At),hy=Ym(At),gy=Qm(At),vy=eh(At),yy=th(At),xy=nh(At),by=oh(At),wy=rh(At),_y=ih(At);var De=A("ZodType",(e,t)=>($e.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ci(e,"input"),output:ci(e,"output")}}),e.toJSONSchema=Lv(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(On(t,{checks:[...t.checks??[],...n.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0}),e.with=e.check,e.clone=(n,o)=>nn(e,n,o),e.brand=()=>e,e.register=(n,o)=>(n.add(e,o),e),e.parse=(n,o)=>dy(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>fy(e,n,o),e.parseAsync=async(n,o)=>py(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>my(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>hy(e,n,o),e.decode=(n,o)=>gy(e,n,o),e.encodeAsync=async(n,o)=>vy(e,n,o),e.decodeAsync=async(n,o)=>yy(e,n,o),e.safeEncode=(n,o)=>xy(e,n,o),e.safeDecode=(n,o)=>by(e,n,o),e.safeEncodeAsync=async(n,o)=>wy(e,n,o),e.safeDecodeAsync=async(n,o)=>_y(e,n,o),e.refine=(n,o)=>e.check(W0(n,o)),e.superRefine=(n)=>e.check(q0(n)),e.overwrite=(n)=>e.check(Fn(n)),e.optional=()=>Ue(e),e.exactOptional=()=>R0(e),e.nullable=()=>Cy(e),e.nullish=()=>Ue(Cy(e)),e.nonoptional=(n)=>F0(e,n),e.array=()=>ie(e),e.or=(n)=>ue([e,n]),e.and=(n)=>ga(e,n),e.transform=(n)=>wu(e,zy(n)),e.default=(n)=>O0(e,n),e.prefault=(n)=>D0(e,n),e.catch=(n)=>Z0(e,n),e.pipe=(n)=>wu(e,n),e.readonly=()=>U0(e),e.describe=(n)=>{let o=e.clone();return yo.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return yo.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return yo.get(e);let o=e.clone();return yo.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),Ty=A("_ZodString",(e,t)=>{la.init(e,t),De.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Dv(e,o,r,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...o)=>e.check(ou(...o)),e.includes=(...o)=>e.check(su(...o)),e.startsWith=(...o)=>e.check(au(...o)),e.endsWith=(...o)=>e.check(cu(...o)),e.min=(...o)=>e.check(ur(...o)),e.max=(...o)=>e.check(fa(...o)),e.length=(...o)=>e.check(ma(...o)),e.nonempty=(...o)=>e.check(ur(1,...o)),e.lowercase=(o)=>e.check(ru(o)),e.uppercase=(o)=>e.check(iu(o)),e.trim=()=>e.check(uu()),e.normalize=(...o)=>e.check(lu(...o)),e.toLowerCase=()=>e.check(du()),e.toUpperCase=()=>e.check(pu()),e.slugify=()=>e.check(fu())}),t0=A("ZodString",(e,t)=>{la.init(e,t),Ty.init(e,t),e.email=(n)=>e.check(tv(n0,n)),e.url=(n)=>e.check(sv(o0,n)),e.jwt=(n)=>e.check(wv(y0,n)),e.emoji=(n)=>e.check(av(r0,n)),e.guid=(n)=>e.check(nu(Sy,n)),e.uuid=(n)=>e.check(nv(ha,n)),e.uuidv4=(n)=>e.check(ov(ha,n)),e.uuidv6=(n)=>e.check(rv(ha,n)),e.uuidv7=(n)=>e.check(iv(ha,n)),e.nanoid=(n)=>e.check(cv(i0,n)),e.guid=(n)=>e.check(nu(Sy,n)),e.cuid=(n)=>e.check(lv(s0,n)),e.cuid2=(n)=>e.check(uv(a0,n)),e.ulid=(n)=>e.check(dv(c0,n)),e.base64=(n)=>e.check(yv(h0,n)),e.base64url=(n)=>e.check(xv(g0,n)),e.xid=(n)=>e.check(pv(l0,n)),e.ksuid=(n)=>e.check(fv(u0,n)),e.ipv4=(n)=>e.check(mv(d0,n)),e.ipv6=(n)=>e.check(hv(p0,n)),e.cidrv4=(n)=>e.check(gv(f0,n)),e.cidrv6=(n)=>e.check(vv(m0,n)),e.e164=(n)=>e.check(bv(v0,n)),e.datetime=(n)=>e.check(yu(n)),e.date=(n)=>e.check(ay(n)),e.time=(n)=>e.check(cy(n)),e.duration=(n)=>e.check(ly(n))});function S(e){return ev(t0,e)}var He=A("ZodStringFormat",(e,t)=>{Le.init(e,t),Ty.init(e,t)}),n0=A("ZodEmail",(e,t)=>{ig.init(e,t),He.init(e,t)});var Sy=A("ZodGUID",(e,t)=>{og.init(e,t),He.init(e,t)});var ha=A("ZodUUID",(e,t)=>{rg.init(e,t),He.init(e,t)});var o0=A("ZodURL",(e,t)=>{sg.init(e,t),He.init(e,t)});var r0=A("ZodEmoji",(e,t)=>{ag.init(e,t),He.init(e,t)});var i0=A("ZodNanoID",(e,t)=>{cg.init(e,t),He.init(e,t)});var s0=A("ZodCUID",(e,t)=>{lg.init(e,t),He.init(e,t)});var a0=A("ZodCUID2",(e,t)=>{ug.init(e,t),He.init(e,t)});var c0=A("ZodULID",(e,t)=>{dg.init(e,t),He.init(e,t)});var l0=A("ZodXID",(e,t)=>{pg.init(e,t),He.init(e,t)});var u0=A("ZodKSUID",(e,t)=>{fg.init(e,t),He.init(e,t)});var d0=A("ZodIPv4",(e,t)=>{yg.init(e,t),He.init(e,t)});var p0=A("ZodIPv6",(e,t)=>{xg.init(e,t),He.init(e,t)});var f0=A("ZodCIDRv4",(e,t)=>{bg.init(e,t),He.init(e,t)});var m0=A("ZodCIDRv6",(e,t)=>{wg.init(e,t),He.init(e,t)});var h0=A("ZodBase64",(e,t)=>{Sg.init(e,t),He.init(e,t)});var g0=A("ZodBase64URL",(e,t)=>{kg.init(e,t),He.init(e,t)});var v0=A("ZodE164",(e,t)=>{Cg.init(e,t),He.init(e,t)});var y0=A("ZodJWT",(e,t)=>{Tg.init(e,t),He.init(e,t)});var Ey=A("ZodNumber",(e,t)=>{Yl.init(e,t),De.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Fv(e,o,r,s),e.gt=(o,r)=>e.check(da(o,r)),e.gte=(o,r)=>e.check(ai(o,r)),e.min=(o,r)=>e.check(ai(o,r)),e.lt=(o,r)=>e.check(ua(o,r)),e.lte=(o,r)=>e.check(si(o,r)),e.max=(o,r)=>e.check(si(o,r)),e.int=(o)=>e.check(ky(o)),e.safe=(o)=>e.check(ky(o)),e.positive=(o)=>e.check(da(0,o)),e.nonnegative=(o)=>e.check(ai(0,o)),e.negative=(o)=>e.check(ua(0,o)),e.nonpositive=(o)=>e.check(si(0,o)),e.multipleOf=(o,r)=>e.check(pa(o,r)),e.step=(o,r)=>e.check(pa(o,r)),e.finite=()=>e;let 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??0.5),e.isFinite=!0,e.format=n.format??null});function ce(e){return Tv(Ey,e)}var x0=A("ZodNumberFormat",(e,t)=>{Eg.init(e,t),Ey.init(e,t)});function ky(e){return Ev(x0,e)}var b0=A("ZodBoolean",(e,t)=>{Ig.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>jv(e,n,o,r)});function ze(e){return Iv(b0,e)}var w0=A("ZodUndefined",(e,t)=>{Ag.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Hv(e,n,o,r)});function _u(e){return Av(w0,e)}var _0=A("ZodNull",(e,t)=>{zg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Zv(e,n,o,r)});function Su(e){return zv(_0,e)}var S0=A("ZodUnknown",(e,t)=>{Pg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Uv(e,n,o,r)});function Ie(){return Pv(S0)}var k0=A("ZodNever",(e,t)=>{Ng.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Bv(e,n,o,r)});function C0(e){return Nv(k0,e)}var T0=A("ZodArray",(e,t)=>{Rg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Xv(e,n,o,r),e.element=t.element,e.min=(n,o)=>e.check(ur(n,o)),e.nonempty=(n)=>e.check(ur(1,n)),e.max=(n,o)=>e.check(fa(n,o)),e.length=(n,o)=>e.check(ma(n,o)),e.unwrap=()=>e.element});function ie(e,t){return Rv(T0,e,t)}var Iy=A("ZodObject",(e,t)=>{Og.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Kv(e,n,o,r),be(e,"shape",()=>t.shape),e.keyof=()=>St(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ie()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ie()}),e.strict=()=>e.clone({...e._zod.def,catchall:C0()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>Tk(e,n),e.safeExtend=(n)=>Ek(e,n),e.merge=(n)=>Ik(e,n),e.pick=(n)=>kk(e,n),e.omit=(n)=>Ck(e,n),e.partial=(...n)=>Ak(Py,e,n[0]),e.required=(...n)=>zk(Ny,e,n[0])});function C(e,t){let n={type:"object",shape:e??{},...X(t)};return new Iy(n)}function bt(e,t){return new Iy({type:"object",shape:e,catchall:Ie(),...X(t)})}var Ay=A("ZodUnion",(e,t)=>{Ql.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Jv(e,n,o,r),e.options=t.options});function ue(e,t){return new Ay({type:"union",options:e,...X(t)})}var E0=A("ZodDiscriminatedUnion",(e,t)=>{Ay.init(e,t),Lg.init(e,t)});function ku(e,t,n){return new E0({type:"union",options:t,discriminator:e,...X(n)})}var I0=A("ZodIntersection",(e,t)=>{Dg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Yv(e,n,o,r)});function ga(e,t){return new I0({type:"intersection",left:e,right:t})}var A0=A("ZodRecord",(e,t)=>{Fg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Qv(e,n,o,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ce(e,t,n){return new A0({type:"record",keyType:e,valueType:t,...X(n)})}var bu=A("ZodEnum",(e,t)=>{jg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Wv(e,o,r,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(o,r)=>{let s={};for(let a of o)if(n.has(a))s[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new bu({...t,checks:[],...X(r),entries:s})},e.exclude=(o,r)=>{let s={...t.entries};for(let a of o)if(n.has(a))delete s[a];else throw Error(`Key ${a} not found in enum`);return new bu({...t,checks:[],...X(r),entries:s})}});function St(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new bu({type:"enum",entries:n,...X(t)})}var z0=A("ZodLiteral",(e,t)=>{Zg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>qv(e,n,o,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function w(e,t){return new z0({type:"literal",values:Array.isArray(e)?e:[e],...X(t)})}var P0=A("ZodTransform",(e,t)=>{Hg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Gv(e,n,o,r),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Qr(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(vo(s,n.value,t));else{let a=s;if(a.fatal)a.continue=!1;a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),n.issues.push(vo(a))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((s)=>(n.value=s,n));return n.value=r,n}});function zy(e){return new P0({type:"transform",transform:e})}var Py=A("ZodOptional",(e,t)=>{eu.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>vu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Ue(e){return new Py({type:"optional",innerType:e})}var N0=A("ZodExactOptional",(e,t)=>{Bg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>vu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function R0(e){return new N0({type:"optional",innerType:e})}var $0=A("ZodNullable",(e,t)=>{Ug.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ey(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Cy(e){return new $0({type:"nullable",innerType:e})}var M0=A("ZodDefault",(e,t)=>{Wg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ny(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function O0(e,t){return new M0({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Hl(t)}})}var L0=A("ZodPrefault",(e,t)=>{qg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>oy(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function D0(e,t){return new L0({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Hl(t)}})}var Ny=A("ZodNonOptional",(e,t)=>{Vg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ty(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function F0(e,t){return new Ny({type:"nonoptional",innerType:e,...X(t)})}var j0=A("ZodCatch",(e,t)=>{Gg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ry(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Z0(e,t){return new j0({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var H0=A("ZodPipe",(e,t)=>{Xg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>iy(e,n,o,r),e.in=t.in,e.out=t.out});function wu(e,t){return new H0({type:"pipe",in:e,out:t})}var B0=A("ZodReadonly",(e,t)=>{Kg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>sy(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function U0(e){return new B0({type:"readonly",innerType:e})}var Ry=A("ZodCustom",(e,t)=>{Jg.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Vv(e,n,o,r)});function $y(e,t){return $v(Ry,e??(()=>!0),t)}function W0(e,t={}){return Mv(Ry,e,t)}function q0(e){return Ov(e)}function Cu(e,t){return wu(zy(e),t)}Lt(tu());var jn="io.modelcontextprotocol/related-task",ya="2.0",ct=$y((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),Oy=ue([S(),ce().int()]),Ly=S(),BR=bt({ttl:ue([ce(),Su()]).optional(),pollInterval:ce().optional()}),V0=C({ttl:ce().optional()}),G0=C({taskId:S()}),Tu=bt({progressToken:Oy.optional(),[jn]:G0.optional()}),zt=C({_meta:Tu.optional()}),ui=zt.extend({task:V0.optional()}),Dy=(e)=>ui.safeParse(e).success,lt=C({method:S(),params:zt.loose().optional()}),Dt=C({_meta:Tu.optional()}),Ft=C({method:S(),params:Dt.loose().optional()}),ut=bt({_meta:Tu.optional()}),pr=ue([S(),ce().int()]),Fy=C({jsonrpc:w(ya),id:pr,...lt.shape}).strict(),Eu=(e)=>Fy.safeParse(e).success,jy=C({jsonrpc:w(ya),...Ft.shape}).strict(),Zy=(e)=>jy.safeParse(e).success,Iu=C({jsonrpc:w(ya),id:pr,result:ut}).strict(),di=(e)=>Iu.safeParse(e).success;var Se;(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Se||(Se={}));var Au=C({jsonrpc:w(ya),id:pr.optional(),error:C({code:ce().int(),message:S(),data:Ie().optional()})}).strict();var Hy=(e)=>Au.safeParse(e).success;var By=ue([Fy,jy,Iu,Au]),UR=ue([Iu,Au]),zu=ut.strict(),X0=Dt.extend({requestId:pr.optional(),reason:S().optional()}),xa=Ft.extend({method:w("notifications/cancelled"),params:X0}),K0=C({src:S(),mimeType:S().optional(),sizes:ie(S()).optional(),theme:St(["light","dark"]).optional()}),pi=C({icons:ie(K0).optional()}),dr=C({name:S(),title:S().optional()}),fi=dr.extend({...dr.shape,...pi.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),J0=ga(C({applyDefaults:ze().optional()}),Ce(S(),Ie())),Y0=Cu((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},ga(C({form:J0.optional(),url:ct.optional()}),Ce(S(),Ie()).optional())),Q0=bt({list:ct.optional(),cancel:ct.optional(),requests:bt({sampling:bt({createMessage:ct.optional()}).optional(),elicitation:bt({create:ct.optional()}).optional()}).optional()}),eC=bt({list:ct.optional(),cancel:ct.optional(),requests:bt({tools:bt({call:ct.optional()}).optional()}).optional()}),tC=C({experimental:Ce(S(),ct).optional(),sampling:C({context:ct.optional(),tools:ct.optional()}).optional(),elicitation:Y0.optional(),roots:C({listChanged:ze().optional()}).optional(),tasks:Q0.optional()}),nC=zt.extend({protocolVersion:S(),capabilities:tC,clientInfo:fi}),oC=lt.extend({method:w("initialize"),params:nC});var rC=C({experimental:Ce(S(),ct).optional(),logging:ct.optional(),completions:ct.optional(),prompts:C({listChanged:ze().optional()}).optional(),resources:C({subscribe:ze().optional(),listChanged:ze().optional()}).optional(),tools:C({listChanged:ze().optional()}).optional(),tasks:eC.optional()}),iC=ut.extend({protocolVersion:S(),capabilities:rC,serverInfo:fi,instructions:S().optional()}),sC=Ft.extend({method:w("notifications/initialized"),params:Dt.optional()});var xo=lt.extend({method:w("ping"),params:zt.optional()}),aC=C({progress:ce(),total:Ue(ce()),message:Ue(S())}),cC=C({...Dt.shape,...aC.shape,progressToken:Oy}),ba=Ft.extend({method:w("notifications/progress"),params:cC}),lC=zt.extend({cursor:Ly.optional()}),mi=lt.extend({params:lC.optional()}),hi=ut.extend({nextCursor:Ly.optional()}),uC=St(["working","input_required","completed","failed","cancelled"]),gi=C({taskId:S(),status:uC,ttl:ue([ce(),Su()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ue(ce()),statusMessage:Ue(S())}),wa=ut.extend({task:gi}),dC=Dt.merge(gi),vi=Ft.extend({method:w("notifications/tasks/status"),params:dC}),_a=lt.extend({method:w("tasks/get"),params:zt.extend({taskId:S()})}),Sa=ut.merge(gi),ka=lt.extend({method:w("tasks/result"),params:zt.extend({taskId:S()})}),WR=ut.loose(),Ca=mi.extend({method:w("tasks/list")}),Ta=hi.extend({tasks:ie(gi)}),Ea=lt.extend({method:w("tasks/cancel"),params:zt.extend({taskId:S()})}),Uy=ut.merge(gi),Wy=C({uri:S(),mimeType:Ue(S()),_meta:Ce(S(),Ie()).optional()}),qy=Wy.extend({text:S()}),Pu=S().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vy=Wy.extend({blob:Pu}),yi=St(["user","assistant"]),fr=C({audience:ie(yi).optional(),priority:ce().min(0).max(1).optional(),lastModified:yu({offset:!0}).optional()}),Gy=C({...dr.shape,...pi.shape,uri:S(),description:Ue(S()),mimeType:Ue(S()),annotations:fr.optional(),_meta:Ue(bt({}))}),pC=C({...dr.shape,...pi.shape,uriTemplate:S(),description:Ue(S()),mimeType:Ue(S()),annotations:fr.optional(),_meta:Ue(bt({}))}),Nu=mi.extend({method:w("resources/list")}),Ia=hi.extend({resources:ie(Gy)}),Ru=mi.extend({method:w("resources/templates/list")}),$u=hi.extend({resourceTemplates:ie(pC)}),Mu=zt.extend({uri:S()}),fC=Mu,Ou=lt.extend({method:w("resources/read"),params:fC}),Aa=ut.extend({contents:ie(ue([qy,Vy]))}),Lu=Ft.extend({method:w("notifications/resources/list_changed"),params:Dt.optional()}),mC=Mu,hC=lt.extend({method:w("resources/subscribe"),params:mC}),gC=Mu,vC=lt.extend({method:w("resources/unsubscribe"),params:gC}),yC=Dt.extend({uri:S()}),xC=Ft.extend({method:w("notifications/resources/updated"),params:yC}),bC=C({name:S(),description:Ue(S()),required:Ue(ze())}),wC=C({...dr.shape,...pi.shape,description:Ue(S()),arguments:Ue(ie(bC)),_meta:Ue(bt({}))}),Du=mi.extend({method:w("prompts/list")}),Fu=hi.extend({prompts:ie(wC)}),_C=zt.extend({name:S(),arguments:Ce(S(),S()).optional()}),SC=lt.extend({method:w("prompts/get"),params:_C}),ju=C({type:w("text"),text:S(),annotations:fr.optional(),_meta:Ce(S(),Ie()).optional()}),Zu=C({type:w("image"),data:Pu,mimeType:S(),annotations:fr.optional(),_meta:Ce(S(),Ie()).optional()}),Hu=C({type:w("audio"),data:Pu,mimeType:S(),annotations:fr.optional(),_meta:Ce(S(),Ie()).optional()}),kC=C({type:w("tool_use"),name:S(),id:S(),input:Ce(S(),Ie()),_meta:Ce(S(),Ie()).optional()}),Bu=C({type:w("resource"),resource:ue([qy,Vy]),annotations:fr.optional(),_meta:Ce(S(),Ie()).optional()}),Uu=Gy.extend({type:w("resource_link")}),mr=ue([ju,Zu,Hu,Uu,Bu]),CC=C({role:yi,content:mr}),TC=ut.extend({description:S().optional(),messages:ie(CC)}),Wu=Ft.extend({method:w("notifications/prompts/list_changed"),params:Dt.optional()}),EC=C({title:S().optional(),readOnlyHint:ze().optional(),destructiveHint:ze().optional(),idempotentHint:ze().optional(),openWorldHint:ze().optional()}),IC=C({taskSupport:St(["required","optional","forbidden"]).optional()}),za=C({...dr.shape,...pi.shape,description:S().optional(),inputSchema:C({type:w("object"),properties:Ce(S(),ct).optional(),required:ie(S()).optional()}).catchall(Ie()),outputSchema:C({type:w("object"),properties:Ce(S(),ct).optional(),required:ie(S()).optional()}).catchall(Ie()).optional(),annotations:EC.optional(),execution:IC.optional(),_meta:Ce(S(),Ie()).optional()}),Pa=mi.extend({method:w("tools/list")}),AC=hi.extend({tools:ie(za)}),bo=ut.extend({content:ie(mr).default([]),structuredContent:Ce(S(),Ie()).optional(),isError:ze().optional()}),qR=bo.or(ut.extend({toolResult:Ie()})),zC=ui.extend({name:S(),arguments:Ce(S(),Ie()).optional()}),Na=lt.extend({method:w("tools/call"),params:zC}),qu=Ft.extend({method:w("notifications/tools/list_changed"),params:Dt.optional()}),VR=C({autoRefresh:ze().default(!0),debounceMs:ce().int().nonnegative().default(300)}),Xy=St(["debug","info","notice","warning","error","critical","alert","emergency"]),PC=zt.extend({level:Xy}),NC=lt.extend({method:w("logging/setLevel"),params:PC}),RC=Dt.extend({level:Xy,logger:S().optional(),data:Ie()}),Vu=Ft.extend({method:w("notifications/message"),params:RC}),$C=C({name:S().optional()}),MC=C({hints:ie($C).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),OC=C({mode:St(["auto","required","none"]).optional()}),LC=C({type:w("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ie(mr).default([]),structuredContent:C({}).loose().optional(),isError:ze().optional(),_meta:Ce(S(),Ie()).optional()}),DC=ku("type",[ju,Zu,Hu]),va=ku("type",[ju,Zu,Hu,kC,LC]),FC=C({role:yi,content:ue([va,ie(va)]),_meta:Ce(S(),Ie()).optional()}),jC=ui.extend({messages:ie(FC),modelPreferences:MC.optional(),systemPrompt:S().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:ie(S()).optional(),metadata:ct.optional(),tools:ie(za).optional(),toolChoice:OC.optional()}),ZC=lt.extend({method:w("sampling/createMessage"),params:jC}),HC=ut.extend({model:S(),stopReason:Ue(St(["endTurn","stopSequence","maxTokens"]).or(S())),role:yi,content:DC}),BC=ut.extend({model:S(),stopReason:Ue(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:yi,content:ue([va,ie(va)])}),UC=C({type:w("boolean"),title:S().optional(),description:S().optional(),default:ze().optional()}),WC=C({type:w("string"),title:S().optional(),description:S().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:St(["email","uri","date","date-time"]).optional(),default:S().optional()}),qC=C({type:St(["number","integer"]),title:S().optional(),description:S().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),VC=C({type:w("string"),title:S().optional(),description:S().optional(),enum:ie(S()),default:S().optional()}),GC=C({type:w("string"),title:S().optional(),description:S().optional(),oneOf:ie(C({const:S(),title:S()})),default:S().optional()}),XC=C({type:w("string"),title:S().optional(),description:S().optional(),enum:ie(S()),enumNames:ie(S()).optional(),default:S().optional()}),KC=ue([VC,GC]),JC=C({type:w("array"),title:S().optional(),description:S().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:C({type:w("string"),enum:ie(S())}),default:ie(S()).optional()}),YC=C({type:w("array"),title:S().optional(),description:S().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:C({anyOf:ie(C({const:S(),title:S()}))}),default:ie(S()).optional()}),QC=ue([JC,YC]),eT=ue([XC,KC,QC]),tT=ue([eT,UC,WC,qC]),nT=ui.extend({mode:w("form").optional(),message:S(),requestedSchema:C({type:w("object"),properties:Ce(S(),tT),required:ie(S()).optional()})}),oT=ui.extend({mode:w("url"),message:S(),elicitationId:S(),url:S().url()}),rT=ue([nT,oT]),iT=lt.extend({method:w("elicitation/create"),params:rT}),sT=Dt.extend({elicitationId:S()}),aT=Ft.extend({method:w("notifications/elicitation/complete"),params:sT}),cT=ut.extend({action:St(["accept","decline","cancel"]),content:Cu((e)=>e===null?void 0:e,Ce(S(),ue([S(),ce(),ze(),ie(S())])).optional())}),lT=C({type:w("ref/resource"),uri:S()});var uT=C({type:w("ref/prompt"),name:S()}),dT=zt.extend({ref:ue([uT,lT]),argument:C({name:S(),value:S()}),context:C({arguments:Ce(S(),S()).optional()}).optional()}),pT=lt.extend({method:w("completion/complete"),params:dT});var fT=ut.extend({completion:bt({values:ie(S()).max(100),total:Ue(ce().int()),hasMore:Ue(ze())})}),mT=C({uri:S().startsWith("file://"),name:S().optional(),_meta:Ce(S(),Ie()).optional()}),hT=lt.extend({method:w("roots/list"),params:zt.optional()}),gT=ut.extend({roots:ie(mT)}),vT=Ft.extend({method:w("notifications/roots/list_changed"),params:Dt.optional()}),GR=ue([xo,oC,pT,NC,SC,Du,Nu,Ru,Ou,hC,vC,Na,Pa,_a,ka,Ca,Ea]),XR=ue([xa,ba,sC,vT,vi]),KR=ue([zu,HC,BC,cT,gT,Sa,Ta,wa]),JR=ue([xo,ZC,iT,hT,_a,ka,Ca,Ea]),YR=ue([xa,ba,Vu,xC,Lu,qu,Wu,vi,aT]),QR=ue([zu,iC,fT,TC,Fu,Ia,$u,Aa,bo,AC,Sa,Ta,wa]);class fe extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`);this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===Se.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ky(o.elicitations,t)}return new fe(e,t,n)}}class Ky extends fe{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Se.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Ra(e){return!!e._zod}function $a(e,t){if(Ra(e))return oi(e,t);return e.safeParse(t)}function Jy(e){if(!e)return;let t;if(Ra(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function Yy(e){if(Ra(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let o=e.value;if(o!==void 0)return o;return}function Zn(e){return e==="completed"||e==="failed"||e==="cancelled"}var yT=Symbol("Let zodToJsonSchema decide on which parser to use");var W$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Gu(e){let n=Jy(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=Yy(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function Xu(e,t){let n=$a(e,t);if(!n.success)throw n.error;return n.data}var kT=60000;class Ma{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(xa,(t)=>{this._oncancel(t)}),this.setNotificationHandler(ba,(t)=>{this._onprogress(t)}),this.setRequestHandler(xo,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(_a,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new fe(Se.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ka,async(t,n)=>{let o=async()=>{let r=t.params.taskId;if(this._taskMessageQueue){let a;while(a=await this._taskMessageQueue.dequeue(r,n.sessionId)){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,p=new fe(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(r,n.sessionId);if(!s)throw new fe(Se.InvalidParams,`Task not found: ${r}`);if(!Zn(s.status))return await this._waitForTaskUpdate(r,n.signal),await o();if(Zn(s.status)){let a=await this._taskStore.getTaskResult(r,n.sessionId);return this._clearTaskQueue(r),{...a,_meta:{...a._meta,[jn]:{taskId:r}}}}return await o()};return await o()}),this.setRequestHandler(Ca,async(t,n)=>{try{let{tasks:o,nextCursor:r}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:o,nextCursor:r,_meta:{}}}catch(o){throw new fe(Se.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ea,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new fe(Se.InvalidParams,`Task not found: ${t.params.taskId}`);if(Zn(o.status))throw new fe(Se.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);let r=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!r)throw new fe(Se.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...r}}catch(o){if(o instanceof fe)throw o;throw new fe(Se.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,o,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),fe.fromError(Se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=(r)=>{n?.(r),this._onerror(r)};let o=this._transport?.onmessage;this._transport.onmessage=(r,s)=>{if(o?.(r,s),di(r)||Hy(r))this._onresponse(r);else if(Eu(r))this._onrequest(r,s);else if(Zy(r))this._onnotification(r);else this._onerror(Error(`Unknown message type: ${JSON.stringify(r)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let t=fe.fromError(Se.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((n)=>this._onerror(Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,r=e.params?._meta?.[jn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Se.MethodNotFound,message:"Method not found"}};if(r&&this._taskMessageQueue)this._enqueueTaskMessage(r,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=Dy(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(s.signal.aborted)return;let d={relatedRequestId:e.id};if(r)d.relatedTask={taskId:r};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(s.signal.aborted)throw new fe(Se.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(r&&!m.relatedTask)m.relatedTask={taskId:r};let f=m.relatedTask?.taskId??r;if(f&&c)await c.updateTaskStatus(f,"input_required");return await this.request(u,d,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:r,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(a)this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async(u)=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Se.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===s)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),r=this._progressHandlers.get(o);if(!r){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}r(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),di(e))n(e);else{let s=new fe(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(t);if(o===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let r=!1;if(di(e)&&e.result&&typeof e.result==="object"){let s=e.result;if(s.task&&typeof s.task==="object"){let a=s.task;if(typeof a.taskId==="string")r=!0,this._taskProgressTokens.set(a.taskId,t)}}if(!r)this._progressHandlers.delete(t);if(di(e))o(e);else{let s=fe.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,t,n)}}catch(s){yield{type:"error",error:s instanceof fe?s:new fe(Se.InternalError,String(s))}}return}let r;try{let s=await this.request(e,wa,n);if(s.task)r=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new fe(Se.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:a},Zn(a.status)){if(a.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:r},t,n)};else if(a.status==="failed")yield{type:"error",error:new fe(Se.InternalError,`Task ${r} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new fe(Se.InternalError,`Task ${r} was cancelled`)};return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:r},t,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((l)=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof fe?s:new fe(Se.InternalError,String(s))}}}request(e,t,n){let{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=(h)=>{u(h)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(h){d(h);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(n?.onprogress)this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(a)m.params={...m.params,task:a};if(c)m.params={...m.params,_meta:{...m.params?._meta||{},[jn]:c}};let f=(h)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(h)}},{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((b)=>this._onerror(Error(`Failed to send cancellation: ${b}`)));let v=h instanceof fe?h:new fe(Se.RequestTimeout,String(h));u(v)};this._responseHandlers.set(p,(h)=>{if(n?.signal?.aborted)return;if(h instanceof Error)return u(h);try{let v=$a(t,h.result);if(!v.success)u(v.error);else l(v.data)}catch(v){u(v)}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??kT,y=()=>f(fe.fromError(Se.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let h=(v)=>{let b=this._responseHandlers.get(p);if(b)b(v);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,h),this._enqueueTaskMessage(x,{type:"request",message:m,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(p),u(v)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((h)=>{this._cleanupTimeout(p),u(h)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Sa,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Ta,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Uy,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[jn]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};if(t?.relatedTask)a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[jn]:t.relatedTask}}};this._transport?.send(a,t).catch((c)=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[jn]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let n=Gu(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,r)=>{let s=Xu(e,o);return Promise.resolve(t(s,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Gu(e);this._notificationHandlers.set(n,(o)=>{let r=Xu(e,o);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,o)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let o of n)if(o.type==="request"&&Eu(o.message)){let r=o.message.id,s=this._requestResolvers.get(r);if(s)s(new fe(Se.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r);else this._onerror(Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e);if(o?.pollInterval)n=o.pollInterval}catch{}return new Promise((o,r)=>{if(t.aborted){r(new fe(Se.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new fe(Se.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error("No task store configured");return{createTask:async(o)=>{if(!e)throw Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},t)},getTask:async(o)=>{let r=await n.getTask(o,t);if(!r)throw new fe(Se.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(o,r,s)=>{await n.storeTaskResult(o,r,s,t);let a=await n.getTask(o,t);if(a){let c=vi.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Zn(a.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>n.getTaskResult(o,t),updateTaskStatus:async(o,r,s)=>{let a=await n.getTask(o,t);if(!a)throw new fe(Se.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Zn(a.status))throw new fe(Se.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,r,s,t);let c=await n.getTask(o,t);if(c){let l=vi.parse({method:"notifications/tasks/status",params:c});if(await this.notification(l),Zn(c.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>n.listTasks(o,t)}}}var tx="2026-01-26";var CT="ui/notifications/tool-input-partial";var TT=ue([w("light"),w("dark")]).describe("Color theme preference for the host environment."),bi=ue([w("inline"),w("fullscreen"),w("pip")]).describe("Display mode for UI presentation."),ET=ue([w("--color-background-primary"),w("--color-background-secondary"),w("--color-background-tertiary"),w("--color-background-inverse"),w("--color-background-ghost"),w("--color-background-info"),w("--color-background-danger"),w("--color-background-success"),w("--color-background-warning"),w("--color-background-disabled"),w("--color-text-primary"),w("--color-text-secondary"),w("--color-text-tertiary"),w("--color-text-inverse"),w("--color-text-ghost"),w("--color-text-info"),w("--color-text-danger"),w("--color-text-success"),w("--color-text-warning"),w("--color-text-disabled"),w("--color-border-primary"),w("--color-border-secondary"),w("--color-border-tertiary"),w("--color-border-inverse"),w("--color-border-ghost"),w("--color-border-info"),w("--color-border-danger"),w("--color-border-success"),w("--color-border-warning"),w("--color-border-disabled"),w("--color-ring-primary"),w("--color-ring-secondary"),w("--color-ring-inverse"),w("--color-ring-info"),w("--color-ring-danger"),w("--color-ring-success"),w("--color-ring-warning"),w("--font-sans"),w("--font-mono"),w("--font-weight-normal"),w("--font-weight-medium"),w("--font-weight-semibold"),w("--font-weight-bold"),w("--font-text-xs-size"),w("--font-text-sm-size"),w("--font-text-md-size"),w("--font-text-lg-size"),w("--font-heading-xs-size"),w("--font-heading-sm-size"),w("--font-heading-md-size"),w("--font-heading-lg-size"),w("--font-heading-xl-size"),w("--font-heading-2xl-size"),w("--font-heading-3xl-size"),w("--font-text-xs-line-height"),w("--font-text-sm-line-height"),w("--font-text-md-line-height"),w("--font-text-lg-line-height"),w("--font-heading-xs-line-height"),w("--font-heading-sm-line-height"),w("--font-heading-md-line-height"),w("--font-heading-lg-line-height"),w("--font-heading-xl-line-height"),w("--font-heading-2xl-line-height"),w("--font-heading-3xl-line-height"),w("--border-radius-xs"),w("--border-radius-sm"),w("--border-radius-md"),w("--border-radius-lg"),w("--border-radius-xl"),w("--border-radius-full"),w("--border-width-regular"),w("--shadow-hairline"),w("--shadow-sm"),w("--shadow-md"),w("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),IT=Ce(ET.describe(`Style variables for theming MCP apps.
151
151
 
152
152
  Individual style keys are optional - hosts may provide any subset of these values.
153
153
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
154
154
 
155
155
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
156
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),ue([S(),du()]).describe(`Style variables for theming MCP apps.
156
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),ue([S(),_u()]).describe(`Style variables for theming MCP apps.
157
157
 
158
158
  Individual style keys are optional - hosts may provide any subset of these values.
159
159
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -165,10 +165,10 @@ Individual style keys are optional - hosts may provide any subset of these value
165
165
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
166
166
 
167
167
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
168
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),xT=C({method:w("ui/open-link"),params:C({url:S().describe("URL to open in the host's browser")})}),RL=C({isError:ze().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),$L=C({isError:ze().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),ML=C({isError:ze().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),bT=C({method:w("ui/notifications/sandbox-proxy-ready"),params:C({})}),Fu=C({connectDomains:ie(S()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
168
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),AT=C({method:w("ui/open-link"),params:C({url:S().describe("URL to open in the host's browser")})}),VL=C({isError:ze().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),GL=C({isError:ze().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),XL=C({isError:ze().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),zT=C({method:w("ui/notifications/sandbox-proxy-ready"),params:C({})}),Ku=C({connectDomains:ie(S()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
169
169
 
170
170
  - Maps to CSP \`connect-src\` directive
171
- - Empty or omitted → no network connections (secure default)`),resourceDomains:ie(S()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:ie(S()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:ie(S()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),ju=C({camera:C({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:C({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:C({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:C({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),wT=C({method:w("ui/notifications/size-changed"),params:C({width:ce().optional().describe("New width in pixels."),height:ce().optional().describe("New height in pixels.")})}),OL=C({method:w("ui/notifications/tool-input"),params:C({arguments:Ce(S(),Ie().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),LL=C({method:w("ui/notifications/tool-input-partial"),params:C({arguments:Ce(S(),Ie().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),DL=C({method:w("ui/notifications/tool-cancelled"),params:C({reason:S().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),_T=C({fonts:S().optional()}),ST=C({variables:yT.optional().describe("CSS variables for theming the app."),css:_T.optional().describe("CSS blocks that apps can inject.")}),FL=C({method:w("ui/resource-teardown"),params:C({})}),kT=Ce(S(),Ie()),Fy=C({text:C({}).optional().describe("Host supports text content blocks."),image:C({}).optional().describe("Host supports image content blocks."),audio:C({}).optional().describe("Host supports audio content blocks."),resource:C({}).optional().describe("Host supports resource content blocks."),resourceLink:C({}).optional().describe("Host supports resource link content blocks."),structuredContent:C({}).optional().describe("Host supports structured content.")}),CT=C({method:w("ui/notifications/request-teardown"),params:C({}).optional()}),TT=C({experimental:C({}).optional().describe("Experimental features (structure TBD)."),openLinks:C({}).optional().describe("Host supports opening external URLs."),downloadFile:C({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:C({listChanged:ze().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:C({listChanged:ze().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:C({}).optional().describe("Host accepts log messages."),sandbox:C({permissions:ju.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Fu.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Fy.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Fy.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),ET=C({experimental:C({}).optional().describe("Experimental features (structure TBD)."),tools:C({listChanged:ze().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:ie(gi).optional().describe("Display modes the app supports.")}),IT=C({method:w("ui/notifications/initialized"),params:C({}).optional()}),jL=C({csp:Fu.optional().describe("Content Security Policy configuration for UI resources."),permissions:ju.optional().describe("Sandbox permissions requested by the UI resource."),domain:S().optional().describe(`Dedicated origin for view sandbox.
171
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:ie(S()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:ie(S()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:ie(S()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Ju=C({camera:C({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:C({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:C({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:C({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),PT=C({method:w("ui/notifications/size-changed"),params:C({width:ce().optional().describe("New width in pixels."),height:ce().optional().describe("New height in pixels.")})}),KL=C({method:w("ui/notifications/tool-input"),params:C({arguments:Ce(S(),Ie().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),JL=C({method:w("ui/notifications/tool-input-partial"),params:C({arguments:Ce(S(),Ie().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),YL=C({method:w("ui/notifications/tool-cancelled"),params:C({reason:S().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),NT=C({fonts:S().optional()}),RT=C({variables:IT.optional().describe("CSS variables for theming the app."),css:NT.optional().describe("CSS blocks that apps can inject.")}),QL=C({method:w("ui/resource-teardown"),params:C({})}),$T=Ce(S(),Ie()),Qy=C({text:C({}).optional().describe("Host supports text content blocks."),image:C({}).optional().describe("Host supports image content blocks."),audio:C({}).optional().describe("Host supports audio content blocks."),resource:C({}).optional().describe("Host supports resource content blocks."),resourceLink:C({}).optional().describe("Host supports resource link content blocks."),structuredContent:C({}).optional().describe("Host supports structured content.")}),MT=C({method:w("ui/notifications/request-teardown"),params:C({}).optional()}),OT=C({experimental:C({}).optional().describe("Experimental features (structure TBD)."),openLinks:C({}).optional().describe("Host supports opening external URLs."),downloadFile:C({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:C({listChanged:ze().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:C({listChanged:ze().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:C({}).optional().describe("Host accepts log messages."),sandbox:C({permissions:Ju.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Ku.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Qy.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Qy.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),LT=C({experimental:C({}).optional().describe("Experimental features (structure TBD)."),tools:C({listChanged:ze().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:ie(bi).optional().describe("Display modes the app supports.")}),DT=C({method:w("ui/notifications/initialized"),params:C({}).optional()}),eD=C({csp:Ku.optional().describe("Content Security Policy configuration for UI resources."),permissions:Ju.optional().describe("Sandbox permissions requested by the UI resource."),domain:S().optional().describe(`Dedicated origin for view sandbox.
172
172
 
173
173
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
174
174
 
@@ -182,10 +182,10 @@ Boolean requesting whether a visible border and background is provided by the ho
182
182
 
183
183
  - \`true\`: request visible border + background
184
184
  - \`false\`: request no visible border + background
185
- - omitted: host decides border`)}),jy=C({method:w("ui/request-display-mode"),params:C({mode:gi.describe("The display mode being requested.")})}),ZL=C({mode:gi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),AT=ue([w("model"),w("app")]).describe("Tool visibility scope - who can access the tool."),HL=C({resourceUri:S().optional(),visibility:ie(AT).optional().describe(`Who can access this tool. Default: ["model", "app"]
185
+ - omitted: host decides border`)}),ex=C({method:w("ui/request-display-mode"),params:C({mode:bi.describe("The display mode being requested.")})}),tD=C({mode:bi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),FT=ue([w("model"),w("app")]).describe("Tool visibility scope - who can access the tool."),nD=C({resourceUri:S().optional(),visibility:ie(FT).optional().describe(`Who can access this tool. Default: ["model", "app"]
186
186
  - "model": Tool visible to and callable by the agent
187
- - "app": Tool callable by the app from this server only`)}),BL=C({mimeTypes:ie(S()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),zT=C({method:w("ui/download-file"),params:C({contents:ie(ue([Nu,Ru])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),PT=C({method:w("ui/message"),params:C({role:w("user").describe('Message role, currently only "user" is supported.'),content:ie(pr).describe("Message content blocks (text, image, etc.).")})}),UL=C({method:w("ui/notifications/sandbox-resource-ready"),params:C({html:S().describe("HTML content to load into the inner iframe."),sandbox:S().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Fu.optional().describe("CSP configuration from resource metadata."),permissions:ju.optional().describe("Sandbox permissions from resource metadata.")})}),WL=C({method:w("ui/notifications/tool-result"),params:xo.describe("Standard MCP tool execution result.")}),Hy=C({toolInfo:C({id:ur.optional().describe("JSON-RPC id of the tools/call request."),tool:xa.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:gT.optional().describe("Current color theme preference."),styles:ST.optional().describe("Style configuration for theming the app."),displayMode:gi.optional().describe("How the UI is currently displayed."),availableDisplayModes:ie(gi).optional().describe("Display modes the host supports."),containerDimensions:ue([C({height:ce().describe("Fixed container height in pixels.")}),C({maxHeight:ue([ce(),du()]).optional().describe("Maximum container height in pixels.")})]).and(ue([C({width:ce().describe("Fixed container width in pixels.")}),C({maxWidth:ue([ce(),du()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
188
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:S().optional().describe("User's language and region preference in BCP 47 format."),timeZone:S().optional().describe("User's timezone in IANA format."),userAgent:S().optional().describe("Host application identifier."),platform:ue([w("web"),w("desktop"),w("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:C({touch:ze().optional().describe("Whether the device supports touch input."),hover:ze().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:C({top:ce().describe("Top safe area inset in pixels."),right:ce().describe("Right safe area inset in pixels."),bottom:ce().describe("Bottom safe area inset in pixels."),left:ce().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),qL=C({method:w("ui/notifications/host-context-changed"),params:Hy.describe("Partial context update containing only changed fields.")}),NT=C({method:w("ui/update-model-context"),params:C({content:ie(pr).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Ce(S(),Ie().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),RT=C({method:w("ui/initialize"),params:C({appInfo:li.describe("App identification (name and version)."),appCapabilities:ET.describe("Features and capabilities this app provides."),protocolVersion:S().describe("Protocol version this app supports.")})}),VL=C({protocolVersion:S().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:li.describe("Host application identification and version."),hostCapabilities:TT.describe("Features and capabilities provided by the host."),hostContext:Hy.describe("Rich context about the host environment.")}).passthrough();class Zu{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(n)=>{if(t&&n.source!==this.eventSource){console.debug("Ignoring message from unknown source",n);return}let o=Ay.safeParse(n.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(n.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,n);else console.error("Failed to parse message",o.error.message,n),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==hT)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}function By(e){if(!e)return"";let t=[];if(e.camera)t.push("camera");if(e.microphone)t.push("microphone");if(e.geolocation)t.push("geolocation");if(e.clipboardWrite)t.push("clipboard-write");return t.join("; ")}var $T=[Zy];class Hu extends ka{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;constructor(e,t,n,o){super(o);this._client=e,this._hostInfo=t,this._capabilities=n,this._hostContext=o?.hostContext||{},this.setRequestHandler(RT,(r)=>this._oninitialize(r)),this.setRequestHandler(yo,(r,s)=>(this.onping?.(r.params,s),{})),this.setRequestHandler(jy,(r)=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;set onsizechange(e){this.setNotificationHandler(wT,(t)=>e(t.params))}set onsandboxready(e){this.setNotificationHandler(bT,(t)=>e(t.params))}set oninitialized(e){this.setNotificationHandler(IT,(t)=>e(t.params))}set onmessage(e){this.setRequestHandler(PT,async(t,n)=>e(t.params,n))}set onopenlink(e){this.setRequestHandler(xT,async(t,n)=>e(t.params,n))}set ondownloadfile(e){this.setRequestHandler(zT,async(t,n)=>e(t.params,n))}set onrequestteardown(e){this.setNotificationHandler(CT,(t)=>e(t.params))}set onrequestdisplaymode(e){this.setRequestHandler(jy,async(t,n)=>e(t.params,n))}set onloggingmessage(e){this.setNotificationHandler(Ou,async(t)=>{e(t.params)})}set onupdatemodelcontext(e){this.setRequestHandler(NT,async(t,n)=>e(t.params,n))}set oncalltool(e){this.setRequestHandler(wa,async(t,n)=>e(t.params,n))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}set onlistresources(e){this.setRequestHandler(wu,async(t,n)=>e(t.params,n))}set onlistresourcetemplates(e){this.setRequestHandler(_u,async(t,n)=>e(t.params,n))}set onreadresource(e){this.setRequestHandler(Cu,async(t,n)=>e(t.params,n))}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}set onlistprompts(e){this.setRequestHandler(Eu,async(t,n)=>e(t.params,n))}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}assertTaskCapability(e){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(e){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(e){let t=e.params.protocolVersion;return this._appCapabilities=e.params.appCapabilities,this._appInfo=e.params.appInfo,{protocolVersion:$T.includes(t)?t:Zy,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let o of Object.keys(e)){let r=this._hostContext[o],s=e[o];if(MT(r,s))continue;t[o]=s,n=!0}if(n)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},kT,t)}sendResourceTeardown=this.teardownResource;async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(n,o)=>this._client.request({method:"tools/call",params:n},xo,{signal:o.signal}),t.tools.listChanged)this._client.setNotificationHandler(Mu,(n)=>this.sendToolListChanged(n.params))}if(t.resources){if(this.onlistresources=async(n,o)=>this._client.request({method:"resources/list",params:n},va,{signal:o.signal}),this.onlistresourcetemplates=async(n,o)=>this._client.request({method:"resources/templates/list",params:n},Su,{signal:o.signal}),this.onreadresource=async(n,o)=>this._client.request({method:"resources/read",params:n},ya,{signal:o.signal}),t.resources.listChanged)this._client.setNotificationHandler(Tu,(n)=>this.sendResourceListChanged(n.params))}if(t.prompts){if(this.onlistprompts=async(n,o)=>this._client.request({method:"prompts/list",params:n},Iu,{signal:o.signal}),t.prompts.listChanged)this._client.setNotificationHandler($u,(n)=>this.sendPromptListChanged(n.params))}}return super.connect(e)}}function MT(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Bu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function OT(e){return Bu(e)&&Array.isArray(e.content)&&e.content.every((t)=>Bu(t)&&typeof t.type==="string")}function LT(...e){for(let t of e)if(typeof t==="string"){if(t.trim().length>0)return t}return}function DT(e){if(typeof e==="string")return e;if(e===void 0)return;try{return JSON.stringify(e)}catch(t){return console.debug("[ext-app-tool-result] stringify failed",t),String(e)}}function Uu(e){let t=e.success===!1;if(OT(e.result))return{...e.result,isError:e.result.isError===!0||t};let n=Bu(e.result)?e.result:null,o=LT(e.detailedContent,e.content,n?.detailedContent,n?.content,n?.textResultForLlm,n?.text,n?.message,typeof e.result==="string"?e.result:void 0,e.error)??DT(e.result);return{content:o?[{type:"text",text:o}]:[],isError:t}}function Uy(e,t){if(e===t)return!0;if(e.isError!==t.isError)return!1;try{let n=JSON.stringify(e),o=JSON.stringify(t);if(n===void 0||o===void 0)return!1;if(Math.abs(n.length-o.length)>2000000)return!1;return n===o}catch{return!1}}function Wy(e){return Boolean(e)&&typeof e==="object"&&e!==null&&!Array.isArray(e)&&"ok"in e&&typeof e.ok==="boolean"}async function FT(e,t){let n=await fetch("/api/canvas/frame-documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({html:e,sandbox:t})}),o=await n.json();if(!n.ok||!Wy(o)||!o.ok||typeof o.url!=="string"){let r=Wy(o)&&o.error?o.error:`Frame document request failed with HTTP ${n.status}`;throw Error(r)}return o.url}function qy(e,t){let n=gt.value,[o,r]=L(null),[s,a]=L(0),c=R(0);D(()=>{if(r(null),!e||n!=="src")return;let u=!1;return c.current=co.value,FT(e,t).then((d)=>{if(!u)r(d)}).catch((d)=>{console.error("[iframe-document] failed to create frame document:",d)}),()=>{u=!0}},[e,t,n,s]);let l=co.value;return D(()=>{if(n!=="src"||l===c.current)return;if(!o){a((d)=>d+1);return}let u=!1;return fetch(o,{method:"HEAD"}).then((d)=>{if(u)return;if(d.ok){c.current=l;return}a((p)=>p+1)}).catch(()=>{}),()=>{u=!0}},[l,o,n]),Ae(()=>{if(n==="srcdoc"&&e)return{attributes:{srcdoc:e},ready:!0,key:`srcdoc-${tr(e)}`};return{attributes:o?{src:o}:{},ready:Boolean(o),key:o??""}},[o,n,e])}function fr(e){let{enabled:t,token:n,nodeId:o,sourceSurface:r,iframeRef:s}=e;D(()=>{if(!t||!n)return;function a(c){if(c.source!==s.current?.contentWindow)return;let l=c.data;if(!l||l.source!==Rs||l.token!==n||l.nodeId!==o)return;let u=l.interaction;if(!u||typeof u.type!=="string")return;let d=u.type;ss({type:d,sourceNodeId:o,sourceSurface:r,...u.payload&&typeof u.payload==="object"?{payload:u.payload}:{}}).then((p)=>{if(p.ok)Wo("context","AX interaction",d,[o]);else Wo("remove","AX interaction rejected",p.error??p.code??"",[o]);s.current?.contentWindow?.postMessage({source:$s,token:n,...l.correlationId?{correlationId:l.correlationId}:{},interaction:{type:d},result:p},"*")})}return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[t,n,o,r])}async function bo(e,t){let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!o.ok)throw Error(o.error??`Request failed: ${e}`);return o.result}function wo(e){return/AppleWebKit/.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/.test(e)}function jT(e){let{userAgent:t,visibilityState:n,rect:o,viewport:r,alreadyRearmed:s}=e;if(s)return!1;if(!wo(t))return!1;if(n!=="hidden")return!1;if(o.width<=0||o.height<=0)return!1;return o.bottom>0&&o.right>0&&o.top<r.height&&o.left<r.width}var ex=1000,Vy=7000;function nt(e,t){if(typeof window>"u")return;let n=window;if(n.__PMX_EXTAPP_LOG??=[],n.__PMX_EXTAPP_LOG.length<500)n.__PMX_EXTAPP_LOG.push({t:Date.now(),nodeId:e,event:t});ZT({t:Date.now(),nodeId:e,event:t})}var Gy=[],Wu=null;function ZT(e){if(Gy.push({...e,...typeof document<"u"?{visibility:document.visibilityState}:{}}),Wu)return;Wu=setTimeout(()=>{Wu=null;let t=Gy.splice(0);if(t.length===0)return;fetch("/api/canvas/debug/ext-app-recovery",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:t})}).catch(()=>{})},1500)}var Xy=Promise.resolve();function Ky(e){Xy=Xy.then(async()=>{if(!e.remount())return;await e.awaitBoot(),await new Promise((t)=>setTimeout(t,ex))}).catch(()=>{})}function HT(e,t){let n=typeof e.data.html==="string"?e.data.html:"",o=typeof e.data.serverName==="string"?e.data.serverName:"",r=typeof e.data.appSessionId==="string"?e.data.appSessionId:"",s=typeof e.data.sessionStatus==="string"?e.data.sessionStatus:"";return`${e.id}:${t}:${o}:${r}:${s}:${n}`}function BT(e,t){if(e==="fullscreen")return{nextMode:"fullscreen",shouldExpand:!t,shouldCollapse:!1};if(e==="inline")return{nextMode:"inline",shouldExpand:!1,shouldCollapse:t};return{nextMode:e,shouldExpand:!1,shouldCollapse:!1}}async function Jy(e,t,n){if(await e.sendToolInput({arguments:t}),n)await e.sendToolResult(n)}function UT(e){return typeof e==="string"&&e.trim().length>0?e.trim():_l}function WT(e,t){return`<script data-pmx-canvas-ax-bridge>
187
+ - "app": Tool callable by the app from this server only`)}),oD=C({mimeTypes:ie(S()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),jT=C({method:w("ui/download-file"),params:C({contents:ie(ue([Bu,Uu])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),ZT=C({method:w("ui/message"),params:C({role:w("user").describe('Message role, currently only "user" is supported.'),content:ie(mr).describe("Message content blocks (text, image, etc.).")})}),rD=C({method:w("ui/notifications/sandbox-resource-ready"),params:C({html:S().describe("HTML content to load into the inner iframe."),sandbox:S().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Ku.optional().describe("CSP configuration from resource metadata."),permissions:Ju.optional().describe("Sandbox permissions from resource metadata.")})}),iD=C({method:w("ui/notifications/tool-result"),params:bo.describe("Standard MCP tool execution result.")}),nx=C({toolInfo:C({id:pr.optional().describe("JSON-RPC id of the tools/call request."),tool:za.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:TT.optional().describe("Current color theme preference."),styles:RT.optional().describe("Style configuration for theming the app."),displayMode:bi.optional().describe("How the UI is currently displayed."),availableDisplayModes:ie(bi).optional().describe("Display modes the host supports."),containerDimensions:ue([C({height:ce().describe("Fixed container height in pixels.")}),C({maxHeight:ue([ce(),_u()]).optional().describe("Maximum container height in pixels.")})]).and(ue([C({width:ce().describe("Fixed container width in pixels.")}),C({maxWidth:ue([ce(),_u()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
188
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:S().optional().describe("User's language and region preference in BCP 47 format."),timeZone:S().optional().describe("User's timezone in IANA format."),userAgent:S().optional().describe("Host application identifier."),platform:ue([w("web"),w("desktop"),w("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:C({touch:ze().optional().describe("Whether the device supports touch input."),hover:ze().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:C({top:ce().describe("Top safe area inset in pixels."),right:ce().describe("Right safe area inset in pixels."),bottom:ce().describe("Bottom safe area inset in pixels."),left:ce().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),sD=C({method:w("ui/notifications/host-context-changed"),params:nx.describe("Partial context update containing only changed fields.")}),HT=C({method:w("ui/update-model-context"),params:C({content:ie(mr).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Ce(S(),Ie().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),BT=C({method:w("ui/initialize"),params:C({appInfo:fi.describe("App identification (name and version)."),appCapabilities:LT.describe("Features and capabilities this app provides."),protocolVersion:S().describe("Protocol version this app supports.")})}),aD=C({protocolVersion:S().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:fi.describe("Host application identification and version."),hostCapabilities:OT.describe("Features and capabilities provided by the host."),hostContext:nx.describe("Rich context about the host environment.")}).passthrough();class Yu{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(n)=>{if(t&&n.source!==this.eventSource){console.debug("Ignoring message from unknown source",n);return}let o=By.safeParse(n.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(n.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,n);else console.error("Failed to parse message",o.error.message,n),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==CT)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}function ox(e){if(!e)return"";let t=[];if(e.camera)t.push("camera");if(e.microphone)t.push("microphone");if(e.geolocation)t.push("geolocation");if(e.clipboardWrite)t.push("clipboard-write");return t.join("; ")}var UT=[tx];class Qu extends Ma{_client;_hostInfo;_capabilities;_appCapabilities;_hostContext={};_appInfo;constructor(e,t,n,o){super(o);this._client=e,this._hostInfo=t,this._capabilities=n,this._hostContext=o?.hostContext||{},this.setRequestHandler(BT,(r)=>this._oninitialize(r)),this.setRequestHandler(xo,(r,s)=>(this.onping?.(r.params,s),{})),this.setRequestHandler(ex,(r)=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;set onsizechange(e){this.setNotificationHandler(PT,(t)=>e(t.params))}set onsandboxready(e){this.setNotificationHandler(zT,(t)=>e(t.params))}set oninitialized(e){this.setNotificationHandler(DT,(t)=>e(t.params))}set onmessage(e){this.setRequestHandler(ZT,async(t,n)=>e(t.params,n))}set onopenlink(e){this.setRequestHandler(AT,async(t,n)=>e(t.params,n))}set ondownloadfile(e){this.setRequestHandler(jT,async(t,n)=>e(t.params,n))}set onrequestteardown(e){this.setNotificationHandler(MT,(t)=>e(t.params))}set onrequestdisplaymode(e){this.setRequestHandler(ex,async(t,n)=>e(t.params,n))}set onloggingmessage(e){this.setNotificationHandler(Vu,async(t)=>{e(t.params)})}set onupdatemodelcontext(e){this.setRequestHandler(HT,async(t,n)=>e(t.params,n))}set oncalltool(e){this.setRequestHandler(Na,async(t,n)=>e(t.params,n))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}set onlistresources(e){this.setRequestHandler(Nu,async(t,n)=>e(t.params,n))}set onlistresourcetemplates(e){this.setRequestHandler(Ru,async(t,n)=>e(t.params,n))}set onreadresource(e){this.setRequestHandler(Ou,async(t,n)=>e(t.params,n))}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}set onlistprompts(e){this.setRequestHandler(Du,async(t,n)=>e(t.params,n))}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}assertTaskCapability(e){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(e){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(e){let t=e.params.protocolVersion;return this._appCapabilities=e.params.appCapabilities,this._appInfo=e.params.appInfo,{protocolVersion:UT.includes(t)?t:tx,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let o of Object.keys(e)){let r=this._hostContext[o],s=e[o];if(WT(r,s))continue;t[o]=s,n=!0}if(n)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},$T,t)}sendResourceTeardown=this.teardownResource;async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(n,o)=>this._client.request({method:"tools/call",params:n},bo,{signal:o.signal}),t.tools.listChanged)this._client.setNotificationHandler(qu,(n)=>this.sendToolListChanged(n.params))}if(t.resources){if(this.onlistresources=async(n,o)=>this._client.request({method:"resources/list",params:n},Ia,{signal:o.signal}),this.onlistresourcetemplates=async(n,o)=>this._client.request({method:"resources/templates/list",params:n},$u,{signal:o.signal}),this.onreadresource=async(n,o)=>this._client.request({method:"resources/read",params:n},Aa,{signal:o.signal}),t.resources.listChanged)this._client.setNotificationHandler(Lu,(n)=>this.sendResourceListChanged(n.params))}if(t.prompts){if(this.onlistprompts=async(n,o)=>this._client.request({method:"prompts/list",params:n},Fu,{signal:o.signal}),t.prompts.listChanged)this._client.setNotificationHandler(Wu,(n)=>this.sendPromptListChanged(n.params))}}return super.connect(e)}}function WT(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ed(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function qT(e){return ed(e)&&Array.isArray(e.content)&&e.content.every((t)=>ed(t)&&typeof t.type==="string")}function VT(...e){for(let t of e)if(typeof t==="string"){if(t.trim().length>0)return t}return}function GT(e){if(typeof e==="string")return e;if(e===void 0)return;try{return JSON.stringify(e)}catch(t){return console.debug("[ext-app-tool-result] stringify failed",t),String(e)}}function td(e){let t=e.success===!1;if(qT(e.result))return{...e.result,isError:e.result.isError===!0||t};let n=ed(e.result)?e.result:null,o=VT(e.detailedContent,e.content,n?.detailedContent,n?.content,n?.textResultForLlm,n?.text,n?.message,typeof e.result==="string"?e.result:void 0,e.error)??GT(e.result);return{content:o?[{type:"text",text:o}]:[],isError:t}}function rx(e,t){if(e===t)return!0;if(e.isError!==t.isError)return!1;try{let n=JSON.stringify(e),o=JSON.stringify(t);if(n===void 0||o===void 0)return!1;if(Math.abs(n.length-o.length)>2000000)return!1;return n===o}catch{return!1}}function ix(e){return Boolean(e)&&typeof e==="object"&&e!==null&&!Array.isArray(e)&&"ok"in e&&typeof e.ok==="boolean"}async function XT(e,t){let n=await fetch("/api/canvas/frame-documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({html:e,sandbox:t})}),o=await n.json();if(!n.ok||!ix(o)||!o.ok||typeof o.url!=="string"){let r=ix(o)&&o.error?o.error:`Frame document request failed with HTTP ${n.status}`;throw Error(r)}return o.url}function sx(e,t){let n=gt.value,[o,r]=L(null),[s,a]=L(0),c=M(0);D(()=>{if(r(null),!e||n!=="src")return;let u=!1;return c.current=co.value,XT(e,t).then((d)=>{if(!u)r(d)}).catch((d)=>{console.error("[iframe-document] failed to create frame document:",d)}),()=>{u=!0}},[e,t,n,s]);let l=co.value;return D(()=>{if(n!=="src"||l===c.current)return;if(!o){a((d)=>d+1);return}let u=!1;return fetch(o,{method:"HEAD"}).then((d)=>{if(u)return;if(d.ok){c.current=l;return}a((p)=>p+1)}).catch(()=>{}),()=>{u=!0}},[l,o,n]),Ae(()=>{if(n==="srcdoc"&&e)return{attributes:{srcdoc:e},ready:!0,key:`srcdoc-${er(e)}`};return{attributes:o?{src:o}:{},ready:Boolean(o),key:o??""}},[o,n,e])}function hr(e){let{enabled:t,token:n,nodeId:o,sourceSurface:r,iframeRef:s}=e;D(()=>{if(!t||!n)return;function a(c){if(c.source!==s.current?.contentWindow)return;let l=c.data;if(!l||l.source!==Os||l.token!==n||l.nodeId!==o)return;let u=l.interaction;if(!u||typeof u.type!=="string")return;let d=u.type;cs({type:d,sourceNodeId:o,sourceSurface:r,...u.payload&&typeof u.payload==="object"?{payload:u.payload}:{}}).then((p)=>{if(p.ok)Wo("context","AX interaction",d,[o]);else Wo("remove","AX interaction rejected",p.error??p.code??"",[o]);s.current?.contentWindow?.postMessage({source:Ls,token:n,...l.correlationId?{correlationId:l.correlationId}:{},interaction:{type:d},result:p},"*")})}return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[t,n,o,r])}async function wo(e,t){let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!o.ok)throw Error(o.error??`Request failed: ${e}`);return o.result}function _o(e){return/AppleWebKit/.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/.test(e)}function KT(e){let{userAgent:t,visibilityState:n,rect:o,viewport:r,alreadyRearmed:s}=e;if(s)return!1;if(!_o(t))return!1;if(n!=="hidden")return!1;if(o.width<=0||o.height<=0)return!1;return o.bottom>0&&o.right>0&&o.top<r.height&&o.left<r.width}var mx=1000,ax=7000;function ot(e,t){if(typeof window>"u")return;let n=window;if(n.__PMX_EXTAPP_LOG??=[],n.__PMX_EXTAPP_LOG.length<500)n.__PMX_EXTAPP_LOG.push({t:Date.now(),nodeId:e,event:t});JT({t:Date.now(),nodeId:e,event:t})}var cx=[],nd=null;function JT(e){if(cx.push({...e,...typeof document<"u"?{visibility:document.visibilityState}:{}}),nd)return;nd=setTimeout(()=>{nd=null;let t=cx.splice(0);if(t.length===0)return;fetch("/api/canvas/debug/ext-app-recovery",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:t})}).catch(()=>{})},1500)}var lx=Promise.resolve();function ux(e){lx=lx.then(async()=>{if(!e.remount())return;await e.awaitBoot(),await new Promise((t)=>setTimeout(t,mx))}).catch(()=>{})}function YT(e,t){let n=typeof e.data.html==="string"?e.data.html:"",o=typeof e.data.serverName==="string"?e.data.serverName:"",r=typeof e.data.appSessionId==="string"?e.data.appSessionId:"",s=typeof e.data.sessionStatus==="string"?e.data.sessionStatus:"";return`${e.id}:${t}:${o}:${r}:${s}:${n}`}function QT(e,t){if(e==="fullscreen")return{nextMode:"fullscreen",shouldExpand:!t,shouldCollapse:!1};if(e==="inline")return{nextMode:"inline",shouldExpand:!1,shouldCollapse:t};return{nextMode:e,shouldExpand:!1,shouldCollapse:!1}}async function dx(e,t,n){if(await e.sendToolInput({arguments:t}),n)await e.sendToolResult(n)}function eE(e){return typeof e==="string"&&e.trim().length>0?e.trim():Cl}function tE(e,t){return`<script data-pmx-canvas-ax-bridge>
189
189
  (function () {
190
190
  const PMX_AX_TOKEN = ${JSON.stringify(e)};
191
191
  const PMX_AX_NODE_ID = ${JSON.stringify(t)};
@@ -203,7 +203,7 @@ container holding the app. Specify either width or maxWidth, and either height o
203
203
  }, 10000);
204
204
  pending.set(correlationId, function (result) { clearTimeout(timer); resolve(result); });
205
205
  window.parent.postMessage({
206
- source: '${Rs}',
206
+ source: '${Os}',
207
207
  token: PMX_AX_TOKEN,
208
208
  nodeId: PMX_AX_NODE_ID,
209
209
  correlationId: correlationId,
@@ -216,7 +216,7 @@ container holding the app. Specify either width or maxWidth, and either height o
216
216
  };
217
217
  window.addEventListener('message', function (event) {
218
218
  const m = event.data;
219
- if (!m || m.source !== '${$s}' || m.token !== PMX_AX_TOKEN) return;
219
+ if (!m || m.source !== '${Ls}' || m.token !== PMX_AX_TOKEN) return;
220
220
  const result = m.result || { ok: false };
221
221
  const resolver = m.correlationId ? pending.get(m.correlationId) : undefined;
222
222
  if (resolver) { pending.delete(m.correlationId); resolver(result); }
@@ -226,11 +226,11 @@ container holding the app. Specify either width or maxWidth, and either height o
226
226
  try { window.dispatchEvent(new CustomEvent('pmx-ax-ack', { detail: { result: result, interaction: m.interaction || null } })); } catch (e) {}
227
227
  });
228
228
  })();
229
- </script>`}function qT(e,t){return`<script data-pmx-canvas-boot-beacon>
229
+ </script>`}function nE(e,t){return`<script data-pmx-canvas-boot-beacon>
230
230
  (function () {
231
231
  var TOKEN = ${JSON.stringify(e)};
232
232
  var NODE_ID = ${JSON.stringify(t)};
233
- window.parent.postMessage({ source: '${Ms}', token: TOKEN, nodeId: NODE_ID }, '*');
233
+ window.parent.postMessage({ source: '${Ds}', token: TOKEN, nodeId: NODE_ID }, '*');
234
234
  // Paint-tick answers (Finding N): a double rAF only fires when this frame's
235
235
  // rendering pipeline is actually running — a frame whose layer WebKit never
236
236
  // composites stays silent, and that silence drives the parent's recovery
@@ -300,15 +300,15 @@ container holding the app. Specify either width or maxWidth, and either height o
300
300
  requestAnimationFrame(function () {
301
301
  requestAnimationFrame(function () {
302
302
  var v = contentVerdict();
303
- window.parent.postMessage({ source: '${Ms}', token: TOKEN, nodeId: NODE_ID, kind: 'paint-tick', content: v.content, detail: v.detail }, '*');
303
+ window.parent.postMessage({ source: '${Ds}', token: TOKEN, nodeId: NODE_ID, kind: 'paint-tick', content: v.content, detail: v.detail }, '*');
304
304
  });
305
305
  });
306
306
  }
307
307
  window.addEventListener('message', function (event) {
308
308
  var m = event.data;
309
- if (m && m.source === '${wl}' && m.token === TOKEN) sendPaintTick();
309
+ if (m && m.source === '${kl}' && m.token === TOKEN) sendPaintTick();
310
310
  });
311
311
  sendPaintTick();
312
312
  })();
313
- </script>`}function Yy(){return"<style data-pmx-canvas-ext-app-base>html, body { background: transparent !important; }</style>"}function Qy(e,t){if(!t)return e;let n=/<head\b[^>]*>/i.exec(e);if(n?.index!==void 0){let r=n.index+n[0].length;return`${e.slice(0,r)}${t}${e.slice(r)}`}let o=/<body\b[^>]*>/i.exec(e);if(o?.index!==void 0){let r=o.index+o[0].length;return`${e.slice(0,r)}${t}${e.slice(r)}`}return`${t}${e}`}function mr(e,t){if(Number.isFinite(e)&&e>0)return Math.round(e);if(Number.isFinite(t)&&t>0)return Math.round(t);return 1}function qu(e,t){let n=e?.getBoundingClientRect();return{width:mr(e?.clientWidth??0,mr(n?.width??0,t.width)),height:mr(e?.clientHeight??0,mr(n?.height??0,t.height))}}function VT(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0&&!t}function GT(e,t){return Math.max(mr(e,1),mr(t,1))}function tx({node:e,expanded:t=!1}){let n=R(null),o=R(null),r=R(null),s=R(null),a=R({}),c=R(void 0),l=R(!1),u=R(void 0),d=R(null),p=R(!1),m=R(null),f=R(0),g=R([]),y=R(""),x=R(!1),h=R(!1),v=R([]),b=R(!1),z=R(!1),F=R(!1),_=R(!1),[k,T]=L("loading"),[P,Z]=L(null),[j,E]=L(0),[B,W]=L(!1),[H,U]=L(!1),[ee,xe]=L(()=>t||typeof navigator>"u"||typeof window>"u"||!wo(navigator.userAgent)),Fe=e.data.html,We=e.data.serverName,Te=e.data.appSessionId,eo=e.data.toolInput??{},Ft=e.data.toolResult,Xt=e.data.toolName??"ext-app",I=e.data.toolDefinition,K=e.data.toolCallId,le=typeof K==="string"||typeof K==="number"?K:void 0,Y=e.data.resourceMeta,J=e.data.sessionStatus,Q=e.data.sessionError,te=e.size.height,q=e.id,ae=HT(e,j),mt=UT(null),N=e.data.axCapabilities?.enabled===!0&&typeof Fe==="string"&&Fe.length>0,se=Ae(()=>`ax-${crypto.randomUUID()}`,[]),Me=N?WT(se,q):"",de=typeof Fe==="string"&&Fe.length>0?qT(se,q):"",jt=qy(Qy(Fe??"",Yy()+de+Me),mt);D(()=>{function G(ne){if(ne.source!==n.current?.contentWindow)return;let me=ne.data;if(!me||me.source!==Ms||me.token!==se||me.nodeId!==q)return;if(h.current=!0,me.kind==="paint-tick"){let Pe=me,Nt={content:Pe.content===!0,detail:typeof Pe.detail==="string"?Pe.detail:""};for(let Cn of g.current.splice(0))Cn(Nt)}}return window.addEventListener("message",G),()=>window.removeEventListener("message",G)},[se,q]),D(()=>{if(ee)return;Ky({remount:()=>{if(_.current)return!1;return nt(q,"mount-slot"),xe(!0),!0},awaitBoot:()=>new Promise((G)=>{let ne=window.setTimeout(me,Vy);function me(){window.clearTimeout(ne),G()}v.current.push(me)})})},[]),fr({enabled:N,token:se,nodeId:q,sourceSurface:"mcp-app",iframeRef:n});let zi=3,Zt=(G)=>{if(f.current>=zi)return nt(q,`remount-cap-hit (${G})`),!1;if(b.current)return!0;return f.current+=1,b.current=!0,nt(q,`remount-queued #${f.current} (${G})`),Ky({remount:()=>{if(b.current=!1,_.current||!t&&Be.value===q)return nt(q,"remount-skipped"),W(!1),!1;return z.current=typeof document<"u"&&document.visibilityState==="hidden",nt(q,`remount-run #${f.current}`),T("loading"),E((ne)=>ne+1),!0},awaitBoot:()=>new Promise((ne)=>{let me=window.setTimeout(Pe,Vy);function Pe(){window.clearTimeout(me),ne()}v.current.push(Pe)})}),!0},Sn=1500,fc=()=>new Promise((G)=>{let ne=n.current?.contentWindow;if(!ne||_.current){G("timeout");return}let me=!1,Pe=window.setTimeout(()=>{if(me)return;me=!0,G("timeout")},Sn);g.current.push((Nt)=>{if(me)return;me=!0,window.clearTimeout(Pe),y.current=Nt.detail,G(Nt.content?"content-verified":"tick-no-content")}),ne.postMessage({source:wl,token:se},"*")}),Fd=async(G)=>{let ne=Date.now()+G;while(Date.now()<ne&&!_.current){if(await fc()==="content-verified")return!0;await new Promise((me)=>window.setTimeout(me,400))}return!1},Pw=()=>new Promise((G)=>{let ne=n.current;if(!ne){G();return}let me=ne.style.width,Pe=ne.style.height;ne.style.width="140%",ne.style.height="140%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{ne.style.width=me,ne.style.height=Pe,nt(q,"soft-expand-cycle"),G()})})}),Nw=600,Pi=()=>{if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;let G=n.current;if(!G||_.current)return;if(!jT({userAgent:navigator.userAgent,visibilityState:document.visibilityState,rect:G.getBoundingClientRect(),viewport:{width:window.innerWidth,height:window.innerHeight},alreadyRearmed:F.current}))return;F.current=!0,window.setTimeout(()=>{if(_.current||document.visibilityState==="visible")return;f.current=0,U(!1),z.current=!1,nt(q,"assume-visible-rearm"),Zt("assume-visible")},Nw)},mc=(G="")=>{let ne=y.current?` [${y.current}]`:"";return typeof document<"u"&&document.visibilityState==="hidden"?`paint-ok (content-verified)${ne}${G} (host hidden)`:`paint-ok (content-verified)${ne}${G}`},Rw=async()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!wo(navigator.userAgent))return;W(!0);let G=await fc();if(G==="content-verified"){nt(q,mc()),W(!1),Pi();return}if(nt(q,G==="tick-no-content"?`paint-fail (tick without content: ${y.current||"unknown"})`:"paint-fail (no tick)"),await Pw(),G=await fc(),G==="content-verified"){nt(q,mc(" (after soft-expand)")),W(!1),Pi();return}if(_.current)return;if(G==="tick-no-content"&&await Fd(3000)){nt(q,mc(" (after content wait)")),W(!1),Pi();return}if(_.current)return;if(!Zt("paint-fail"))nt(q,"recovery-exhausted"),W(!1),U(!0),Pi()};D(()=>{if(t)return;if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;if(!wo(navigator.userAgent))return;function G(){if(document.visibilityState!=="visible")return;if(!z.current||_.current)return;z.current=!1,f.current=0,U(!1),nt(q,"visible-again-rearm"),Zt("visible-after-hidden-boot")}return document.addEventListener("visibilitychange",G),()=>document.removeEventListener("visibilitychange",G)},[t,q]);let $w=6000;D(()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!wo(navigator.userAgent))return;if(!jt.ready||!ee)return;let G=window.setTimeout(()=>{if(x.current||h.current||_.current)return;Zt("boot-watchdog")},$w);return()=>window.clearTimeout(G)},[ae,jt.ready,t,ee]),D(()=>()=>{_.current=!0;for(let G of v.current.splice(0))G();for(let G of g.current.splice(0))G({content:!1,detail:"unmounted"})},[]);let hc=(G)=>sr(G),kn=t||Be.value===q;a.current=eo,c.current=Ft;let Ni=J==="error"&&typeof Fe==="string"&&Fe.length>0,gc=J==="error"?Ni?`Live session unavailable — showing saved content. Reopen the app to restore interactivity.${Q?` (${Q})`:""}`:Q??"Saved app session is unavailable. Reopen the app to restore interactivity.":"Reconnecting saved app session...",vc=(G)=>{let ne=c.current;if(!G||!p.current||!ne)return null;if(u.current===ne)return null;if(u.current&&Uy(u.current,ne))return u.current=ne,null;if(d.current)return d.current;let me=G.sendToolResult(ne).then(()=>{u.current=ne,l.current=!0,T("done")}).catch((Pe)=>{let Nt=Pe instanceof Error?Pe.message:String(Pe);throw Z(`Tool result delivery failed: ${Nt}`),Pe}).finally(()=>{d.current=null});return d.current=me,me};if(D(()=>{if(!Fe||!jt.ready||!ee)return;let G=n.current;if(!G)return;let ne=!1,me=null,Pe=null,Nt=null,Cn=null,to=null;l.current=!1,u.current=void 0,d.current=null,p.current=!1,x.current=!1,h.current=!1;let Ri=()=>{if(!me)return;clearTimeout(me),me=null};return(async()=>{if(!Fe)return;let Tn=G.contentWindow;if(!Tn)throw Error("Ext-app iframe window is unavailable");let no=(pe=Be.value===q?"fullscreen":"inline")=>({theme:hc(Xe.value),platform:"web",containerDimensions:qu(G,{width:e.size.width,height:te}),displayMode:pe,locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,...I?{toolInfo:{id:le,tool:I}}:{}}),Mw=()=>{if(Cn!==null)return;Cn=requestAnimationFrame(()=>{if(Cn=null,ne||!p.current)return;Ne.setHostContext?.(no())})},jd=()=>{if(to!==null)return;to=requestAnimationFrame(()=>{to=requestAnimationFrame(()=>{if(to=null,ne||!p.current)return;Ne.sendHostContextChange?.(no())})})},Zd=()=>{if(!wo(navigator.userAgent))return;if(Pe)clearTimeout(Pe);Pe=setTimeout(()=>{if(Pe=null,ne)return;Rw()},ex+200)},Ne=new Hu(null,{name:"PMX Canvas",version:"1.0.0"},{openLinks:{},serverTools:{listChanged:!1},serverResources:{listChanged:!1},logging:{},updateModelContext:{text:{},structuredContent:{}}},{hostContext:no(kn?"fullscreen":"inline")});Ne.onsizechange=async({height:pe})=>{if(VT(pe,Be.value===q)){let Qe=qu(G.parentElement??G,{width:e.size.width,height:te}),Rt=GT(pe,Qe.height);G.style.height=`${Rt}px`;let oo=M.value.get(q)?.size??e.size,Bd=Math.max(oo.height,Rt+nr);if(Math.abs(Bd-oo.height)>8){if(Ko(q,{width:oo.width,height:Bd}),s.current!==null)window.clearTimeout(s.current);s.current=window.setTimeout(()=>{Ye({recordHistory:!1}),s.current=null},0)}}return{}},Ne.onopenlink=async({url:pe})=>(window.open(pe,"_blank","noopener"),{}),Ne.onsandboxready=async()=>{await Ne.sendSandboxResourceReady({html:Qy(Fe,Yy()),sandbox:_l,...Y?.csp?{csp:Y.csp}:{},...Y?.permissions?{permissions:Y.permissions}:{}})},Ne.onrequestdisplaymode=async({mode:pe})=>{let{nextMode:Qe,shouldExpand:Rt,shouldCollapse:oo}=BT(pe,kn);if(Rt)en(q);else if(oo)po();return{mode:Qe}},Ne.oncalltool=async(pe)=>{if(!Te)throw Error(gc);try{let Qe=await bo("/api/ext-app/call-tool",{sessionId:Te,nodeId:q,serverName:We,toolName:pe.name,arguments:pe.arguments??{}});return Z(null),Qe}catch(Qe){let Rt=Qe instanceof Error?Qe.message:String(Qe);throw Z(`Tool call failed: ${Rt}`),Qe}},Ne.setRequestHandler(ba,async()=>{if(!Te)return{tools:[]};return bo("/api/ext-app/list-tools",{sessionId:Te})}),Ne.onlistresources=async()=>Te?bo("/api/ext-app/list-resources",{sessionId:Te}):{resources:[]},Ne.onlistresourcetemplates=async()=>Te?bo("/api/ext-app/list-resource-templates",{sessionId:Te}):{resourceTemplates:[]},Ne.onreadresource=async(pe)=>{if(!Te)throw Error(gc);return bo("/api/ext-app/read-resource",{sessionId:Te,uri:pe.uri})},Ne.onlistprompts=async()=>Te?bo("/api/ext-app/list-prompts",{sessionId:Te}):{prompts:[]},Ne.onupdatemodelcontext=async(pe)=>{if(!Te)return{};return await bo("/api/ext-app/model-context",{nodeId:q,...Array.isArray(pe.content)?{content:pe.content}:{},...pe.structuredContent&&typeof pe.structuredContent==="object"?{structuredContent:pe.structuredContent}:{}}),{}};let yc=new Zu(Tn,Tn);if(Ne.oninitialized=()=>{if(ne)return;Ri(),p.current=!0,x.current=!0,nt(q,"initialized"),T("ready"),Z(null),Promise.resolve(Ne.sendHostContextChange(no(kn?"fullscreen":"inline"))).then(()=>Jy(Ne,a.current,void 0)).then(()=>vc(Ne)).then(()=>{let pe=()=>{for(let Qe of v.current.splice(0))Qe()};if(typeof navigator<"u"&&wo(navigator.userAgent))Fd(4000).then((Qe)=>{nt(q,Qe?"settled (content-verified)":`settled (content-timeout${y.current?`: ${y.current}`:""})`),pe()});else nt(q,"settled"),pe();jd(),Zd()}).catch((pe)=>{let Qe=pe instanceof Error?pe.message:String(pe);Z(`Bridge bootstrap failed: ${Qe}`)})},me=setTimeout(()=>{if(ne||p.current)return;let pe=c.current,Qe=no(kn?"fullscreen":"inline");p.current=!0,Ne.setHostContext?.(Qe),Promise.resolve(Ne.sendHostContextChange(Qe)).then(()=>Jy(Ne,a.current,pe)).then(()=>{if(l.current=Boolean(pe),pe)u.current=pe;if(T(pe?"done":"ready"),Z(null),jd(),Zd(),h.current){nt(q,"settled (fallback)");for(let Rt of v.current.splice(0))Rt()}}).catch((Rt)=>{let oo=Rt instanceof Error?Rt.message:String(Rt);Z(`Bridge bootstrap fallback failed: ${oo}`)})},1200),await Ne.connect(yc),ne){Ri(),await yc.close();return}if(o.current=Ne,r.current=yc,Nt=new ResizeObserver(Mw),Nt.observe(G),G.parentElement)Nt.observe(G.parentElement);let Hd=!0;m.current=Xe.subscribe((pe)=>{if(Hd){Hd=!1;return}if(ne)return;Ne.setHostContext?.({...no(),theme:hc(pe)}),Ne.sendHostContextChange?.(no())}),vc(Ne)})().catch((Tn)=>{Ri(),console.error("[ext-app] Bridge init failed:",Tn),Z(Tn?.message??"Bridge initialization failed")}),()=>{if(ne=!0,Ri(),Pe)clearTimeout(Pe),Pe=null;if(Nt?.disconnect(),Nt=null,Cn!==null)cancelAnimationFrame(Cn),Cn=null;if(to!==null)cancelAnimationFrame(to),to=null;if(p.current=!1,d.current=null,m.current?.(),m.current=null,s.current!==null)window.clearTimeout(s.current),s.current=null;if(o.current=null,r.current)r.current.close().catch((Tn)=>{console.error("[ext-app] transport close failed:",Tn)}),r.current=null}},[ae,jt.key,ee]),D(()=>{if(Ft&&o.current&&(k==="ready"||k==="done"))vc(o.current)},[Ft,k]),D(()=>{let G=o.current;if(n.current)n.current.style.height="100%";if(!G||!p.current)return;let ne=null,me=null;return ne=requestAnimationFrame(()=>{ne=null,me=requestAnimationFrame(()=>{if(me=null,!p.current)return;let Pe={theme:hc(Xe.value),platform:"web",containerDimensions:qu(n.current,{width:e.size.width,height:te}),displayMode:kn?"fullscreen":"inline",locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone};G.setHostContext?.(Pe),G.sendHostContextChange?.(Pe)})}),()=>{if(ne!==null)cancelAnimationFrame(ne);if(me!==null)cancelAnimationFrame(me)}},[kn,te]),!Fe)return i("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--c-muted)",fontSize:"13px",flexDirection:"column",gap:"8px"},children:[i("div",{style:{opacity:0.6},children:["Loading ",Xt," viewer..."]},void 0,!0,void 0,this),i("div",{style:{width:"24px",height:"24px",border:"2px solid var(--c-line)",borderTopColor:"var(--c-muted)",borderRadius:"50%",animation:"spin 1s linear infinite"}},void 0,!1,void 0,this),i("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{style:{flex:1,width:"100%",height:"100%",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[J&&J!=="ready"&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:J==="error"&&!Ni?"var(--c-danger-12)":"var(--c-warn-10)",color:J==="error"&&!Ni?"var(--c-danger)":"var(--c-warn)",borderBottom:`1px solid ${J==="error"&&!Ni?"var(--c-danger-12)":"var(--c-warn-15)"}`},children:gc},void 0,!1,void 0,this),P&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:"var(--c-danger-12)",color:"var(--c-danger)",borderBottom:"1px solid var(--c-danger-12)",display:"flex",alignItems:"center",gap:"6px"},children:[i("span",{children:"⚠"},void 0,!1,void 0,this),i("span",{style:{flex:1},children:P},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>{Z(null),T("loading"),E((G)=>G+1)},style:{background:"var(--c-surface-hover)",border:"1px solid var(--c-danger-12)",borderRadius:"3px",color:"var(--c-danger)",cursor:"pointer",fontSize:"10px",padding:"1px 6px"},children:"Retry"},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>Z(null),style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{flex:1,position:"relative",display:"flex",minHeight:0,height:"100%"},children:[ee&&i("iframe",{ref:n,...jt.attributes,sandbox:mt,allow:By(Y?.permissions),style:{flex:1,width:"100%",height:"100%",minHeight:0,border:"none",background:"var(--c-panel)",pointerEvents:kn?"auto":"none"},title:`Ext App: ${Xt}`},ae,!1,void 0,this),H&&!P&&i("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"10px",background:"var(--c-panel)",color:"var(--c-warn)",fontSize:"12px"},children:[i("div",{children:"App surface failed to paint."},void 0,!1,void 0,this),i("button",{type:"button",onClick:(G)=>{G.stopPropagation(),nt(q,"manual-retry"),f.current=0,U(!1),T("loading"),E((ne)=>ne+1)},style:{background:"var(--c-surface-hover)",border:"1px solid var(--c-warn-15)",borderRadius:"4px",color:"var(--c-warn)",cursor:"pointer",fontSize:"11px",padding:"3px 10px"},children:"Retry"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(k==="loading"||B)&&!P&&!H&&i("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"10px",background:"var(--c-panel)",color:"var(--c-muted)",fontSize:"12px",pointerEvents:"none"},children:[i("div",{style:{width:"22px",height:"22px",border:"2px solid var(--c-line)",borderTopColor:"var(--c-muted)",borderRadius:"50%",animation:"spin 1s linear infinite"}},void 0,!1,void 0,this),i("div",{children:k==="loading"?`Connecting to ${Xt}...`:"Finishing paint..."},void 0,!1,void 0,this),i("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!kn&&!(H&&!P)&&i("button",{type:"button",onClick:(G)=>{G.stopPropagation(),en(q)},class:"ext-app-preview-catcher",title:"Click to open",style:{position:"absolute",top:0,right:"56px",bottom:"56px",left:0,background:"transparent",border:"none",padding:0,margin:0,cursor:"zoom-in"},"aria-label":"Open full view to edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function XT(e,t,n,o,r,s,a){if(!e)return e;try{let c=new URL(e,window.location.origin);if(c.searchParams.set("theme",sr(Xe.value)),t)c.searchParams.set("display","expanded");if(typeof n==="number")c.searchParams.set("v",String(n));if(o)c.searchParams.set("axToken",o);if(r)c.searchParams.set("axNodeId",r);if(s)c.searchParams.set("frameToken",s);if(a)c.searchParams.set("fit","content");return c.toString()}catch{return e}}function KT(e,t=window.location.origin){if(!e)return!1;try{let n=new URL(t).origin,o=new URL(e,n);return o.origin===n&&o.pathname.startsWith("/api/canvas/frame-documents/")}catch{return!1}}function Hn({node:e,expanded:t=!1}){if(e.data.mode==="ext-app")return i(tx,{node:e,expanded:t},void 0,!1,void 0,this);return i(JT,{node:e,expanded:t},void 0,!1,void 0,this)}function JT({node:e,expanded:t}){let n=R(null),o=e.type==="mcp-app"&&e.data.viewerType==="web-artifact",r=e.type==="json-render"||e.type==="graph",s=e.data.axCapabilities?.enabled,c=(r||o)&&(o?s===!0:s!==!1),l=o?"mcp-app":"json-render",u=Ae(()=>c?`ax-${crypto.randomUUID()}`:"",[c]),d=kl(e)&&!t,p=Ae(()=>d?`frame-${crypto.randomUUID()}`:"",[d]);or(e,n,p),fr({enabled:c&&Boolean(u),token:u,nodeId:e.id,sourceSurface:l,iframeRef:n});let m=Gt.value,f=()=>{if(!c||!u||m==null)return;n.current?.contentWindow?.postMessage({source:Mt,type:"ax-update",token:u,state:m},"*")};D(f,[c,u,m]);let g=typeof e.data.specVersion==="number"?e.data.specVersion:void 0,y=XT(e.data.url||"",t,g,u||void 0,c?e.id:void 0,p||void 0,d),x=rr(y),h=e.data.sourceServer||"",v=e.data.hostMode||"hosted",b=e.data.fallbackReason,z=e.data.trustedDomain===!0||KT(y);if(v==="fallback")return i("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[i("div",{style:{color:"var(--c-warn)",display:"flex",alignItems:"center",gap:"6px"},children:[i("span",{children:"⚠"},void 0,!1,void 0,this),i("span",{children:"Cannot embed — opened externally"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b&&i("div",{style:{color:"var(--c-muted)",fontSize:"11px"},children:["Reason: ",b]},void 0,!0,void 0,this),i("a",{href:y,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all"},children:y},void 0,!1,void 0,this),h&&i("div",{style:{color:"var(--c-dim)",fontSize:"10px"},children:["Source: ",h]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return i("div",{style:{height:"100%",display:"flex",flexDirection:"column",...t?{flex:1,minHeight:0,width:"100%"}:{}},children:[!z&&i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-warn-10)",color:"var(--c-warn)",borderBottom:"1px solid var(--c-warn-15)"},children:"Unverified domain"},void 0,!1,void 0,this),i("iframe",{ref:n,...x,class:"mcp-app-frame",sandbox:"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",allow:"clipboard-read; clipboard-write",loading:gt.value==="srcdoc"?void 0:"lazy",onLoad:f,style:{flex:1,minHeight:0,width:"100%"},title:`MCP App: ${h}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var YT=null;function hr(){YT=null}var nx={idle:"var(--c-muted)",running:"var(--c-accent)",planning:"var(--c-thinking)",thinking:"var(--c-thinking)",drafting:"var(--c-accent)",tooling:"var(--c-accent)",review:"var(--c-ok)","waiting-approval":"var(--c-warn)",waiting:"var(--c-warn-alt)"};function QT(e){let t=typeof e.data.phase==="string"&&e.data.phase.trim().length>0?e.data.phase.trim():"";if(t)return t;let n=typeof e.data.content==="string"&&e.data.content.trim().length>0?e.data.content.trim():"";if(n)return n;return(typeof e.data.status==="string"&&e.data.status.trim().length>0?e.data.status.trim():"")||"idle"}function Ca({node:e}){let t=QT(e),n=e.data.detail||"",o=e.data.message||"",r=e.data.level||"ok",s=e.data.activeTool,a=e.data.subagent,c=nx[t]??"var(--c-muted)",l=t!=="idle";return i("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[i("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:c,boxShadow:l?`0 0 8px ${c}`:"none",animation:l?"pulse 1.5s infinite":"none",flexShrink:0}},void 0,!1,void 0,this),i("span",{style:{fontWeight:600,color:c,textTransform:"uppercase",letterSpacing:"0.05em"},children:t},void 0,!1,void 0,this),n&&i("span",{style:{color:"var(--c-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s&&i("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-warn)"},children:[i("span",{style:{fontSize:"10px"},children:"⚙"},void 0,!1,void 0,this),i("span",{style:{fontFamily:"var(--mono)",fontSize:"11px"},children:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a&&a.state!=="completed"&&i("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-subagent)"},children:[i("span",{style:{fontSize:"10px"},children:"⠉"},void 0,!1,void 0,this),i("span",{children:a.name},void 0,!1,void 0,this),i("span",{style:{color:"var(--c-muted)",fontSize:"10px"},children:["(",a.state,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o&&i("div",{style:{color:r==="warn"?"var(--c-warn)":r==="error"?"var(--c-danger)":"var(--c-muted)",lineHeight:1.4},children:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function gr(e){return typeof e==="string"&&e.trim().length>0?e.trim():null}function ox(e){if(typeof e==="string"){let r=gr(e);return r?{title:"Evidence warning",detail:r}:null}if(!e||typeof e!=="object")return null;let t=e,n=gr(t.title)??"Evidence warning",o=gr(t.detail);return o?{title:n,detail:o}:null}function eE(e){let t=[],n=ox(e.data.warning);if(n)t.push(n);let o=e.data.warnings;if(Array.isArray(o))for(let s of o){let a=ox(s);if(a)t.push(a)}let r=gr(e.data.validationStatus)?.toLowerCase();if(r==="failed"||r==="invalid")t.push({title:"Image failed validation",detail:gr(e.data.validationMessage)??"Review this image before using it as evidence."});return t}function tE(e){let t=[e.data.title,e.data.caption,e.data.alt,e.data.src,e.data.path].map((n)=>gr(n)?.toLowerCase()??"").join(" ");if(t.length===0)return!1;return["login","log in","sign in","signin","password","2fa","mfa","authenticate","authentication","sso"].some((n)=>t.includes(n))}function rx(e){let t=eE(e);if(t.length>0)return t;if(tE(e))return[{title:"Captured login page",detail:"This image looks like an auth screen. Treat it as environment context, not product evidence."}];return[]}function Ta({node:e,expanded:t=!1}){let n=e.data.src||"",o=e.data.alt||e.data.title||"Image",r=e.data.caption||"",s=rx(e),a=n.startsWith("data:")||n.startsWith("http://")||n.startsWith("https://")?n:`/api/canvas/image/${e.id}`,[c,l]=L(!1),[u,d]=L(!1),[p,m]=L(1),[f,g]=L({x:0,y:0}),[y,x]=L({w:0,h:0}),h=R(null),v=R(!1),b=R({x:0,y:0}),z=O((B)=>{let W=B.target;x({w:W.naturalWidth,h:W.naturalHeight}),l(!0),d(!1)},[]),F=O(()=>{d(!0),l(!1)},[]);D(()=>{m(1),g({x:0,y:0})},[n]);let _=O((B)=>{B.preventDefault(),B.stopPropagation();let W=B.deltaY>0?0.9:1.1;m((H)=>Math.max(0.25,Math.min(10,H*W)))},[]),k=O((B)=>{if(p<=1)return;B.stopPropagation(),v.current=!0,b.current={x:B.clientX,y:B.clientY},B.target.setPointerCapture(B.pointerId)},[p]),T=O((B)=>{if(!v.current)return;let W=B.clientX-b.current.x,H=B.clientY-b.current.y;b.current={x:B.clientX,y:B.clientY},g((U)=>({x:U.x+W,y:U.y+H}))},[]),P=O(()=>{v.current=!1},[]),Z=O(()=>{m(1),g({x:0,y:0})},[]);if(!n)return i("div",{class:"image-node-empty",children:[i("div",{class:"image-node-empty-icon",children:"\uD83D\uDDBC"},void 0,!1,void 0,this),i("div",{class:"image-node-empty-text",children:"No image source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let j=y.w>0?`${y.w}×${y.h}`:"",E=Math.round(p*100);return i("div",{class:`image-node ${t?"image-node-expanded":""}`,ref:h,children:[s.length>0&&i("div",{class:"image-node-warning-stack",children:s.map((B)=>i("div",{class:"image-node-warning",children:[i("span",{class:"image-node-warning-title",children:B.title},void 0,!1,void 0,this),i("span",{class:"image-node-warning-detail",children:B.detail},void 0,!1,void 0,this)]},`${B.title}-${B.detail}`,!0,void 0,this))},void 0,!1,void 0,this),i("div",{class:"image-node-viewport",onWheel:_,onPointerDown:k,onPointerMove:T,onPointerUp:P,style:{cursor:p>1?"grab":"default"},children:[!c&&!u&&i("div",{class:"image-node-loading",children:"Loading…"},void 0,!1,void 0,this),u&&i("div",{class:"image-node-error",children:[i("div",{class:"image-node-error-icon",children:"⚠"},void 0,!1,void 0,this),i("div",{children:"Failed to load image"},void 0,!1,void 0,this),i("div",{class:"image-node-error-path",children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("img",{src:a,alt:o,onLoad:z,onError:F,draggable:!1,style:{transform:`translate(${f.x}px, ${f.y}px) scale(${p})`,opacity:c?1:0,display:u?"none":"block"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(r||j||p!==1)&&i("div",{class:"image-node-footer",children:[r&&i("span",{class:"image-node-caption",children:r},void 0,!1,void 0,this),i("span",{class:"image-node-meta",children:[j&&i("span",{children:j},void 0,!1,void 0,this),p!==1&&i("button",{type:"button",class:"image-node-zoom-reset",onClick:Z,title:"Reset zoom",children:[E,"% ↺"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ix({node:e}){if((e.data.children??[]).filter((o)=>M.value.has(o)).length>0)return null;return i("div",{class:"group-empty-hint",children:"Drop nodes here — release while the frame lights up to add them"},void 0,!1,void 0,this)}function nE(e){try{return new URL(e).host}catch{return e}}function oE(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ea({node:e,expanded:t=!1}){let n=typeof e.data.url==="string"?e.data.url:"",o=typeof e.data.pageTitle==="string"?e.data.pageTitle:"",r=typeof e.data.description==="string"?e.data.description:"",s=typeof e.data.excerpt==="string"?e.data.excerpt:typeof e.data.content==="string"?e.data.content:"",a=typeof e.data.status==="string"?e.data.status:"idle",c=typeof e.data.error==="string"?e.data.error:"",l=oE(typeof e.data.fetchedAt==="string"?e.data.fetchedAt:void 0),u=typeof e.data.statusCode==="number"?e.data.statusCode:null,d=typeof e.data.imageUrl==="string"?e.data.imageUrl:"",p=e.data.frameBlocked===!0,m=typeof e.data.frameBlockedReason==="string"?e.data.frameBlockedReason:"",[f,g]=L(!1),[y,x]=L(t);D(()=>{if(t)x(!0)},[t]);let h=O(async()=>{if(!n||f)return;g(!0);try{await is(e.id)}finally{g(!1)}},[e.id,f,n]);if(!n)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No webpage URL set"},void 0,!1,void 0,this);let v=a==="ready"?"var(--c-ok)":a==="error"?"var(--c-danger)":"var(--c-warn)";return i("div",{style:{display:"flex",flexDirection:"column",gap:"12px",height:"100%"},children:[i("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[i("div",{style:{minWidth:0,flex:1},children:[i("div",{style:{fontSize:"12px",color:"var(--c-muted)"},children:nE(n)},void 0,!1,void 0,this),i("div",{style:{fontSize:t?"18px":"15px",fontWeight:700,color:"var(--c-text)"},children:o||e.data.title||n},void 0,!1,void 0,this),i("a",{href:n,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all",textDecoration:"none"},children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 8px",borderRadius:"999px",background:"rgba(255,255,255,0.04)",color:v,fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.04em",flexShrink:0},children:[i("span",{style:{width:"7px",height:"7px",borderRadius:"999px",background:v}},void 0,!1,void 0,this),a]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(r||d)&&i("div",{style:{display:"grid",gridTemplateColumns:d&&t?"160px 1fr":"1fr",gap:"12px",alignItems:"start"},children:[d&&t&&i("img",{src:d,alt:o||"Webpage preview image",style:{width:"160px",height:"96px",objectFit:"cover",borderRadius:"10px",border:"1px solid var(--c-line)",background:"var(--c-panel-soft)"}},void 0,!1,void 0,this),r&&i("p",{style:{margin:0,color:"var(--c-text-soft)",lineHeight:1.5,fontSize:t?"14px":"12px"},children:r},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:[i("button",{type:"button",onClick:h,disabled:f,style:{border:"1px solid var(--c-line)",background:"var(--c-panel-soft)",color:"var(--c-text)",borderRadius:"8px",padding:"6px 10px",cursor:f?"progress":"pointer",fontSize:"12px"},children:f||a==="fetching"?"Refreshing…":"Refresh"},void 0,!1,void 0,this),t&&!p&&i("button",{type:"button",onClick:()=>x((b)=>!b),style:{border:"1px solid var(--c-line)",background:"var(--c-panel-soft)",color:"var(--c-text)",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px"},children:y?"Hide live preview":"Show live preview"},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>window.open(n,"_blank","noopener"),style:{border:"1px solid var(--c-line)",background:"transparent",color:"var(--c-accent)",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px"},children:"Open in browser"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&p&&i("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[i("div",{style:{padding:"8px 12px",fontSize:"11px",color:"var(--c-muted)",borderBottom:"1px solid var(--c-line)",background:"rgba(255,255,255,0.03)"},children:"Live preview unavailable. This site refuses embedding, so PMX Canvas cannot show it inline."},void 0,!1,void 0,this),i("div",{style:{padding:"20px",color:"var(--c-text-soft)",lineHeight:1.6,fontSize:"13px"},children:m||"The remote site blocks iframe embedding."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&y&&!p&&i("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[i("div",{style:{padding:"8px 12px",fontSize:"11px",color:"var(--c-muted)",borderBottom:"1px solid var(--c-line)",background:"rgba(255,255,255,0.03)"},children:"Live preview (best effort). If this stays blank, the site likely blocks framing. The cached text snapshot below still works."},void 0,!1,void 0,this),i("iframe",{class:"webpage-node-iframe",title:o||e.data.title||n,src:n,loading:"lazy",referrerPolicy:"no-referrer",sandbox:"allow-downloads allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-presentation allow-scripts",style:{display:"block",width:"100%",height:t?"320px":"180px",border:"none",background:"#fff"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(l||u!==null)&&i("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",color:"var(--c-muted)",fontSize:"11px"},children:[l&&i("span",{children:["Fetched ",l]},void 0,!0,void 0,this),u!==null&&i("span",{children:["HTTP ",u]},void 0,!0,void 0,this),p&&i("span",{children:"Preview blocked by site"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c&&i("div",{style:{color:"var(--c-danger)",fontSize:"12px",lineHeight:1.5},children:c},void 0,!1,void 0,this),i("div",{style:{flex:1,minHeight:0,overflow:"auto",border:"1px solid var(--c-line)",borderRadius:"10px",background:"var(--c-panel-soft)",padding:t?"14px":"10px"},children:s?i("div",{style:{whiteSpace:"pre-wrap",lineHeight:1.55,color:"var(--c-text)",fontSize:t?"14px":"12px"},children:s},void 0,!1,void 0,this):i("div",{style:{color:"var(--c-dim)",fontStyle:"italic"},children:a==="error"?"No cached page text available.":"Waiting for page text..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sx(e){return e.type==="html"&&e.data.presentation===!0}function vi({node:e,expanded:t=!1,presentation:n=!1,presentationExitToken:o,autoFocus:r=!1}){let s=R(null),a=Xe.value,c=Ae(()=>`theme-${crypto.randomUUID()}`,[]),l=Ae(()=>`ax-${crypto.randomUUID()}`,[]),u=Ae(()=>`frame-${crypto.randomUUID()}`,[]),d=typeof e.data.html==="string"?e.data.html:typeof e.data.content==="string"?e.data.content:"",p=Ae(()=>tr(d),[d]),m=Ae(()=>d?Vr(e.id,{theme:a,themeToken:c,present:n,presentToken:o,v:p,axToken:l,frameToken:u}):"",[d,n,o,c,p,e.id,l,u]),f=rr(m);or(e,s,t?"":u),fr({enabled:!0,token:l,nodeId:e.id,sourceSurface:"html-node",iframeRef:s}),D(()=>{if(s.current?.contentWindow?.postMessage({source:Mt,type:"theme-update",token:c,theme:a},"*"),r)s.current?.focus()},[a,c]);let g=e.data.axCapabilities,y=g?.enabled===!0&&(!Array.isArray(g.allowed)||g.allowed.length>0),x=Gt.value;D(()=>{if(!y||x==null)return;s.current?.contentWindow?.postMessage({source:Mt,type:"ax-update",token:l,state:x},"*")},[y,x,l]),D(()=>{if(!r)return;let v=window.setTimeout(()=>s.current?.focus(),0);return()=>window.clearTimeout(v)},[r,m]);let h=()=>{if(s.current?.contentWindow?.postMessage({source:Mt,type:"theme-update",token:c,theme:a},"*"),y&&Gt.value!=null)s.current?.contentWindow?.postMessage({source:Mt,type:"ax-update",token:l,state:Gt.value},"*");if(r)s.current?.focus()};if(!d)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No HTML content set"},void 0,!1,void 0,this);return i("iframe",{ref:s,class:n?"html-node-frame html-node-frame-presentation":"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"HTML node",sandbox:"allow-scripts",...f,tabIndex:r?0:void 0,onLoad:h,style:{width:"100%",height:"100%",minHeight:n?0:t?"70vh":"300px",border:"none",background:"var(--c-bg)",borderRadius:n?0:"6px",display:"block"}},void 0,!1,void 0,this)}var Vu=null;async function ax(){if(!Vu)Vu=await Dp();return Vu}function cx(e,t){if(!e)return null;let n=e.toLowerCase(),o=t.find((s)=>s.name.toLowerCase()===n);if(o)return o.name;let r=t.filter((s)=>s.name.toLowerCase().startsWith(n));return r.length===1?r[0].name:null}function rE(e){return e.replace(/<script[\s>][\s\S]*?<\/script>/gi,"").replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi,"").replace(/<object[\s>][\s\S]*?<\/object>/gi,"").replace(/<embed[\s>][\s\S]*?(?:\/>|<\/embed>)/gi,"").replace(/<link[\s>][\s\S]*?(?:\/>|<\/link>)/gi,"").replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/href\s*=\s*"javascript:[^"]*"/gi,'href="#"').replace(/href\s*=\s*'javascript:[^']*'/gi,"href='#'")}function iE({html:e}){let t=R(null);return D(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=e,n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function sE(e,t){return`${e.role}:${e.status??"none"}:${t}:${e.text}`}function lx({count:e}){if(e===0)return null;return i("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--c-accent)",background:"rgba(70,182,255,0.08)",borderRadius:"var(--radius-sm)",flexShrink:0},children:["✦"," ",e," context node",e!==1?"s":""," attached"]},void 0,!0,void 0,this)}function ux({message:e,onDismiss:t}){if(!e)return null;return i("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--c-danger)",background:"rgba(255,80,80,0.08)",borderRadius:"var(--radius-sm)",display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[i("span",{style:{flex:1},children:e},void 0,!1,void 0,this),i("button",{type:"button",onClick:t,style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ia({node:e,expanded:t=!1}){let n=Array.isArray(e.data.turns)?e.data.turns:[],o=n.length===0,r=e.data.text||"",s=e.data.status||"draft",a=o?s:e.data.threadStatus||"draft",c=a==="draft",l=a==="pending"||a==="sending",u=a==="streaming",d=a==="answered",[p,m]=L(""),[f,g]=L(""),[y,x]=L(null),[h,v]=L(new Map),b=R(null),z=R(null),F=n[n.length-1],_=`${n.length}:${F?.role??""}:${F?.status??""}:${Math.floor((F?.text?.length??0)/200)}`;D(()=>{if(t&&c&&b.current)b.current.focus()},[t,c]),D(()=>{if(!_)return;if(z.current)z.current.scrollTo({top:z.current.scrollHeight,behavior:"smooth"})},[_]);let k=R(null),T=R(n);T.current=n,D(()=>{let W=n.some((U)=>U.role==="assistant"&&U.status==="streaming"),H=()=>{let U=!1,xe=T.current.map((Fe,We)=>({turn:Fe,index:We})).filter(({turn:Fe})=>Fe.role==="assistant"&&Fe.text);if(xe.length===0)return;return Promise.all(xe.map(async({turn:Fe,index:We})=>{let Te=await an(Fe.text);return{index:We,html:rE(Te)}})).then((Fe)=>{if(U)return;let We=new Map;for(let Te of Fe)We.set(Te.index,Te.html);v(We)}),()=>{U=!0}};if(!W){if(k.current)clearTimeout(k.current),k.current=null;return H()}if(k.current)clearTimeout(k.current);return k.current=setTimeout(()=>{k.current=null,H()},400),()=>{if(k.current)clearTimeout(k.current),k.current=null}},[n]);let P=O(async()=>{let W=p.trim();if(!W)return;let H=p;x(null),oe(e.id,{turns:[{role:"user",text:W,status:"pending"}],threadStatus:"pending",text:W}),m("");let U=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds:void 0;if(!(await Lr(W,e.position,e.id,U,e.id)).ok)oe(e.id,{turns:[],threadStatus:"draft",text:"",status:"draft"}),m(H),x("Failed to send prompt. Your draft has been restored.")},[p,e.id,e.position,e.data.contextNodeIds]),Z=O(async()=>{let W=f.trim();if(!W)return;let H=f;x(null);let U=Array.isArray(e.data.turns)?[...e.data.turns]:[];if(U.push({role:"user",text:W,status:"pending"}),oe(e.id,{turns:U,threadStatus:"pending"}),g(""),!(await Fp(e.id,W)).ok)U.pop(),oe(e.id,{turns:U,threadStatus:"answered"}),g(H),x("Failed to send reply. Your draft has been restored.")},[f,e.id,e.data.turns]),j=O((W)=>{if(W.key==="Enter"&&(W.metaKey||W.ctrlKey)){W.preventDefault(),P();return}if(W.key==="Tab"&&p.startsWith("/")){W.preventDefault();let H=p.slice(1).split(/\s/)[0];if(H)ax().then((U)=>{let ee=cx(H,U);if(ee)m(`/${ee}`)})}},[P,p]),E=O((W)=>{if(W.key==="Enter"&&(W.metaKey||W.ctrlKey)){W.preventDefault(),Z();return}if(W.key==="Tab"&&f.startsWith("/")){W.preventDefault();let H=f.slice(1).split(/\s/)[0];if(H)ax().then((U)=>{let ee=cx(H,U);if(ee)g(`/${ee}`)})}},[Z,f]),B=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds.length:0;if(c&&n.length===0)return i("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%",gap:"8px"},children:[i(lx,{count:B},void 0,!1,void 0,this),i(ux,{message:y,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("textarea",{ref:b,value:p,onInput:(W)=>m(W.target.value),onKeyDown:j,placeholder:"Ask the agent something…",spellcheck:!1,style:{flex:1,resize:"none",background:"rgba(10,14,30,0.4)",border:"1px solid var(--c-line)",borderRadius:"var(--radius-sm)",color:"var(--c-text)",fontFamily:"var(--font)",fontSize:"13px",lineHeight:"1.5",padding:"8px 10px",outline:"none"}},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter to send"]},void 0,!0,void 0,this),i("button",{type:"button",onClick:P,disabled:!p.trim(),style:{padding:"5px 14px",fontSize:"12px",fontWeight:600,background:p.trim()?"var(--c-accent)":"var(--c-line)",color:p.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:p.trim()?"pointer":"default"},children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(o)return i("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[i("div",{style:{flex:1,padding:"2px 0",fontSize:"13px",lineHeight:"1.55",color:"var(--c-text)",whiteSpace:"pre-wrap",wordBreak:"break-word",overflow:"auto"},children:r},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px"},children:i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:l?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:l?"Sending…":d?"Answered":s},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[i(lx,{count:B},void 0,!1,void 0,this),i(ux,{message:y,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("div",{ref:z,style:{flex:1,overflow:"auto",minHeight:0},children:n.map((W,H)=>i("div",{children:[H>0&&i("div",{class:"thread-turn-divider"},void 0,!1,void 0,this),W.role==="user"?i("div",{class:"thread-turn-user",children:[i("div",{class:"thread-turn-role",children:[i("span",{class:"status-dot"},void 0,!1,void 0,this),"You"]},void 0,!0,void 0,this),i("div",{style:{fontSize:t?"15px":"13px",lineHeight:t?"1.7":"1.55",color:"var(--c-text)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:W.text},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i("div",{class:"thread-turn-assistant",children:[i("div",{class:"thread-turn-role",children:[i("span",{class:`status-dot${W.status==="streaming"?" pulsing":""}`},void 0,!1,void 0,this),"PMX"]},void 0,!0,void 0,this),W.status==="streaming"&&!W.text&&i("div",{style:{height:"2px",background:"linear-gradient(90deg, transparent, var(--c-ok), transparent)",animation:"response-stream-pulse 1.5s ease-in-out infinite",borderRadius:"1px",marginBottom:"4px"}},void 0,!1,void 0,this),i("div",{class:t?"md-reader-content":void 0,style:{fontSize:t?void 0:"13px",lineHeight:t?void 0:"1.55",opacity:W.text?1:0.4},children:h.get(H)?i(ve,{children:[i(iE,{html:h.get(H)??""},void 0,!1,void 0,this),W.status==="streaming"&&i("span",{class:"streaming-cursor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i("div",{style:{color:"var(--c-muted)",fontStyle:"italic"},children:W.status==="streaming"?"Waiting for response…":W.text||"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},sE(W,H),!0,void 0,this))},void 0,!1,void 0,this),i("div",{style:{flexShrink:0,borderTop:"1px solid var(--c-line)",marginTop:"4px",paddingTop:"6px"},children:[i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:d?"6px":0},children:[i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:u?"var(--c-accent)":l?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:u?"Streaming…":l?"Sending…":d?"Answered":a},void 0,!1,void 0,this),i("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:[n.length," turn",n.length!==1?"s":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d&&i("div",{class:"thread-reply-area",children:[i("textarea",{value:f,onInput:(W)=>g(W.target.value),onKeyDown:E,placeholder:"Reply…",spellcheck:!1,rows:2,style:{width:"100%",resize:"none",background:"rgba(10,14,30,0.4)",border:"1px solid var(--c-line)",borderRadius:"var(--radius-sm)",color:"var(--c-text)",fontFamily:"var(--font)",fontSize:"12px",lineHeight:"1.5",padding:"6px 8px",outline:"none"}},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"4px"},children:[i("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter"]},void 0,!0,void 0,this),i("button",{type:"button",onClick:Z,disabled:!f.trim(),style:{padding:"3px 10px",fontSize:"11px",fontWeight:600,background:f.trim()?"var(--c-accent)":"var(--c-line)",color:f.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:f.trim()?"pointer":"default"},children:"Reply"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function aE(e){return e.replace(/<script[\s>][\s\S]*?<\/script>/gi,"").replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi,"").replace(/<object[\s>][\s\S]*?<\/object>/gi,"").replace(/<embed[\s>][\s\S]*?(?:\/>|<\/embed>)/gi,"").replace(/<link[\s>][\s\S]*?(?:\/>|<\/link>)/gi,"").replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/href\s*=\s*"javascript:[^"]*"/gi,'href="#"').replace(/href\s*=\s*'javascript:[^']*'/gi,"href='#'")}function cE({html:e}){let t=R(null);return D(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=e,n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function Aa({node:e,expanded:t=!1}){let n=e.data.content||"",o=e.data.status||"streaming",[r,s]=L(""),a=o==="streaming",c=o==="complete";D(()=>{if(!n){s("");return}let u=!1;return an(n).then((d)=>{if(!u)s(aE(d))}),()=>{u=!0}},[n]);let l=O(()=>{Lr("",{x:e.position.x,y:e.position.y+e.size.height+24},e.id)},[e]);return i("div",{class:"response-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[a&&i("div",{class:"response-streaming-bar",style:{height:"2px",background:"linear-gradient(90deg, transparent, var(--c-accent), transparent)",animation:"response-stream-pulse 1.5s ease-in-out infinite",borderRadius:"1px",marginBottom:"4px",flexShrink:0}},void 0,!1,void 0,this),i("div",{class:t?"md-reader":void 0,style:{flex:1,overflow:"auto",minHeight:0,opacity:n?1:0.4,transition:"opacity 0.2s ease"},children:r?i("div",{class:t?"md-reader-content":void 0,children:i(cE,{html:r},void 0,!1,void 0,this)},void 0,!1,void 0,this):i("div",{style:{color:"var(--c-muted)",fontStyle:"italic",fontSize:"13px"},children:a?"Waiting for response…":"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px",flexShrink:0},children:[i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:a?"var(--c-accent)":c?"var(--c-ok)":"var(--c-muted)"},children:a?"Streaming…":c?"Complete":o},void 0,!1,void 0,this),c&&i("button",{type:"button",onClick:l,style:{padding:"3px 10px",fontSize:"11px",background:"rgba(70,182,255,0.1)",border:"1px solid rgba(70,182,255,0.3)",borderRadius:"var(--radius-sm)",color:"var(--c-accent)",cursor:"pointer"},children:"Reply"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function dx(e){return{toolName:e.toolName||e.title||"unknown",category:e.category||"other",status:e.status||"running",duration:e.duration||"",resultSummary:e.resultSummary||e.content||"",error:e.error||""}}var px={mcp:"var(--c-accent)",file:"var(--c-warn)",subagent:"var(--c-purple)",other:"var(--c-muted)"},lE={running:"⠋",success:"✓",failed:"✕"},uE={running:"var(--c-accent)",success:"var(--c-ok)",failed:"var(--c-danger)"};function za({node:e}){let{toolName:t,category:n,status:o,duration:r,resultSummary:s,error:a}=dx(e.data),c=px[n]??px.other,l=lE[o]??"◌",u=uE[o]??"var(--c-muted)",d=o==="running",p=a?a.slice(0,30):s.length>30?`${s.slice(0,28)}…`:s;return i("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"0 12px",height:"100%",overflow:"hidden"},children:[i("span",{style:{fontSize:"14px",color:u,flexShrink:0,animation:d?"pulse 1.5s infinite":"none"},children:l},void 0,!1,void 0,this),i("div",{style:{flex:1,minWidth:0,overflow:"hidden"},children:[i("div",{style:{fontFamily:"var(--mono)",fontSize:"11px",fontWeight:600,color:c,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t},void 0,!1,void 0,this),p&&i("div",{style:{fontSize:"10px",color:a?"var(--c-danger)":"var(--c-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1.3},children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r&&i("span",{style:{fontSize:"9px",padding:"1px 5px",borderRadius:"3px",background:"rgba(255,255,255,0.06)",color:"var(--c-muted)",flexShrink:0,whiteSpace:"nowrap"},children:r},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Xu(e){let t=M.value.get(e);if(!t)return null;return{left:t.position.x,top:t.position.y,width:t.size.width,height:t.size.height}}function dE(e){let t=e.map((l)=>Xu(l)).filter((l)=>l!==null);if(t.length===0)return null;let n=Math.min(...t.map((l)=>l.left)),o=Math.min(...t.map((l)=>l.top)),r=Math.max(...t.map((l)=>l.left+l.width)),s=Math.max(...t.map((l)=>l.top+l.height)),a=54,c=46;return{left:n-a,top:o-c,width:r-n+a*2,height:s-o+c*2}}function Gu(e,t){return{left:`${e.left}px`,top:`${e.top}px`,width:`${e.width}px`,height:`${e.height}px`,borderRadius:`${t}px`}}function fx(){let e=Array.from(Lo.value),t=Array.from(Do.value),n=Ji.value;if(e.length===0&&t.length===0)return null;let o=[...M.value.values()],r=o.length>0?(Math.max(...o.map((s)=>s.position.x+s.size.width))-Math.min(...o.map((s)=>s.position.x)))*(Math.max(...o.map((s)=>s.position.y+s.size.height))-Math.min(...o.map((s)=>s.position.y))):0;return i("div",{class:"attention-field-layer","aria-hidden":"true",children:[n.map((s)=>{let a=dE(s.nodeIds);if(!a)return null;if(r>0&&a.width*a.height>=r*0.75)return null;return i("div",{class:"attention-field-region",style:Gu(a,42)},s.id,!1,void 0,this)}),t.map((s)=>{let a=Xu(s);if(!a)return null;return i("div",{class:"attention-field-node attention-field-secondary",style:Gu({left:a.left-18,top:a.top-18,width:a.width+36,height:a.height+36},28)},`secondary-${s}`,!1,void 0,this)}),e.map((s)=>{let a=Xu(s);if(!a)return null;return i("div",{class:"attention-field-node attention-field-primary",style:Gu({left:a.left-24,top:a.top-24,width:a.width+48,height:a.height+48},30)},`primary-${s}`,!1,void 0,this)})]},void 0,!0,void 0,this)}var pE=new Set(["png","jpg","jpeg","gif","svg","webp","bmp","ico","avif"]),fE=new Set(["md","mdx","markdown"]);function mE(e){let t=e.split(".").pop()?.toLowerCase()??"";if(pE.has(t))return"image";if(fE.has(t))return"markdown";return"file"}async function Pa(e,t,n){let a=Math.ceil(Math.sqrt(e.length));for(let c=0;c<e.length;c++){let l=e[c],u=c%a,d=Math.floor(c/a),p=t-a*420/2+u*420,m=n-150+d*320,f=mE(l.name),g=l.name;if(f==="image"){let y=new FileReader,x=await new Promise((h)=>{y.onload=()=>h(y.result),y.readAsDataURL(l)});await Bt({type:"image",title:g,content:x,x:p,y:m,width:400,height:300})}else{let y=await l.text(),x=f==="markdown"||f==="file";await Bt({type:f,title:g,content:y,x:p,y:m,width:x?720:400,height:x?500:300})}}}var Ve=V(new Map),yr=V(null),hE=480,gE=320,vE=650,yi=new Map,vr=new Map,Na=new Map,vn=null;function Ku(e){Ve.value=e,yE()}function Ju(e){let t=yi.get(e);if(t)clearTimeout(t),yi.delete(e)}function Yu(e){let t=vr.get(e);if(t)clearTimeout(t),vr.delete(e)}function hx(e){if(Ju(e.id),Yu(e.id),!Ve.value.has(e.id))Na.set(e.id,Date.now());let t=new Map(Ve.value);t.set(e.id,{...e,phase:"forming"}),Ku(t)}function xi(e){if(Ju(e),Yu(e),Na.delete(e),!Ve.value.has(e))return;let t=new Map(Ve.value);t.delete(e),Ku(t)}function mx(e,t,n,o){let r=Ve.value.get(e);if(!r||r.phase===t)return;let s=new Map(Ve.value);s.set(e,{...r,phase:t,...o?{settledNodeId:o}:{}}),Ku(s),Ju(e),yi.set(e,setTimeout(()=>xi(e),n))}function gx(e,t,n,o){Yu(e);let r=Date.now()-(Na.get(e)??0),s=Math.max(0,vE-r);if(s===0){mx(e,t,n,o);return}vr.set(e,setTimeout(()=>{vr.delete(e),mx(e,t,n,o)},s))}function vx(e,t){gx(e,"settling",hE,t)}function Qu(e){gx(e,"dissolving",gE)}function ed(){for(let e of yi.values())clearTimeout(e);yi.clear();for(let e of vr.values())clearTimeout(e);if(vr.clear(),Na.clear(),vn)clearInterval(vn),vn=null;yr.value=null,Ve.value=new Map}function yE(){if(vn||Ve.value.size===0)return;vn=setInterval(()=>{let e=Date.now();for(let t of Ve.value.values())if(t.phase==="forming"&&t.expiresAt<=e)Qu(t.id);if(Ve.value.size===0&&vn)clearInterval(vn),vn=null},1000),vn.unref?.()}var xE={fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"};function we({size:e=16,children:t,...n}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",...xE,...n,children:t},void 0,!1,void 0,this)}function $a(e){return i(we,{...e,children:[i("polyline",{points:"1 5 1 1 5 1"},void 0,!1,void 0,this),i("polyline",{points:"11 1 15 1 15 5"},void 0,!1,void 0,this),i("polyline",{points:"15 11 15 15 11 15"},void 0,!1,void 0,this),i("polyline",{points:"5 15 1 15 1 11"},void 0,!1,void 0,this),i("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xx(e){return i(we,{...e,children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),i("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this),i("line",{x1:"7",y1:"5",x2:"7",y2:"9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bx(e){return i(we,{...e,children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),i("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _o(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"4",x2:"9.5",y2:"4"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"12",x2:"9.5",y2:"12"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"6.5",x2:"4",y2:"9.5"},void 0,!1,void 0,this),i("line",{x1:"12",y1:"6.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ma(e){return i(we,{...e,children:[i("rect",{x:"1",y:"2",width:"14",height:"12",rx:"1.5"},void 0,!1,void 0,this),i("rect",{x:"8",y:"7",width:"6",height:"6",rx:"1",fill:"currentColor","fill-opacity":"0.2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function wx(e){return i(we,{...e,children:[i("circle",{cx:"8",cy:"8",r:"3"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"1",x2:"8",y2:"3"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"13",x2:"8",y2:"15"},void 0,!1,void 0,this),i("line",{x1:"1",y1:"8",x2:"3",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"13",y1:"8",x2:"15",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"3.05",y1:"3.05",x2:"4.46",y2:"4.46"},void 0,!1,void 0,this),i("line",{x1:"11.54",y1:"11.54",x2:"12.95",y2:"12.95"},void 0,!1,void 0,this),i("line",{x1:"3.05",y1:"12.95",x2:"4.46",y2:"11.54"},void 0,!1,void 0,this),i("line",{x1:"11.54",y1:"4.46",x2:"12.95",y2:"3.05"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Oa(e){return i(we,{...e,children:i("path",{d:"M13 9.5A5.5 5.5 0 1 1 6.5 3 4.5 4.5 0 0 0 13 9.5Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function td(e){return i(we,{...e,children:[i("path",{d:"M3 13l2.8-.7L13 5.1 10.9 3 3.7 10.2 3 13Z"},void 0,!1,void 0,this),i("path",{d:"M9.8 4.1l2.1 2.1"},void 0,!1,void 0,this),i("path",{d:"M2.5 14h11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nd(e){return i(we,{...e,children:[i("path",{d:"M3 10.5 8.5 5a2 2 0 0 1 2.8 0l1.7 1.7a2 2 0 0 1 0 2.8L8.5 14H5.8L3 11.2Z"},void 0,!1,void 0,this),i("path",{d:"M7.5 6 12 10.5"},void 0,!1,void 0,this),i("path",{d:"M8.5 14H14"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function od(e){return i(we,{...e,children:[i("path",{d:"M3 4h10"},void 0,!1,void 0,this),i("path",{d:"M8 4v8"},void 0,!1,void 0,this),i("path",{d:"M6 12h4"},void 0,!1,void 0,this),i("path",{d:"M4.5 4 4 6"},void 0,!1,void 0,this),i("path",{d:"M11.5 4 12 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _x(e){return i(we,{...e,children:[i("rect",{x:"1",y:"4",width:"14",height:"10",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M5.5 4 L6.5 2.5 H9.5 L10.5 4"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"9",r:"2.3"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Sx(e){return i(we,{...e,children:[i("circle",{cx:"8",cy:"8",r:"6"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"8",r:"3"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"8",r:"0.8",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kx(e){return i(we,{...e,children:[i("circle",{cx:"8",cy:"8",r:"6"},void 0,!1,void 0,this),i("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"10.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"5.5",x2:"5.5",y2:"10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Cx(e){return i(we,{...e,children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Tx(e){return i(we,{...e,children:[i("rect",{x:"1",y:"3",width:"14",height:"10",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"6",x2:"5",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"7.5",y1:"6",x2:"8.5",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"11",y1:"6",x2:"12",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"10",x2:"12",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function br(e){return i(we,{...e,children:i("path",{d:"M2 13 L2 4 A2 2 0 0 1 4 2 L12 2 A2 2 0 0 1 14 4 L14 9 A2 2 0 0 1 12 11 L5 11 Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Ex({size:e=22,class:t}){return i("svg",{width:e,height:e,viewBox:"0 0 64 64",xmlns:"http://www.w3.org/2000/svg",class:t,"aria-hidden":"true",children:[i("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.35"},void 0,!1,void 0,this),i("rect",{x:"16",y:"16",width:"32",height:"32",rx:"5",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.6"},void 0,!1,void 0,this),i("rect",{x:"24",y:"24",width:"16",height:"16",rx:"3",fill:"none",stroke:"currentColor","stroke-width":"2.2"},void 0,!1,void 0,this),i("rect",{x:"29",y:"29",width:"6",height:"6",rx:"1",fill:"currentColor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ix({size:e=15}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M3 2l10 5.5-4.2 1.3L7.5 13z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Ax({size:e=15}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M5 7.5V3.8a1 1 0 0 1 2 0V7m0-3.9a1 1 0 0 1 2 0V7m0-2.7a1 1 0 0 1 2 0V7.4m0-.9a1 1 0 0 1 2 0v3.2A4.3 4.3 0 0 1 8.7 14H8a4.3 4.3 0 0 1-3.6-2L2.7 9.3a1 1 0 0 1 1.6-1.2L5 9.2"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function zx({size:e=15}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M6 4.5L2.5 8 6 11.5M10 4.5L13.5 8 10 11.5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Bn(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"6",x2:"10",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"8.5",x2:"8",y2:"8.5"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"11",x2:"11",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M4 13.5 L5.5 11.5 L8 11.5"},void 0,!1,void 0,this),i("polyline",{points:"5 6 7 8 5 10"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"10",x2:"11",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function wE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M12 13.5 L10.5 11.5 L8 11.5"},void 0,!1,void 0,this),i("circle",{cx:"5",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"11",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ra(e){return i(we,{...e,children:[i("path",{d:"M3 1.5h6l3.5 3.5v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V2.5a1 1 0 0 1 1-1z"},void 0,!1,void 0,this),i("polyline",{points:"9 1.5 9 5 12.5 5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"8.5",x2:"10.5",y2:"8.5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"11",x2:"9",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function rd(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("circle",{cx:"5.5",cy:"6.5",r:"1.2"},void 0,!1,void 0,this),i("path",{d:"M1.8 12 L6 8.5 L9 11 L11.5 9 L14.2 12"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xr(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"1.5",y1:"5.5",x2:"14.5",y2:"5.5"},void 0,!1,void 0,this),i("circle",{cx:"3.3",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"5",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"6.7",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"8",x2:"12",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"10",x2:"10",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _E(e){return i(we,{...e,children:[i("rect",{x:"2",y:"4",width:"12",height:"10",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"2",y1:"6.5",x2:"14",y2:"6.5"},void 0,!1,void 0,this),i("path",{d:"M11 1.5 L11 4"},void 0,!1,void 0,this),i("circle",{cx:"11",cy:"4",r:"1.6",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function id(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"1.5","stroke-dasharray":"2 1.5"},void 0,!1,void 0,this),i("rect",{x:"4",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),i("rect",{x:"8.5",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),i("rect",{x:"6.25",y:"8.5",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function SE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M3.5 10.5 L6 6.5 L8.5 9.5 L12.5 5"},void 0,!1,void 0,this),i("circle",{cx:"12.5",cy:"5",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function CE(e){return i(we,{...e,children:[i("rect",{x:"2",y:"2",width:"12",height:"12",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"5.5",x2:"11.5",y2:"5.5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"8",x2:"11.5",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"10.5",x2:"8",y2:"10.5"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"2",x2:"6.5",y2:"14",opacity:"0.45"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function TE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"2"},void 0,!1,void 0,this),i("path",{d:"M4 11 L4 6 L6 8.5 L8 6 L8 11"},void 0,!1,void 0,this),i("path",{d:"M10 11 L10 6 L12.5 11 L12.5 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function EE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("polyline",{points:"10 5 13 5 13 8"},void 0,!1,void 0,this),i("line",{x1:"13",y1:"5",x2:"8",y2:"10"},void 0,!1,void 0,this),i("path",{d:"M6 6 L3.5 6 L3.5 11.5 L10 11.5 L10 9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function IE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M7 5.5 C 5.5 5.5 5.5 8 4 8 C 5.5 8 5.5 10.5 7 10.5"},void 0,!1,void 0,this),i("path",{d:"M9 5.5 C 10.5 5.5 10.5 8 12 8 C 10.5 8 10.5 10.5 9 10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yx(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"5.2",y1:"6",x2:"8",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"8",x2:"10.8",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"8",x2:"8",y2:"11"},void 0,!1,void 0,this),i("circle",{cx:"5.2",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"10.8",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"8",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"11",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yn(e){switch(e){case"markdown":return Bn;case"prompt":return bE;case"response":return wE;case"file":return Ra;case"diff":return Ra;case"mermaid":return yx;case"image":return rd;case"webpage":return xr;case"context":return _E;case"group":return id;case"status":return SE;case"trace":return kE;case"ledger":return CE;case"mcp-app":return TE;case"ext-app":return EE;case"json-render":return IE;case"graph":return yx;case"html":return xr;default:return Bn}}var Px={width:260,height:150},AE={markdown:{width:300,height:170},status:{width:280,height:110},context:{width:300,height:200},trace:{width:220,height:64},file:{width:300,height:190},image:{width:260,height:200},webpage:{width:320,height:210},html:{width:320,height:210},group:{width:340,height:210},graph:{width:320,height:210},"json-render":{width:320,height:210},"mcp-app":{width:340,height:230}};function ad(e){return!!e&&e in it}function xn(e){if(!e)return null;let t=M.value.get(e);if(!t)return null;return{left:t.position.x,top:t.position.y,width:t.size.width,height:t.size.height}}function sd(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function bi(e){let t=typeof e.confidence!=="number"?0.82:0.4+Math.max(0,Math.min(1,e.confidence))*0.55;return e.auto?t*0.62:t}function Nx(e,t){let n=Math.max(40,Math.abs(t.x-e.x)/2);return`M ${e.x} ${e.y} C ${e.x+n} ${e.y}, ${t.x-n} ${t.y}, ${t.x} ${t.y}`}function cd({intent:e}){let t=ad(e.nodeType)?yn(e.nodeType):null,n=e.label||e.kind,o=typeof e.confidence==="number"?`${Math.round(e.confidence*100)}%`:null;return i("div",{class:"intent-info",onMouseEnter:()=>yr.value=e.id,onMouseLeave:()=>{if(yr.value===e.id)yr.value=null},children:[i("div",{class:"intent-chip",children:[typeof e.seq==="number"&&i("span",{class:"intent-seq",children:e.seq},void 0,!1,void 0,this),t&&i("span",{class:"intent-chip-icon","aria-hidden":"true",children:i(t,{size:12},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"intent-chip-label",children:n},void 0,!1,void 0,this),o&&i("span",{class:"intent-confidence",children:o},void 0,!1,void 0,this),e.phase==="forming"&&!e.auto&&i("button",{type:"button",class:"intent-veto",title:"Veto this move (Esc)","aria-label":"Veto this move",onClick:(r)=>{r.stopPropagation(),io(e)},children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.reason&&i("div",{class:"intent-reason",children:e.reason},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Rx({intent:e,rect:t}){let n=ad(e.nodeType)?yn(e.nodeType):null,o=ad(e.nodeType)?it[e.nodeType]:"Node";return i("div",{class:`intent-ghost intent-ghost-box is-${e.phase}${e.auto?" is-auto":""}`,"data-intent-id":e.id,style:{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`,opacity:bi(e)},children:[i("div",{class:"intent-ghost-titlebar",children:[i("span",{class:"intent-ghost-icon","aria-hidden":"true",children:n?i(n,{size:13},void 0,!1,void 0,this):"◇"},void 0,!1,void 0,this),i("span",{class:"intent-ghost-badge",children:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(cd,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function $x({intent:e,rect:t,variant:n}){return i("div",{class:`intent-ghost intent-ghost-${n} is-${e.phase}${e.auto?" is-auto":""}`,"data-intent-id":e.id,style:{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`,opacity:bi(e)},children:[n==="edit"&&i("div",{class:"intent-edit-bar"},void 0,!1,void 0,this),i(cd,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zE(e){let t=e.phase==="settling"?xn(e.settledNodeId):null;switch(e.kind){case"create":{if(!e.position)return null;let n=e.nodeType&&AE[e.nodeType]||Px,o=t??{left:e.position.x,top:e.position.y,...n};return i(Rx,{intent:e,rect:o},e.id,!1,void 0,this)}case"move":{if(!e.position)return null;let o=xn(e.nodeId)??Px,r=t??{left:e.position.x,top:e.position.y,width:o.width,height:o.height};return i(Rx,{intent:e,rect:r},e.id,!1,void 0,this)}case"remove":{let n=t??xn(e.nodeId);if(!n)return null;return i($x,{intent:e,rect:n,variant:"remove"},e.id,!1,void 0,this)}case"edit":{let n=t??xn(e.nodeId);if(!n)return null;return i($x,{intent:e,rect:n,variant:"edit"},e.id,!1,void 0,this)}case"connect":{if(!e.edge)return null;let n=xn(e.edge.from),o=xn(e.edge.to);if(!n||!o)return null;let r={x:(n.left+n.width/2+o.left+o.width/2)/2,y:(n.top+n.height/2+o.top+o.height/2)/2},s={left:r.x-110,top:r.y-18,width:220,height:36};return i("div",{class:`intent-ghost intent-ghost-connect is-${e.phase}${e.auto?" is-auto":""}`,"data-intent-id":e.id,style:{left:`${s.left}px`,top:`${s.top}px`,width:`${s.width}px`,opacity:bi(e)},children:i(cd,{intent:e},void 0,!1,void 0,this)},e.id,!1,void 0,this)}default:return null}}function Mx(){let e=Array.from(Ve.value.values());if(D(()=>{function t(n){if(n.key!=="Escape")return;let o=yr.value;if(!o)return;let r=Ve.value.get(o);if(!r||r.phase!=="forming")return;n.stopImmediatePropagation(),n.preventDefault(),io(r)}return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[]),e.length===0)return null;return i("div",{class:"intent-layer",children:[i("svg",{class:"intent-line-layer",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"},children:[i("defs",{children:i("marker",{id:"intent-arrow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"3",orient:"auto",children:i("path",{d:"M0,0 L6,3 L0,6 Z",class:"intent-arrow-head"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e.map((t)=>{if(t.kind==="connect"&&t.edge){let n=xn(t.edge.from),o=xn(t.edge.to);if(!n||!o)return null;return i("path",{d:Nx(sd(n),sd(o)),class:`intent-edge type-${t.edge.type}`,style:{opacity:bi(t)}},`line-${t.id}`,!1,void 0,this)}if(t.kind==="move"&&t.position){let n=xn(t.nodeId);if(!n)return null;let o=n,r={x:t.position.x+o.width/2,y:t.position.y+o.height/2};return i("path",{d:Nx(sd(n),r),class:"intent-trail",markerEnd:"url(#intent-arrow)",style:{opacity:bi(t)}},`line-${t.id}`,!1,void 0,this)}return null})]},void 0,!0,void 0,this),e.map(zE)]},void 0,!0,void 0,this)}var Ox=32000;var La="Agent session";function Lx(e){return e.some((t)=>t.attached)}function Dx(e){return e.filter((t)=>!t.attached)}function Un(e){switch(e.phase){case"thinking":return"Thinking";case"tooling":return e.detail?`Running ${e.detail}`:"Working";case"waiting-approval":return"Waiting on you";default:return"Idle"}}function Wn(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t%360+360)%360}var pt=V([]),ud=V({used:0,total:Ox}),qn=V([]),So=V(!1),wr=V(!1),dd=V(null),Fx=["var(--c-purple)","var(--c-accent)","var(--c-ok)","var(--c-warn)","var(--c-danger)"],ld=new Map;function Da(e){let t=ld.get(e);if(t)return t;let n=Fx[ld.size%Fx.length];return ld.set(e,n),n}function jx(e){return(e.trim().replace(/^[^a-z0-9]+/i,"").charAt(0)||e.trim().charAt(0)||"?").toUpperCase()}function Fa(e,t=Date.now()){let n=t-Date.parse(e);if(!Number.isFinite(n)||n<5000)return"now";if(n<60000)return`${Math.floor(n/1000)}s`;if(n<3600000)return`${Math.floor(n/60000)}m`;return`${Math.floor(n/3600000)}h`}var ft=Oe(()=>Lx(pt.value)),pd=Oe(()=>Dx(pt.value)),Zx=Oe(()=>{let e=new Set;return[...pt.value].filter((t)=>t.label!==La).sort((t,n)=>Number(n.attached)-Number(t.attached)).map((t)=>({value:t.sessionId==="browser"?t.label:t.sessionId,label:t.label,attached:t.attached,steerable:t.attached||t.steerable===!0,pendingSteers:t.pendingSteers??0,polling:t.lastClaimAt!==void 0&&Date.now()-Date.parse(t.lastClaimAt)<300000})).filter((t)=>e.has(t.value)?!1:(e.add(t.value),!0))}),Hx=Oe(()=>pt.value.filter((e)=>e.attached)),_r=Oe(()=>pt.value.find((e)=>e.attached)??null);function PE(e){let t=new Set;for(let n of e)if(n.nodeId&&n.kind!=="create")t.add(n.nodeId);return t}var Bx=Oe(()=>PE(Ve.value.values()));function ja(e,t){if(e.cursor)return{x:e.cursor.x,y:e.cursor.y};if(!e.focusNodeId)return null;let n=t(e.focusNodeId);if(!n)return null;return{x:n.position.x+Math.max(24,n.size.width-28),y:n.position.y+16}}function fd(e){if(!e)return;if(Array.isArray(e.presences))pt.value=e.presences;if(e.budget&&Number.isFinite(e.budget.used)&&Number.isFinite(e.budget.total))ud.value={used:e.budget.used,total:e.budget.total};if(Array.isArray(e.activity))qn.value=e.activity}function Ux(){let e=R(new Map),t=re.value.scale,n=M.value,o=1/Math.max(0.05,t),r=pt.value.map((s)=>{let a=ja(s,(l)=>n.get(l));if(a)e.current.set(s.sessionId,a);let c=a??e.current.get(s.sessionId)??null;return c?{presence:s,position:c}:null}).filter((s)=>s!==null);if(r.length===0)return null;return i("div",{class:"agent-presence-layer","aria-hidden":"true",children:r.map(({presence:s,position:a})=>i("div",{class:`agent-cursor phase-${s.phase}${s.attached?"":" is-external"}${s.parentAgentId?" is-worker":""}`,"data-session-id":s.sessionId,style:{transform:`translate(${a.x}px, ${a.y}px)`,"--identity-color":`hsl(${Wn(s.sessionId)} 65% 62%)`},children:i("div",{class:"agent-cursor-inner",style:{transform:`scale(${o})`},children:[i("svg",{class:"agent-cursor-glyph",width:"16",height:"18",viewBox:"0 0 16 18","aria-hidden":"true",children:i("path",{d:"M1.5 1.5L14.5 9.2 8.3 10.6 5.2 16.5z",fill:"currentColor",stroke:"var(--c-bg)","stroke-width":"1.2"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"agent-cursor-chip",children:[i("span",{class:"agent-cursor-dot"},void 0,!1,void 0,this),i("span",{class:"agent-cursor-label",children:Un(s)},void 0,!1,void 0,this),i("span",{class:"agent-cursor-who",children:s.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},s.sessionId,!1,void 0,this))},void 0,!1,void 0,this)}var Wx=30000;var md=80;function NE(e,t){try{let n=window.sessionStorage.getItem(e);if(n)return n;let o=t();return window.sessionStorage.setItem(e,o),o}catch{return t()}}var Ua=NE("pmx-canvas-human-client",()=>`tab-${Math.random().toString(36).slice(2,8)}`);function RE(){try{let e=new URLSearchParams(window.location.search).get("name")?.trim();if(e)return window.localStorage.setItem("pmx-canvas-human-name",e),e;let t=window.localStorage.getItem("pmx-canvas-human-name")?.trim();if(t)return t}catch{}return`guest-${Ua.slice(-4)}`}var Vx=V(RE()),Gx=V([]),hd=Oe(()=>Gx.value.filter((e)=>e.clientId!==Ua)),ko=V(new Map);function gd(e){if(!e||!Array.isArray(e.humans))return;Gx.value=e.humans}var Ha=null,Wa=null,Xx=0,wi=null;function Ba(e){Ht("humanPresence","/api/canvas/human-presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:Ua,name:Vx.value,...e})})}function qx(){wi=null,Xx=Date.now(),Ba({cursor:Wa,grabbingNodeId:Ha})}function qa(e){Wa=e;let t=Date.now()-Xx;if(t>=md){if(wi)clearTimeout(wi);qx()}else if(!wi)wi=setTimeout(qx,md-t)}function vd(e){Ha=e,Ba({cursor:Wa,grabbingNodeId:e})}function $E(e,t){let n=new Map(ko.value);n.set(e,t),ko.value=n,setTimeout(()=>{let o=new Map(ko.value);if(o.get(e)===t)o.delete(e),ko.value=o},6000)}function Kx(e,t){let n=[...Ve.value.values()].filter((r)=>r.nodeId===e&&!r.auto&&r.phase==="forming");if(n.length===0)return;let o=Vx.value;$E(e,o);for(let r of n)io({id:r.id,kind:r.kind,label:r.label,reason:`${o} took over “${t}” mid-edit — yield and requeue the change once it is released`}).then((s)=>{if(s)xi(r.id)});Ht("yieldEvent","/api/canvas/ax/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"yield",summary:`${o} grabbed “${t}” mid-edit — agent yielded, change requeued`,nodeIds:[e],source:"browser"})})}var Za=null;function Jx(){Ba({cursor:Wa,grabbingNodeId:Ha}),Za=setInterval(()=>Ba({grabbingNodeId:Ha}),3000);let e=()=>{try{navigator.sendBeacon?.("/api/canvas/human-presence",new Blob([JSON.stringify({clientId:Ua,left:!0})],{type:"application/json"}))}catch{}};return window.addEventListener("pagehide",e),()=>{if(Za)clearInterval(Za);Za=null,window.removeEventListener("pagehide",e)}}function bn(e=1000){let[t,n]=L(()=>Date.now());return D(()=>{if(e<=0)return;n(Date.now());let o=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(o)},[e]),t}function Yx(){let e=bn(hd.value.length>0?5000:0),t=hd.value.filter((o)=>o.cursor!==null&&(!o.lastSeenAt||e-Date.parse(o.lastSeenAt)<Wx+5000));if(t.length===0)return null;let n=1/Math.max(0.05,re.value.scale);return i("div",{class:"human-presence-layer","aria-hidden":"true",children:t.map((o)=>i("div",{class:`human-cursor${o.grabbingNodeId?" is-grabbing":""}`,"data-client-id":o.clientId,style:{transform:`translate(${o.cursor.x}px, ${o.cursor.y}px)`},children:i("div",{class:"human-cursor-inner",style:{transform:`scale(${n})`},children:[i("svg",{class:"human-cursor-glyph",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",children:i("path",{d:"M3 2 L13 8 L8.5 9.5 L6.5 14 Z",fill:"currentColor",stroke:"var(--c-bg)","stroke-width":"1"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"human-cursor-tag",children:o.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},o.clientId,!1,void 0,this))},void 0,!1,void 0,this)}function Va(e,t){let{POSITIVE_INFINITY:n,POSITIVE_INFINITY:o,NEGATIVE_INFINITY:r,NEGATIVE_INFINITY:s}=Number,a=0;for(let c of e)a+=1,n=Math.min(n,c.position.x),o=Math.min(o,c.position.y),r=Math.max(r,c.position.x+c.size.width),s=Math.max(s,c.position.y+c.size.height);if(a===0)return null;return{x:n-t,y:o-t,width:r-n+t*2,height:s-o+t*2}}function xd(){let e=Gt.value;return e&&typeof e==="object"?e:{}}var Qx=Oe(()=>xd().workItems??[]),eb=Oe(()=>xd().approvalGates??[]),Co=Oe(()=>eb.value.filter((e)=>e.status==="pending")),Vn=Oe(()=>{let e=xd().policy?.scope;return e&&Array.isArray(e.nodeIds)&&e.nodeIds.length>0?{nodeIds:e.nodeIds,padding:typeof e.padding==="number"?e.padding:40}:null});async function tb(e){return(await Ct("setScopeFence","/api/canvas/ax/policy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e&&e.length>0?{nodeIds:e}:null,source:"browser"})})).ok}var nb=Oe(()=>eb.value.filter((e)=>e.status==="held")),ob=V({events:[],evidence:[],steering:[]}),To=V("all");function bd(e){if(e==="update")return"update";if(e==="steer"||e==="steering"||e==="yield")return"steer";if(e==="assistant-message")return"assistant";if(e==="evidence")return"evidence";return"event"}var ME=new Set(["api","mcp","sdk","cli"]);function yd(e,t){if(e?.trim())return e.trim();let n=t?.trim();if(n&&!ME.has(n))return n;return null}var OE=/^(node|edge|group|annotation|jsonrender|graph|render)\.|^arrange$|^canvas\.clear$|^snapshot\.restore$/,rb=V(null),_i=V(new Set),LE={prompt:"Prompt","assistant-message":"Assistant","tool-start":"Tool run","tool-result":"Tool result",failure:"Failure",approval:"Approval",steering:"Steering",command:"Command",note:"Note",policy:"Policy",yield:"Yield"};function DE(e,t=40,n=[],o=null,r="all"){let s=n.find((l)=>OE.test(l.op)),a=[...n.map((l)=>({id:`update-${l.id}`,kind:"update",label:"Update",body:l.summary,createdAt:l.at,who:l.sessionId??null,...o?.actor==="agent"&&s?.id===l.id?{undoable:!0}:{}})),...e.events.map((l)=>({id:`event-${l.id}`,kind:l.kind,label:LE[l.kind]??l.kind,body:l.detail?`${l.summary} — ${l.detail}`:l.summary,createdAt:l.createdAt,who:yd(l.agentId,l.source)})),...e.evidence.map((l)=>({id:`evidence-${l.id}`,kind:"evidence",label:"Evidence",body:l.body?`${l.title} — ${l.body}`:l.title,createdAt:l.createdAt,who:yd(l.agentId,l.source)})),...e.steering.map((l)=>{let u=l.agentId??(l.source&&l.source!=="browser"?l.source:null),d=l.target?`→ ${l.target} · `:u?"→ all · ":"",p=l.target&&l.delivered===!1?` — waiting for ${l.target} to pick it up`:"";return{id:`steer-${l.id}`,kind:"steer",label:"Steer",body:`${u?`${u} `:""}${d}${l.message}${p}`,createdAt:l.createdAt,who:yd(l.agentId,l.source)}})],c=r==="all"?a:a.filter((l)=>bd(l.kind)===r);return c.sort((l,u)=>l.createdAt<u.createdAt?1:l.createdAt>u.createdAt?-1:0),c.slice(0,t)}var ib=Oe(()=>DE(ob.value,40,qn.value,rb.value,To.value));async function Gn(){let[e,t]=await Promise.all([ge("refreshTimeline","/api/canvas/ax/timeline?limit=40",null),ge("refreshHistoryTop","/api/canvas/history",null)]);if(t)rb.value=t.top??null;if(!e)return;ob.value={events:Array.isArray(e.events)?e.events:[],evidence:Array.isArray(e.evidence)?e.evidence:[],steering:Array.isArray(e.steering)?e.steering:[]}}async function wd(e){if(!(await Ct("undoAgentEdit","/api/canvas/undo",{method:"POST"})).ok)return!1;return _i.value=new Set([..._i.value,e.id]),await Ht("undoAgentEditSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:`Undid your edit: ${e.body} — it was reverted on the board.`,source:"browser"})}),Gn(),!0}async function _d(e=!1){let t=await Ct(e?"redo":"undo",e?"/api/canvas/redo":"/api/canvas/undo",{method:"POST"});if(t.ok)Gn();return t.ok}async function sb(e,t){if(!(await Ct("resolveGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/resolve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:t,source:"browser"})})).ok)return!1;if(t==="rejected")await Ht("rejectGateSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:`Rejected gate "${e.title}" — do not proceed with it.`,source:"browser"})});return!0}async function ab(e){return(await Ct("reopenGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/reopen`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser"})})).ok}async function cb(e,t){return(await Ct("sendSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,source:"browser",...t?{target:t}:{}})})).ok}async function Xn(){return(await Ct("startSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser",label:La,attached:!0,phase:"idle"})})).ok}async function Ga(e){return(await Ct("endSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:e.source,agentId:e.agentId,attached:!1,endedBy:"human"})})).ok}var Xa=V(null);function lb(e){let{counts:t,snapshot:n}=e;if(typeof e.label!=="string"||typeof e.endedAt!=="string")return;Xa.value={label:e.label,endedAt:e.endedAt,endedBy:e.endedBy==="human"||e.endedBy==="agent"||e.endedBy==="idle-timeout"?e.endedBy:void 0,unchanged:e.unchanged===!0,counts:{items:Number(t?.items??0)||0,done:Number(t?.done??0)||0,cancelled:Number(t?.cancelled??0)||0,rejected:Number(t?.rejected??0)||0,held:Number(t?.held??0)||0},snapshot:n&&typeof n.id==="string"?{id:n.id,name:String(n.name??"")}:null}}function ub(){Xa.value=null}function db(){if(!ft.value)return null;let e=Vn.value;if(!e)return null;let t=M.value,n=e.nodeIds.map((s)=>t.get(s)).filter((s)=>s!==void 0),o=Va(n,e.padding);if(!o)return null;let r=1/Math.max(0.05,re.value.scale);return i("div",{class:"scope-fence","data-fenced-count":n.length,style:{transform:`translate(${o.x}px, ${o.y}px)`,width:`${o.width}px`,height:`${o.height}px`},"aria-hidden":"true",children:[i("span",{class:"scope-fence-pill scope-fence-pill-top",style:{transform:`scale(${r})`},children:["Agent scope · ",n.length," node",n.length===1?"":"s"]},void 0,!0,void 0,this),i("span",{class:"scope-fence-pill scope-fence-pill-bottom",style:{transform:`scale(${r})`},children:"writes outside are blocked · reads allowed"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Ka={markdown:"var(--c-accent)","mcp-app":"var(--c-ok)",webpage:"var(--c-warn)","json-render":"var(--c-ok)",graph:"var(--c-purple)",prompt:"var(--c-accent)",response:"var(--c-ok)",status:"var(--c-warn)",context:"var(--c-muted)",ledger:"var(--c-dim)",trace:"var(--c-purple)",file:"var(--c-accent)",diff:"var(--c-ok)",mermaid:"var(--c-purple)",image:"var(--c-ok)",html:"var(--c-warn)",group:"var(--c-accent)"};function FE(e){let t=typeof e==="number"&&Number.isFinite(e)?Math.floor(e):1;return Math.max(1,Math.min(20,t))}function Ja(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Si(e){return typeof e==="string"&&e.length>0}function pb(e){let t=e.axStep;if(!Ja(t))return null;if(!Si(t.flowId)||!Si(t.workItemId))return null;if(typeof t.index!=="number"||typeof t.total!=="number")return null;return{flowId:t.flowId,index:t.index,total:t.total,workItemId:t.workItemId}}function fb(e){let t=e.axFlow;if(!Ja(t)||!Si(t.flowId)||!Array.isArray(t.steps))return null;let n=[];for(let r of t.steps){if(!Ja(r)||!Si(r.nodeId)||!Si(r.workItemId))return null;if(typeof r.index!=="number")return null;n.push({index:r.index,nodeId:r.nodeId,workItemId:r.workItemId,title:typeof r.title==="string"?r.title:""})}if(n.length===0)return null;let o=Ja(t.loop)?t.loop:{};return{flowId:t.flowId,title:typeof t.title==="string"?t.title:"Flow",steps:n,loop:{running:o.running===!0,run:typeof o.run==="number"&&Number.isFinite(o.run)?Math.max(0,Math.floor(o.run)):0,maxRuns:FE(o.maxRuns)}}}var jE={position:"sticky",bottom:"calc(-1 * var(--ax-dock-bleed, 12px))",marginTop:"12px",marginLeft:"calc(-1 * var(--ax-dock-bleed, 12px))",marginRight:"calc(-1 * var(--ax-dock-bleed, 12px))",marginBottom:"calc(-1 * var(--ax-dock-bleed, 12px))",padding:"9px var(--ax-dock-pad, 12px) 10px",background:"var(--c-panel-overlay)",borderTop:"1px solid var(--c-line)",backdropFilter:"blur(6px)"},hb={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},gb={fontSize:"10px",color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginRight:"auto"},vb={...ao,background:"var(--c-accent-25)",color:"var(--c-text)"},ZE=[{status:"in-progress",label:"Start",toast:"Step started"},{status:"done",label:"Done",toast:"Step done"},{status:"blocked",label:"Blocked",toast:"Step blocked"}];async function mb(e,t,n){let o={...t,loop:n};oe(e.id,{axFlow:o}),await rt(e.id,{data:{axFlow:o}})}function yb(e){return typeof e?.axWorkStatus==="string"?e.axWorkStatus:"todo"}function HE({node:e,flow:t}){let[n,o]=L(""),{running:r,run:s,maxRuns:a}=t.loop,c=async()=>{await mb(e,t,{running:!0,run:s>=a?0:s,maxRuns:a});let u=t.steps.find((p)=>yb(M.value.get(p.nodeId)?.data)!=="done"),d=u??t.steps[t.steps.length-1];await zn(e,"ax.work.update",{id:d.workItemId,status:u?"in-progress":"done"},"Loop running")},l=async()=>{let u=n.trim();if(!u)return;await zn(e,"ax.steer",{message:u},"Steering sent"),o("")};return i("div",{class:"ax-flow-controls",style:{...hb,marginTop:"6px",rowGap:"4px"},children:[i("span",{class:"ax-flow-runs",style:gb,children:r?`Loop running · run ${s+1}/${a}`:`Loop idle · ${s}/${a} runs`},void 0,!1,void 0,this),r?i("button",{type:"button",class:"ax-node-action",style:vb,title:"Stop the loop now. The stop is persisted on this node, so it survives a refresh and no further step is opened.",onClick:(u)=>{u.stopPropagation(),mb(e,t,{...t.loop,running:!1})},children:"Stop"},void 0,!1,void 0,this):i("button",{type:"button",class:"ax-node-action",style:ao,title:"Run this flow as a loop: each completed step opens the next one, and the last step starts the next run — until the run cap is reached or you press Stop.",onClick:(u)=>{u.stopPropagation(),c()},children:"Run loop"},void 0,!1,void 0,this),i("input",{class:"ax-flow-steer-input",value:n,placeholder:"Steer the agent…","aria-label":"Steer the agent",onInput:(u)=>o(u.target.value),onClick:(u)=>u.stopPropagation(),onKeyDown:(u)=>{if(u.key!=="Enter")return;u.stopPropagation(),l()},style:{flex:"1 1 120px",minWidth:"90px",fontSize:"10px",padding:"3px 6px",borderRadius:"4px",border:"1px solid var(--c-line)",background:"var(--c-panel-overlay)",color:"var(--c-text)"}},void 0,!1,void 0,this),i("button",{type:"button",class:"ax-node-action",style:ao,title:"Send a steering message to the agent working this flow.",onClick:(u)=>{u.stopPropagation(),l()},children:"Steer"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ya({node:e}){let t=pb(e.data);if(!t)return null;let n=fb(e.data),o=yb(e.data);return i("div",{class:"ax-step-dock",style:jE,children:[i("div",{class:"ax-step-controls",style:hb,children:[i("span",{class:"ax-step-position",style:gb,children:["Step ",t.index,"/",t.total]},void 0,!0,void 0,this),ZE.map((r)=>i("button",{type:"button",class:"ax-node-action","aria-pressed":o===r.status,style:o===r.status?vb:ao,title:`Set this step's work item to "${r.status}".`,onClick:(s)=>{s.stopPropagation(),zn(e,"ax.work.update",{id:t.workItemId,status:r.status},r.toast)},children:r.label},r.status,!1,void 0,this))]},void 0,!0,void 0,this),n&&i(HE,{node:e,flow:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Sr=8,Eo=V(null),kr=[],Cr=[],wb=null;function xb(e){let t=e?.data.parentGroup;return typeof t==="string"&&t.length>0?t:null}function bb(e){if(!e||!Array.isArray(e.data.children))return[];return e.data.children.filter((t)=>typeof t==="string")}function BE(e,t){let n=new Map(t.map((c)=>[c.id,c])),o=new Set([e]),r=n.get(e);if(!r)return o;let s=xb(r);while(s&&!o.has(s))o.add(s),s=xb(n.get(s));if(r.type!=="group")return o;let a=[...bb(r)];while(a.length>0){let c=a.pop();if(!c||o.has(c))continue;o.add(c);let l=n.get(c);if(l?.type==="group")a.push(...bb(l))}return o}function _b(e,t){kr=[],Cr=[],wb=e;let n=Array.from(t),o=BE(e,n);for(let r of n){if(o.has(r.id))continue;let s=r.position.x,a=r.position.x+r.size.width,c=r.position.x+r.size.width/2,l=r.position.y,u=r.position.y+r.size.height,d=r.position.y+r.size.height/2;kr.push({val:s,minY:l,maxY:u}),kr.push({val:a,minY:l,maxY:u}),kr.push({val:c,minY:l,maxY:u}),Cr.push({val:l,minX:s,maxX:a}),Cr.push({val:u,minX:s,maxX:a}),Cr.push({val:d,minX:s,maxX:a})}}function Sb(){kr=[],Cr=[],wb=null}function kb(e,t,n,o){let r=[e,e+n/2,e+n],s=[t,t+o/2,t+o],a=[0,n/2,n],c=[0,o/2,o],l=null,u=Sr+1,d=null;for(let y=0;y<3;y++){let x=r[y];for(let h of kr){let v=Math.abs(x-h.val);if(v<u)u=v,l=h.val-a[y],d={axis:"x",pos:h.val,from:Math.min(h.minY,t),to:Math.max(h.maxY,t+o)}}}let p=null,m=Sr+1,f=null;for(let y=0;y<3;y++){let x=s[y];for(let h of Cr){let v=Math.abs(x-h.val);if(v<m)m=v,p=h.val-c[y],f={axis:"y",pos:h.val,from:Math.min(h.minX,e),to:Math.max(h.maxX,e+n)}}}let g=[];if(d&&u<=Sr)g.push(d);if(f&&m<=Sr)g.push(f);return{x:l!==null&&u<=Sr?l:e,y:p!==null&&m<=Sr?p:t,guides:g}}function Cb({nodeId:e,viewport:t,onMove:n,onDragEnd:o}){let r=R(!1),s=R({x:0,y:0}),a=R({x:0,y:0});return O((l,u,d)=>{l.stopPropagation(),l.preventDefault(),r.current=!0,document.documentElement.classList.add("is-node-dragging"),window.getSelection()?.removeAllRanges(),s.current={x:l.clientX,y:l.clientY},a.current={x:u,y:d};let p=null,m=null,f=()=>{if(m=null,!r.current||!p)return;let x=p;p=null;let h=t.value.scale,v=(x.x-s.current.x)/h,b=(x.y-s.current.y)/h;n(e,a.current.x+v,a.current.y+b)},g=(x)=>{if(!r.current)return;if(p={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(f)},y=()=>{if(m!==null)window.cancelAnimationFrame(m),f();r.current=!1,document.documentElement.classList.remove("is-node-dragging"),document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",y),document.removeEventListener("pointercancel",y),o()};document.addEventListener("pointermove",g),document.addEventListener("pointerup",y),document.addEventListener("pointercancel",y)},[e,t,n,o])}var UE=200,WE=100;function Tb({nodeId:e,viewport:t,onResize:n,onResizeEnd:o}){let r=R(!1),s=R({x:0,y:0}),a=R({w:0,h:0});return O((l,u,d)=>{l.stopPropagation(),l.preventDefault(),r.current=!0,s.current={x:l.clientX,y:l.clientY},a.current={w:u,h:d},document.documentElement.classList.add("is-node-resizing");let p=null,m=null,f=()=>{if(m=null,!r.current||!p)return;let x=p;p=null;let h=t.value.scale,v=(x.x-s.current.x)/h,b=(x.y-s.current.y)/h;n(e,Math.max(UE,a.current.w+v),Math.max(WE,a.current.h+b))},g=(x)=>{if(!r.current)return;if(p={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(f)},y=()=>{if(m!==null)window.cancelAnimationFrame(m),f();r.current=!1,document.documentElement.classList.remove("is-node-resizing"),document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",y),document.removeEventListener("pointercancel",y),o()};document.addEventListener("pointermove",g),document.addEventListener("pointerup",y),document.addEventListener("pointercancel",y)},[e,t,n,o])}var qE={ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1}};function VE(e,t,n){let o=e.position.x+e.size.width/2,r=e.position.y+e.size.height/2,s=null,a=Number.POSITIVE_INFINITY;for(let c of n){if(c.id===e.id)continue;let l=c.position.x+c.size.width/2-o,u=c.position.y+c.size.height/2-r,d=l*t.dx+u*t.dy;if(d<=0)continue;let p=Math.abs(l*t.dy)+Math.abs(u*t.dx);if(p>d)continue;let m=d+p*2;if(m<a)a=m,s=c}return s}var GE=0.4,XE=0.55,KE=175;function JE(e,t,n=0){if(!Number.isFinite(e)||e>=1)return 1;let r=Math.min(2.2,1/Math.max(e,0.01));if(Number.isFinite(t)&&t>0)r=Math.min(r,t*GE/nr);if(Number.isFinite(n)&&n>0)r=Math.min(r,n*XE/KE);return Math.max(1,r)}function Eb({node:e,children:t,onContextMenu:n}){let o=ke.value===e.id,r=ye.value.has(e.id),s=Ee.value.has(e.id),a=Lo.value.has(e.id),c=!a&&Do.value.has(e.id),l=Yi.value.has(e.id),u=!o&&gf.value.has(e.id),d=Nn.value,p=d!==null&&d.has(e.id),m=d!==null&&!d.has(e.id),[f,g]=L(!1),y=R(null),x=O((N,se,Me)=>{let de=kb(se,Me,e.size.width,e.size.height),jt=M.value.get(N);if(jt?.position.x===de.x&&jt.position.y===de.y){Eo.value=de.guides.length>0?de.guides:null;return}st(N,{position:{x:de.x,y:de.y}}),Eo.value=de.guides.length>0?de.guides:null,bf(N)},[e.size.width,e.size.height]),h=R(null),v=O(()=>{if(Sb(),Eo.value=null,vd(null),h.current)document.removeEventListener("keydown",h.current),h.current=null;Ye();let N=ln.value;if(xf(),!N||N.nodeId!==e.id)return;if(N.mode==="add")Fc(N.groupId,[e.id]);else{let se=M.value.get(N.groupId),Me=Array.isArray(se?.data.children)?se.data.children.filter((de)=>typeof de==="string"&&de!==e.id):[];as(N.groupId,Me)}},[e.id]),b=Cb({nodeId:e.id,viewport:re,onMove:x,onDragEnd:v}),z=O((N,se,Me)=>{let de=M.value.get(N);if(de?.size.width===se&&de.size.height===Me)return;st(N,{size:{width:se,height:Me}})},[]),F=O(()=>{oe(e.id,{userResized:!0}),rt(e.id,{data:{userResized:!0}}),Ye()},[e.id]),_=Tb({nodeId:e.id,viewport:re,onResize:z,onResizeEnd:F}),k=O((N)=>{N.stopPropagation(),N.preventDefault(),je.value={fromId:e.id,fromX:e.position.x+e.size.width/2,fromY:e.position.y+e.size.height/2,cursorX:e.position.x+e.size.width/2,cursorY:e.position.y+e.size.height/2,targetId:null}},[e.id,e.position.x,e.position.y,e.size.width,e.size.height]),T=O((N)=>{if(N.button!==0)return;if(f)return;if(yt.value==="connect"){k(N);return}if(N.shiftKey){N.stopPropagation(),Jc(e.id);return}if(fn(e.id),vd(e.id),Kx(e.id,typeof e.data.title==="string"&&e.data.title?e.data.title:e.type),_b(e.id,M.value.values()),e.type!=="group"){let se=(Me)=>{if(Me.key==="Escape")yf()};h.current=se,document.addEventListener("keydown",se)}b(N,e.position.x,e.position.y)},[e.id,e.type,e.data.title,e.position.x,e.position.y,b,f,k]),P=O((N)=>{if(N.button!==0)return;if(N.stopPropagation(),yt.value==="connect"){k(N);return}if(N.shiftKey){Jc(e.id);return}fn(e.id)},[e.id,k]),Z=O((N)=>{if((N.target instanceof Element?N.target:null)?.closest('button, input, textarea, select, a, [contenteditable="true"]'))return;if(n)n(N,e.id)},[n,e.id]),j=O((N)=>{let se=N.target;if(se&&se!==N.currentTarget&&se.closest('input, textarea, [contenteditable="true"]'))return;let Me=qE[N.key];if(Me){N.preventDefault();let de=VE(e,Me,M.value.values());if(!de)return;fn(de.id),requestAnimationFrame(()=>{document.querySelector(`.canvas-node[data-node-id="${CSS.escape(de.id)}"]`)?.focus()})}else if(N.key==="Enter"&&N.target===N.currentTarget&&Fr.has(e.type))N.preventDefault(),en(e.id)},[e]),E=e.data.title||(e.type==="file"?(e.data.path||e.data.content||"").split(/[\\/]/).pop()??"":"")||it[e.type],B=O((N)=>{let se=N.trim();if(se&&se!==E)oe(e.id,{title:se}),rt(e.id,{title:se});g(!1)},[e.id,E]),W=R(null),H=R(!1),U=R(null);D(()=>{if(H.current||!Sl(e))return;let N=W.current;if(!N)return;let se=new ResizeObserver(()=>{if(H.current){se.disconnect();return}let Me=N.scrollHeight,de=Cm(e,Me);if(de===null)return;if(Math.abs(de-e.size.height)>8){if(Ko(e.id,{width:e.size.width,height:de}),U.current!==null)window.clearTimeout(U.current);U.current=window.setTimeout(()=>{Ye({recordHistory:!1}),U.current=null},0)}H.current=!0,se.disconnect()});return se.observe(N),()=>{if(se.disconnect(),U.current!==null)window.clearTimeout(U.current),U.current=null}},[e.id,e.type,e.data.mode,e.data.strictSize,e.collapsed,e.size.width,e.size.height]);let ee=e.pinned,xe=e.type==="trace",Fe=xe&&e.data.status==="running",We=e.type==="group",Te=e.data.strictSize===!0,eo=Math.max(re.value.scale,0.01),Ft=JE(eo,e.collapsed?0:e.size.height,e.size.width),Xt=We&&e.data.color?e.data.color:void 0,I={left:`${e.position.x}px`,top:`${e.position.y}px`,width:`${e.size.width}px`,height:e.collapsed?"auto":`${e.size.height}px`,zIndex:e.zIndex,"--node-chrome-scale":Ft.toFixed(3),...Xt?{"--group-color":Xt}:{}},K=ft.value&&Bx.value.has(e.id),le=["canvas-node",o?"active":"",u?"neighbor":"",p?"search-match":"",m?"search-dimmed":"",r?"selected":"",s?"context-pinned":"",a?"attention-focus-primary":"",c?"attention-focus-secondary":"",l?"attention-pulse":"",ee?"pinned":"",xe?"trace-node":"",Fe?"trace-running":"",We?"group-node":"",Te?"strict-size":"",K?"agent-mutating":""].filter(Boolean).join(" "),Y=We?(Array.isArray(e.data.children)?e.data.children:[]).filter((N)=>typeof N==="string"&&M.value.has(N)):[],[J,Q]=L(!1),te=ln.value,q=We&&te?.groupId===e.id&&te.mode==="add",ae=We&&te?.groupId===e.id&&te.mode==="remove",mt=je.value?.targetId===e.id,kt=We?[...new Set(Y.map((N)=>M.value.get(N)?.type).filter((N)=>!!N))].slice(0,4):[];if(We&&e.collapsed)return i("div",{class:`${le} group-chip`,"data-node-type":e.type,style:{...I,width:"auto",height:"auto"},onPointerDown:P,onDblClick:Z,title:"Expand group","data-testid":"group-chip",children:i("div",{class:"node-titlebar group-chip-inner",onPointerDown:T,children:[i("button",{type:"button",class:"group-chip-expand","aria-label":`Expand group ${E}`,onClick:(N)=>{N.stopPropagation(),Jo(e.id)},children:"▸"},void 0,!1,void 0,this),i("div",{class:"group-chip-text",children:[i("div",{class:"group-chip-name",children:E},void 0,!1,void 0,this),i("div",{class:"group-chip-meta",children:[kt.map((N)=>i("span",{class:"group-kind-dot",style:{background:Ka[N]},"aria-hidden":"true"},N,!1,void 0,this)),i("span",{class:"group-chip-count",children:[Y.length," node",Y.length===1?"":"s"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this);return i("div",{class:`${le}${q?" is-drop-target":""}${ae?" is-drop-source":""}${mt?" is-edge-target":""}${We&&J?" group-menu-open":""}`,"data-node-type":e.type,"data-node-id":e.id,style:I,tabIndex:o?0:-1,onKeyDown:j,onPointerDown:P,onMouseDown:(N)=>{if(N.shiftKey)N.preventDefault()},onDblClick:Z,children:[We&&i("div",{class:"node-titlebar group-edge-row",onPointerDown:T,children:[i("span",{class:"group-name-pill",children:[f?i("input",{ref:y,class:"node-title-input group-title-input",value:E,onBlur:(N)=>B(N.target.value),onKeyDown:(N)=>{if(N.key==="Enter")B(N.target.value);if(N.key==="Escape")g(!1)},onClick:(N)=>N.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"group-name",title:E,children:E},void 0,!1,void 0,this),i("span",{class:"group-count",children:Y.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"group-edge-spacer"},void 0,!1,void 0,this),i("span",{class:"group-actions",role:"toolbar","aria-label":`${E} actions`,children:[i("button",{type:"button",class:"group-action",title:"Auto-arrange children","aria-label":"Auto-arrange children",disabled:Y.length===0,onClick:(N)=>{N.stopPropagation(),Fc(e.id,Y,"grid")},children:i("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[i("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"group-action",title:"Collapse group","aria-label":"Collapse group",onClick:(N)=>{N.stopPropagation(),Jo(e.id)},children:i("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M3 10 L8 5 L13 10"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"group-action",title:"Rename · Ungroup · Pin all to context","aria-label":"Group menu","aria-expanded":J,onClick:(N)=>{N.stopPropagation(),Q((se)=>!se)},children:"⋯"},void 0,!1,void 0,this),J&&i("div",{class:"group-menu",role:"menu",onPointerDown:(N)=>N.stopPropagation(),children:[i("button",{type:"button",role:"menuitem",onClick:(N)=>{N.stopPropagation(),Q(!1),g(!0),requestAnimationFrame(()=>y.current?.focus())},children:"Rename"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",onClick:(N)=>{N.stopPropagation(),Q(!1),It(e.id),Zo(e.id)},children:"Ungroup"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",disabled:Y.length===0,onClick:(N)=>{N.stopPropagation(),Q(!1),ys(Y)},children:"Pin all to context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!We&&i("div",{class:"node-titlebar",onPointerDown:T,children:[i("span",{class:"node-type-icon","aria-hidden":"true",children:(()=>{let N=yn(e.type);return i(N,{size:Math.round(14*Ft)},void 0,!1,void 0,this)})()},void 0,!1,void 0,this),typeof e.data.axWorkStatus==="string"&&i("span",{class:`node-ax-status node-ax-status-${e.data.axWorkStatus}`,children:e.data.axWorkStatus},void 0,!1,void 0,this),f?i("input",{ref:y,class:"node-title-input",value:E,onBlur:(N)=>B(N.target.value),onKeyDown:(N)=>{if(N.key==="Enter")B(N.target.value);if(N.key==="Escape")g(!1)},onClick:(N)=>N.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"node-title",title:E,children:E},void 0,!1,void 0,this),i("div",{class:"node-controls",children:[ee&&i("span",{class:"pin-indicator",title:"Pinned",children:"⊙"},void 0,!1,void 0,this),i("button",{type:"button",class:`ctx-pin-btn${s?" ctx-pin-active":""}`,onClick:(N)=>{N.stopPropagation(),Rn(e.id)},title:s?"Remove from context":"Add to context",children:"✦"},void 0,!1,void 0,this),Os(e)&&i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),Ls(e)},title:"Open as site",children:"↗"},void 0,!1,void 0,this),Fr.has(e.type)&&i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),en(e.id)},title:"Expand (focus mode)",children:"⤢"},void 0,!1,void 0,this),i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),Jo(e.id)},title:e.collapsed?"Expand":"Collapse",children:e.collapsed?"▸":"▾"},void 0,!1,void 0,this),i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),It(e.id),In(e.id)},title:"Close",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&i("div",{ref:W,class:"node-body",children:[t,i(Ya,{node:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&i("div",{class:"node-resize-handle",onPointerDown:(N)=>_(N,e.size.width,e.size.height)},void 0,!1,void 0,this),r&&["tl","tr","bl","br"].map((N)=>i("span",{class:`node-selection-handle is-${N}`,"aria-hidden":"true"},N,!1,void 0,this)),ko.value.has(e.id)&&i("span",{class:"node-yield-pill","data-testid":"yield-pill",children:[i("span",{class:"node-yield-dot","aria-hidden":"true"},void 0,!1,void 0,this),ko.value.get(e.id)," took over — agent yielded"]},void 0,!0,void 0,this),!We&&["top","right","bottom","left"].map((N)=>i("div",{class:`node-port node-port-${N}`,onPointerDown:(se)=>{se.stopPropagation(),se.preventDefault();let Me=e.position.x+e.size.width/2,de=e.position.y+e.size.height/2,jt=e.size.width/2,zi=e.size.height/2,Zt,Sn;switch(N){case"top":Zt=Me,Sn=de-zi;break;case"bottom":Zt=Me,Sn=de+zi;break;case"left":Zt=Me-jt,Sn=de;break;case"right":Zt=Me+jt,Sn=de;break}je.value={fromId:e.id,fromX:Zt,fromY:Sn,cursorX:Zt,cursorY:Sn}}},N,!1,void 0,this))]},void 0,!0,void 0,this)}var YE={relation:"var(--c-muted)","depends-on":"var(--c-warn)",flow:"var(--c-accent)",references:"var(--c-muted)"},QE=new Set(["depends-on","flow"]);function eI(e){if(!Number.isFinite(e)||e<=0)return 1;return e<1?1/e:1}function tI(e,t){let n=`${8*t} ${4*t}`;if(e.style==="dashed")return n;if(e.style==="dotted")return`${3*t} ${3*t}`;if(e.type==="references"&&!e.style)return n;return}function Qa(e,t){let n=e.position.x+e.size.width/2,o=e.position.y+e.size.height/2,r=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=r-n,c=s-o,l=e.size.width/2,u=e.size.height/2,d=Math.abs(c/(a||0.001)),p=u/(l||0.001);if(d>p){let f=c>0?1:-1;return{x:n+u/d*(a>0?1:-1),y:o+u*f,side:f>0?"bottom":"top"}}let m=a>0?1:-1;return{x:n+l*m,y:o+d*l*(c>0?1:-1),side:m>0?"right":"left"}}function ec(e,t){switch(e.side){case"top":return{x:e.x,y:e.y-t};case"bottom":return{x:e.x,y:e.y+t};case"left":return{x:e.x-t,y:e.y};case"right":return{x:e.x+t,y:e.y}}}function nI(e,t,n,o,r,s,a,c){return{x:0.125*e+0.375*n+0.375*r+0.125*a,y:0.125*t+0.375*o+0.375*s+0.125*c}}function oI({edge:e,fromNode:t,toNode:n,focused:o,dimmed:r,selected:s,scale:a,onContextMenu:c}){let l=Qa(t,n),u=Qa(n,t),d=u.x-l.x,p=u.y-l.y,m=Math.sqrt(d*d+p*p),f=Math.min(Math.max(m*0.35,32),160),g=ec(l,f),y=ec(u,f),x=`M ${l.x} ${l.y} C ${g.x} ${g.y}, ${y.x} ${y.y}, ${u.x} ${u.y}`,h=YE[e.type],v=QE.has(e.type),b=tI(e,a),z=Math.min(a,2.2),F=e.label&&a<=3.4?nI(l.x,l.y,g.x,g.y,y.x,y.y,u.x,u.y):null,_=`edge-path-${e.id}`;return i("g",{children:[i("path",{d:x,fill:"none",stroke:"transparent","stroke-width":12*a,style:{cursor:"pointer",pointerEvents:"stroke"},onClick:(k)=>{k.stopPropagation(),un.value=e.id},onDblClick:c?(k)=>c(k,e.id):void 0},void 0,!1,void 0,this),(o||s)&&i("path",{d:x,fill:"none",stroke:h,"stroke-width":6*a,"stroke-dasharray":b,opacity:s?0.3:0.15,style:{filter:"blur(3px)"}},void 0,!1,void 0,this),i("path",{id:_,d:x,class:s?"edge-selected":void 0,fill:"none",stroke:h,"stroke-width":(s?3:o?2.5:1.5)*a,"stroke-dasharray":b,"marker-end":v?"url(#edge-arrow)":void 0,opacity:s?1:r?0.2:o?1:0.85,style:{transition:"opacity 0.2s, stroke-width 0.2s"}},void 0,!1,void 0,this),e.animated&&i("circle",{r:3*a,fill:h,opacity:"0.9",children:i("animateMotion",{dur:"2s",repeatCount:"indefinite",children:i("mpath",{href:`#${_}`},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),F&&e.label&&i("g",{transform:`translate(${F.x}, ${F.y})`,children:[i("rect",{class:"edge-label-bg",x:-(e.label.length*3.5+8)*z,y:-10*z,width:(e.label.length*7+16)*z,height:20*z,rx:4*z},void 0,!1,void 0,this),i("text",{class:"edge-label","text-anchor":"middle","dominant-baseline":"central",fill:"var(--c-text)",children:e.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Ib({nodes:e,edges:t,onEdgeContextMenu:n}){let o=e.value,r=Array.from(t.value.values()),s=ke.value,a=s!==null,c=Nn.value,l=c!==null,u=eI(re.value.scale);if(r.length===0&&!je.value)return null;let d=96,p=Array.from(o.values());if(p.length===0)return null;let m=Math.min(...p.map((v)=>v.position.x))-d,f=Math.min(...p.map((v)=>v.position.y))-d,g=Math.max(...p.map((v)=>v.position.x+v.size.width))+d,y=Math.max(...p.map((v)=>v.position.y+v.size.height))+d,x=Math.max(1,g-m),h=Math.max(1,y-f);return i("svg",{"aria-label":"Canvas connections",role:"img",viewBox:`${m} ${f} ${x} ${h}`,width:x,height:h,style:{position:"absolute",top:`${f}px`,left:`${m}px`,pointerEvents:"none",overflow:"visible","--edge-chrome-scale":u.toFixed(3),"--edge-label-scale":Math.min(u,2.2).toFixed(3)},children:[i("title",{children:"Canvas connections"},void 0,!1,void 0,this),i("defs",{children:i("marker",{id:"edge-arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerUnits:"userSpaceOnUse",markerWidth:8*Math.min(u,2.2),markerHeight:8*Math.min(u,2.2),orient:"auto-start-reverse",children:i("path",{d:"M 0 1 L 10 5 L 0 9 z",fill:"currentColor",opacity:"0.75"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r.map((v)=>{let b=vs(v.from),z=vs(v.to);if(!b||!z||b.id===z.id)return null;let F=a&&(v.from===s||v.to===s),_=l&&!(c.has(v.from)||c.has(v.to));return i(oI,{edge:v,fromNode:b,toNode:z,focused:F,dimmed:a&&!F||_,selected:un.value===v.id,scale:u,onContextMenu:n},v.id,!1,void 0,this)}),je.value&&(()=>{let v=je.value,b=vs(v.fromId),z={position:{x:v.cursorX,y:v.cursorY},size:{width:1,height:1}},F;if(b){let _=Qa(b,z),k=Qa(z,b),T=k.x-_.x,P=k.y-_.y,Z=Math.sqrt(T*T+P*P),j=Math.min(Math.max(Z*0.35,32),160),E=ec(_,j),B=ec(k,j);F=`M ${_.x} ${_.y} C ${E.x} ${E.y}, ${B.x} ${B.y}, ${k.x} ${k.y}`}else{let _=v.cursorX-v.fromX,k=v.cursorY-v.fromY,T=Math.sqrt(_*_+k*k),P=Math.min(T*0.25,80),Z=_/(T||1),j=k/(T||1);F=`M ${v.fromX} ${v.fromY} C ${v.fromX+Z*P} ${v.fromY+j*P}, ${v.cursorX-Z*P} ${v.cursorY-j*P}, ${v.cursorX} ${v.cursorY}`}return i("g",{children:[i("path",{d:F,fill:"none",stroke:"var(--c-accent)","stroke-width":6*u,opacity:"0.1",style:{filter:"blur(3px)"}},void 0,!1,void 0,this),i("path",{d:F,fill:"none",stroke:"var(--c-accent)","stroke-width":2*u,"stroke-dasharray":`${6*u} ${4*u}`,opacity:"0.8"},void 0,!1,void 0,this),i("circle",{cx:v.cursorX,cy:v.cursorY,r:5*u,fill:"var(--c-accent)",opacity:"0.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})()]},void 0,!0,void 0,this)}function rI(e){let[t,...n]=e;if(!t)return"";return n.reduce((o,r)=>`${o} L ${r.x} ${r.y}`,`M ${t.x} ${t.y}`)}function Sd({annotations:e}){if(e.length===0)return null;return i("svg",{class:"annotation-layer","aria-hidden":"true",children:e.map((t)=>{let n=t.color==="currentColor"?"var(--c-annotation)":t.color;if(t.type==="text"){let o=t.points[0];if(!o||!t.text)return null;return i("text",{x:o.x,y:o.y,fill:n,"font-size":t.width,"font-family":"var(--font)","font-weight":"700",opacity:"0.95",children:t.text},t.id,!1,void 0,this)}return i("path",{d:rI(t.points),fill:"none",stroke:n,"stroke-width":t.width,"stroke-linecap":"round","stroke-linejoin":"round",opacity:"0.9"},t.id,!1,void 0,this)})},void 0,!1,void 0,this)}var iI=0.1,sI=4,Ab=1;function zb(e){return Math.min(sI,Math.max(iI,e))}function Pb({viewport:e,onViewportChange:t,onViewportCommit:n,disabled:o=!1}){let r=R(null),s=R(!1),a=R({x:0,y:0}),c=R(0),l=R(null),u=O((h)=>{if(l.current!==null)window.clearTimeout(l.current);l.current=window.setTimeout(()=>{l.current=null,n(h)},140)},[n]);function d(h){if(h.deltaMode!==0)return h.deltaX===0;return h.deltaX===0&&Number.isInteger(h.deltaY)&&Math.abs(h.deltaY)>=50}let p=O((h)=>{if(o)return;h.preventDefault();let v=e.value;if(h.ctrlKey||h.metaKey||d(h)){let b=r.current?.getBoundingClientRect();if(!b)return;let z=h.clientX-b.left,F=h.clientY-b.top,_=-h.deltaY*0.002,k=zb(v.scale*(1+_)),T=k/v.scale,P={x:z-T*(z-v.x),y:F-T*(F-v.y),scale:k};t(P),u(P)}else{let b={x:v.x-h.deltaX*Ab,y:v.y-h.deltaY*Ab,scale:v.scale};t(b),u(b)}},[o,e,t,u]),m=O((h)=>{if(o)return;let v=r.current;if(!v)return;if(h.button===1||h.button===2)h.preventDefault();else if(Xo()){if(h.target!==v)return;h.preventDefault()}else return;s.current=!0,document.documentElement.classList.add("is-canvas-panning"),a.current={x:h.clientX,y:h.clientY},v.setPointerCapture(h.pointerId)},[o]),f=O((h)=>{if(!s.current)return;if(o)return;let v=h.clientX-a.current.x,b=h.clientY-a.current.y;a.current={x:h.clientX,y:h.clientY};let z=e.value;t({x:z.x+v,y:z.y+b,scale:z.scale})},[o,e,t]),g=O(()=>{if(s.current)n(e.value);s.current=!1,document.documentElement.classList.remove("is-canvas-panning")},[n,e]),y=O((h)=>{if(o)return;if(h.touches.length!==2){c.current=0;return}h.preventDefault();let v=h.touches[0],b=h.touches[1],z=Math.hypot(b.clientX-v.clientX,b.clientY-v.clientY),F=(v.clientX+b.clientX)/2,_=(v.clientY+b.clientY)/2;if(c.current>0){let k=e.value,T=r.current?.getBoundingClientRect();if(!T)return;let P=F-T.left,Z=_-T.top,j=z/c.current,E=zb(k.scale*j),B=E/k.scale,W={x:P-B*(P-k.x),y:Z-B*(Z-k.y),scale:E};t(W),u(W)}c.current=z},[o,e,t,u]),x=O(()=>{if(l.current!==null)window.clearTimeout(l.current),l.current=null;n(e.value),c.current=0},[n,e]);return D(()=>{let h=r.current;if(!h)return;return h.addEventListener("wheel",p,{passive:!1}),h.addEventListener("pointerdown",m),h.addEventListener("pointermove",f),h.addEventListener("pointerup",g),h.addEventListener("pointercancel",g),h.addEventListener("lostpointercapture",g),h.addEventListener("touchmove",y,{passive:!1}),h.addEventListener("touchend",x),()=>{if(l.current!==null)window.clearTimeout(l.current);h.removeEventListener("wheel",p),h.removeEventListener("pointerdown",m),h.removeEventListener("pointermove",f),h.removeEventListener("pointerup",g),h.removeEventListener("pointercancel",g),h.removeEventListener("lostpointercapture",g),h.removeEventListener("touchmove",y),h.removeEventListener("touchend",x)}},[p,m,f,g,y,x]),D(()=>()=>{document.documentElement.classList.remove("is-canvas-panning")},[]),r}function aI(e){switch(e.type){case"markdown":return i(Ns,{node:e},void 0,!1,void 0,this);case"mcp-app":return i(Hn,{node:e},void 0,!1,void 0,this);case"webpage":return i(Ea,{node:e},void 0,!1,void 0,this);case"json-render":return i(Hn,{node:e},void 0,!1,void 0,this);case"graph":return i(Hn,{node:e},void 0,!1,void 0,this);case"prompt":return i(Ia,{node:e},void 0,!1,void 0,this);case"response":return i(Aa,{node:e},void 0,!1,void 0,this);case"status":return i(Ca,{node:e},void 0,!1,void 0,this);case"context":return i(ms,{node:e},void 0,!1,void 0,this);case"ledger":return i(Ts,{node:e},void 0,!1,void 0,this);case"trace":return i(za,{node:e},void 0,!1,void 0,this);case"file":return i(Cs,{node:e},void 0,!1,void 0,this);case"diff":return i(hs,{node:e},void 0,!1,void 0,this);case"mermaid":return i(Ds,{node:e},void 0,!1,void 0,this);case"image":return i(Ta,{node:e},void 0,!1,void 0,this);case"html":return i(vi,{node:e},void 0,!1,void 0,this);case"group":return i(ix,{node:e},void 0,!1,void 0,this);default:return i("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function cI(e,t,n){let o=n.x-t.x,r=n.y-t.y,s=o*o+r*r;if(s===0)return Math.hypot(e.x-t.x,e.y-t.y);let a=Math.max(0,Math.min(1,((e.x-t.x)*o+(e.y-t.y)*r)/s));return Math.hypot(e.x-(t.x+a*o),e.y-(t.y+a*r))}function lI(e,t,n){for(let o=e.length-1;o>=0;o--){let r=e[o];if(!r)continue;let s=n+r.width;if(t.x<r.bounds.x-s||t.x>r.bounds.x+r.bounds.width+s||t.y<r.bounds.y-s||t.y>r.bounds.y+r.bounds.height+s)continue;if(r.type==="text")return r;for(let a=1;a<r.points.length;a++){let c=r.points[a-1],l=r.points[a];if(c&&l&&cI(t,c,l)<=n+r.width/2)return r}}return null}var kd="currentColor",Nb=4,Rb=24,uI=14,$b={width:520,height:420};function dI(e){let t=e.trim();if(!t||/\s/.test(t))return null;let n=/^[a-z][a-z0-9+.-]*:/i.test(t)?t:`https://${t}`;try{let o=new URL(n);if(o.protocol!=="http:"&&o.protocol!=="https:")return null;return o.toString()}catch{return null}}function Td(e){let t=e.trim();if(!t)return[];let n=t.includes(`
314
- `)?t.split(/\r?\n/):t.split(/\s+/),o=new Set,r=[];for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let c=dI(a);if(!c||o.has(c))continue;o.add(c),r.push(c)}return r}function pI(e){let t=Td(e.getData("text/uri-list"));if(t.length>0)return t;return Td(e.getData("text/plain"))}function fI(e){if(!e)return!1;return e.types.includes("text/uri-list")||e.types.includes("text/plain")}function Cd(e){if(!(e instanceof HTMLElement))return!1;return Boolean(e.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}function mI(e,t,n=new Set){let o=[],r=0;for(let s of e){if(n.has(s.id))continue;if(t&&s.id===t)continue;if(s.type==="group")o.splice(r++,0,s);else o.push(s)}return o}function Mb({onNodeContextMenu:e,onEdgeContextMenu:t,onCanvasContextMenu:n,annotationMode:o=!1,annotationTool:r=null}){let s=re.value,a=R(!1),c=R(null),l=R(!1),u=R([]),[d,p]=L(null),[m,f]=L(null),[g,y]=L(null),x=R(null),[h,v]=L(!1),b=R(0),z=R(null),F=R(null);D(()=>{let I=null,K=Kt(()=>{re.value;let le=F.current;if(!le)return;if(le.style.willChange="transform",I)clearTimeout(I);I=setTimeout(()=>{le.style.willChange="auto"},180)});return()=>{if(I)clearTimeout(I);K()}},[]);let _=Pb({viewport:re,disabled:o,onViewportChange:(I)=>{if(a.current||o)return;Qo(),If(I)},onViewportCommit:(I)=>{if(a.current||o)return;Qo(),zf(I)}}),k=O((I)=>{x.current=I,y(I)},[]),T=O(async(I,K,le)=>{if(I.length===0)return;let{width:Y,height:J}=$b,Q=24,te=Math.ceil(Math.sqrt(I.length)),q=Math.ceil(I.length/te),ae=te*Y+Math.max(0,te-1)*Q,mt=q*J+Math.max(0,q-1)*Q;for(let kt=0;kt<I.length;kt++){let N=kt%te,se=Math.floor(kt/te),Me=K-ae/2+N*(Y+Q),de=le-mt/2+se*(J+Q);await Bt({type:"webpage",content:I[kt],x:Me,y:de,width:Y,height:J})}},[]),P=O((I)=>{let K=_.current;if(!K)return;if(r==="eraser"){if((I.target instanceof Element?I.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;I.preventDefault(),I.stopPropagation();let q=K.getBoundingClientRect(),ae=re.value,mt={x:(I.clientX-q.left-ae.x)/ae.scale,y:(I.clientY-q.top-ae.y)/ae.scale},kt=lI(Array.from(Vo.value.values()),mt,uI/ae.scale);if(kt)Ef(kt.id);return}if(r==="text"){if((I.target instanceof Element?I.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;I.preventDefault(),I.stopPropagation(),ke.value=null,ht();let q=K.getBoundingClientRect(),ae=re.value;k({x:(I.clientX-q.left-ae.x)/ae.scale,y:(I.clientY-q.top-ae.y)/ae.scale,value:""});return}if(r==="pen"){if((I.target instanceof Element?I.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;I.preventDefault(),I.stopPropagation(),ke.value=null,ht(),l.current=!0;let q=K.getBoundingClientRect(),ae=re.value,mt={x:(I.clientX-q.left-ae.x)/ae.scale,y:(I.clientY-q.top-ae.y)/ae.scale};u.current=[mt],f({id:"draft-annotation",type:"freehand",points:[mt],bounds:{x:0,y:0,width:0,height:0},color:kd,width:Nb,createdAt:""}),K.setPointerCapture(I.pointerId);return}if(I.target!==K)return;if(Xo()||I.button===1||I.button===2){if(!I.shiftKey&&!z.current)ke.value=null,ht();return}I.preventDefault(),I.stopPropagation(),a.current=!0;let le=K.getBoundingClientRect(),Y=I.clientX-le.left,J=I.clientY-le.top,Q={startX:Y,startY:J,currentX:Y,currentY:J};z.current=Q,p(Q),K.setPointerCapture(I.pointerId)},[r,_]);D(()=>Kt(()=>{let I=re.value,K=c.current,le=_.current;if(!K||!le)return;let Y=le.getBoundingClientRect();qa({x:(K.x-Y.left-I.x)/I.scale,y:(K.y-Y.top-I.y)/I.scale})}),[]);let Z=O((I)=>{{let Y=_.current;if(Y){c.current={x:I.clientX,y:I.clientY};let J=Y.getBoundingClientRect(),Q=re.value;qa({x:(I.clientX-J.left-Q.x)/Q.scale,y:(I.clientY-J.top-Q.y)/Q.scale})}}if(l.current){let Y=_.current;if(!Y)return;let J=Y.getBoundingClientRect(),Q=re.value,te={x:(I.clientX-J.left-Q.x)/Q.scale,y:(I.clientY-J.top-Q.y)/Q.scale},q=u.current.at(-1);if(q&&Math.hypot(te.x-q.x,te.y-q.y)<2)return;u.current=[...u.current,te],f((ae)=>ae?{...ae,points:u.current}:null);return}if(!a.current||!z.current)return;let K=_.current?.getBoundingClientRect();if(!K)return;let le={...z.current,currentX:I.clientX-K.left,currentY:I.clientY-K.top};z.current=le,p(le)},[_]),j=O((I)=>{if(l.current){l.current=!1;let te=u.current;if(u.current=[],f(null),te.length>=2)nl({points:te,color:kd,width:Nb});let q=_.current;if(q?.hasPointerCapture(I.pointerId))q.releasePointerCapture(I.pointerId);return}let K=z.current;if(!a.current||!K)return;a.current=!1,z.current=null;let le=Math.min(K.startX,K.currentX),Y=Math.max(K.startX,K.currentX),J=Math.min(K.startY,K.currentY),Q=Math.max(K.startY,K.currentY);if(Y-le<=5&&Q-J<=5)ke.value=null,ht();if(Y-le>5||Q-J>5){let te=re.value,q=(le-te.x)/te.scale,ae=(Y-te.x)/te.scale,mt=(J-te.y)/te.scale,kt=(Q-te.y)/te.scale,N=[];for(let se of M.value.values()){let Me=se.position.x,de=se.position.y;if(Me+se.size.width>q&&Me<ae&&de+se.size.height>mt&&de<kt)N.push(se.id)}if(N.length>0)vf(N)}p(null)},[]);D(()=>{if(o)return;if(!l.current&&!m&&!g)return;l.current=!1,u.current=[],f(null),k(null)},[o,m,k,g]);let E=O(()=>{let I=x.current;if(!I)return;let K=I.value.trim();if(k(null),!K)return;let le={x:I.x,y:I.y};nl({type:"text",points:[le],color:kd,width:Rb,text:K})},[k]);D(()=>{if(r!=="text"&&g)k(null)},[r,k,g]),D(()=>{let I=(J,Q,te)=>{let q=null;for(let ae of M.value.values()){if(ae.id===te||ae.type==="group")continue;if(J>=ae.position.x&&J<=ae.position.x+ae.size.width&&Q>=ae.position.y&&Q<=ae.position.y+ae.size.height)q=ae.id}return q};function K(J){if(!je.value)return;let Q=_.current;if(!Q)return;let te=Q.getBoundingClientRect(),q=re.value,ae=(J.clientX-te.left-q.x)/q.scale,mt=(J.clientY-te.top-q.y)/q.scale;je.value={...je.value,cursorX:ae,cursorY:mt,targetId:I(ae,mt,je.value.fromId)}}function le(){let J=je.value;if(!J)return;je.value=null;let Q=J.targetId;if(!Q)return;if(J.withLabel){Yt("Edge label","label text").then((te)=>{so(J.fromId,Q,"relation",te??void 0)});return}so(J.fromId,Q,"relation",void 0)}function Y(J){let Q=je.value;if(!Q)return;if(J.key==="Escape")J.preventDefault(),je.value=null;else if(J.key==="l"||J.key==="L")J.preventDefault(),je.value={...Q,withLabel:!Q.withLabel}}return document.addEventListener("pointermove",K),document.addEventListener("pointerup",le),document.addEventListener("keydown",Y),()=>{document.removeEventListener("pointermove",K),document.removeEventListener("pointerup",le),document.removeEventListener("keydown",Y)}},[_]);let B=O((I)=>{if(o)return;let K=_.current;if(!K||I.target!==K||!n)return;let le=K.getBoundingClientRect(),Y=re.value,J=(I.clientX-le.left-Y.x)/Y.scale,Q=(I.clientY-le.top-Y.y)/Y.scale;n(I,J,Q)},[o,_,n]),W=O((I)=>{I.preventDefault()},[]),H=O((I)=>{if(Cd(I.target instanceof Element?I.target:null))return;I.preventDefault()},[]),U=O((I)=>{if(I.preventDefault(),b.current++,I.dataTransfer?.types.includes("Files")||fI(I.dataTransfer))v(!0)},[]),ee=O((I)=>{if(I.preventDefault(),I.dataTransfer)I.dataTransfer.dropEffect="copy"},[]),xe=O((I)=>{if(I.preventDefault(),b.current--,b.current<=0)b.current=0,v(!1)},[]),Fe=O(async(I)=>{I.preventDefault(),v(!1),b.current=0;let K=_.current;if(!K||!I.dataTransfer)return;let le=K.getBoundingClientRect(),Y=re.value,J=(I.clientX-le.left-Y.x)/Y.scale,Q=(I.clientY-le.top-Y.y)/Y.scale,te=Array.from(I.dataTransfer.files);if(te.length===0){let q=pI(I.dataTransfer);await T(q,J,Q);return}await Pa(te,J,Q)},[_,T]);D(()=>{let I=async(K)=>{if(K.defaultPrevented)return;if(Cd(K.target instanceof Element?K.target:null))return;if(Cd(document.activeElement))return;let le=K.clipboardData?.getData("text/plain")??"",Y=Td(le);if(Y.length===0)return;let J=_.current;if(!J)return;K.preventDefault();let Q=J.getBoundingClientRect(),te=re.value,q=(Q.width/2-te.x)/te.scale,ae=(Q.height/2-te.y)/te.scale;await T(Y,q,ae)};return document.addEventListener("paste",I),()=>{document.removeEventListener("paste",I)}},[_,T]);let We=mI(M.value.values(),Be.value,new Set(Qc.value.keys())),Te=ln.value,eo=Te?M.value.get(Te.groupId):void 0,Ft=Te?M.value.get(Te.nodeId):void 0,Xt=null;if(d){let I=Math.min(d.startX,d.currentX),K=Math.min(d.startY,d.currentY),le=Math.abs(d.currentX-d.startX),Y=Math.abs(d.currentY-d.startY);Xt={position:"absolute",left:`${I}px`,top:`${K}px`,width:`${le}px`,height:`${Y}px`,pointerEvents:"none"}}return i("div",{class:`canvas-viewport${Xo()?" pan-mode":""}`,ref:_,tabIndex:0,onPointerDown:P,onPointerMove:Z,onPointerLeave:()=>{c.current=null,qa(null)},onPointerUp:j,onContextMenu:W,onDblClick:B,onDragStart:H,onDragEnter:U,onDragOver:ee,onDragLeave:xe,onDrop:Fe,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden",cursor:r==="eraser"?"cell":r==="text"?"text":o||je.value||a.current||yt.value==="connect"?"crosshair":Xo()?"grab":"default"},children:[i("div",{ref:F,class:"canvas-world",style:{transform:`matrix(${s.scale}, 0, 0, ${s.scale}, ${s.x}, ${s.y})`,transformOrigin:"0 0",position:"absolute",top:0,left:0},children:[i(fx,{},void 0,!1,void 0,this),i(db,{},void 0,!1,void 0,this),i(Mx,{},void 0,!1,void 0,this),i(Ux,{},void 0,!1,void 0,this),i(Yx,{},void 0,!1,void 0,this),i(Ib,{nodes:M,edges:Re,onEdgeContextMenu:t},void 0,!1,void 0,this),je.value&&i("div",{class:"edge-hint-pill","data-testid":"edge-hint",style:{left:`${je.value.cursorX+14}px`,top:`${je.value.cursorY+14}px`},children:[i("span",{class:"edge-hint-main",children:je.value.targetId?"release to connect":"drag onto a node"},void 0,!1,void 0,this),i("span",{class:"edge-hint-keys",children:["esc cancels · L labels",je.value.withLabel?" · label on":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Te&&eo&&Ft&&i("div",{class:"drop-pill","data-testid":"drop-pill",style:{left:`${Ft.position.x}px`,top:`${Ft.position.y+Ft.size.height+10}px`},children:[i("span",{class:"drop-pill-text",children:Te.mode==="add"?`release to add to ${String(eo.data.title??"group")}`:`release to remove from ${String(eo.data.title??"group")}`},void 0,!1,void 0,this),i("span",{class:"drop-pill-hint",children:Te.mode==="add"?"esc keeps it out":"esc keeps it in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Sd,{annotations:Array.from(Vo.value.values())},void 0,!1,void 0,this),m&&m.points.length>=2&&i(Sd,{annotations:[m]},void 0,!1,void 0,this),We.map((I)=>i(Eb,{node:I,onContextMenu:e,children:aI(I)},I.id,!1,void 0,this)),Eo.value&&i("svg",{class:"snap-guides-svg",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"visible"},children:Eo.value.map((I,K)=>I.axis==="x"?i("line",{x1:I.pos,y1:I.from-20,x2:I.pos,y2:I.to+20,class:"snap-guide-line"},K,!1,void 0,this):i("line",{x1:I.from-20,y1:I.pos,x2:I.to+20,y2:I.pos,class:"snap-guide-line"},K,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&i("div",{class:`annotation-capture-layer${r==="eraser"?" erasing":""}${r==="text"?" text":""}`,"aria-hidden":"true"},void 0,!1,void 0,this),g&&i("input",{class:"annotation-text-input",value:g.value,autoFocus:!0,style:{left:`${g.x*s.scale+s.x}px`,top:`${g.y*s.scale+s.y}px`,fontSize:`${Rb*s.scale}px`},onInput:(I)=>k({...g,value:I.target.value}),onBlur:E,onPointerDown:(I)=>I.stopPropagation(),onKeyDown:(I)=>{if(I.key==="Enter")I.preventDefault(),E();if(I.key==="Escape")I.preventDefault(),k(null)}},void 0,!1,void 0,this),Xt&&i("div",{class:"lasso-rect",style:Xt},void 0,!1,void 0,this),h&&i("div",{class:"drop-zone-overlay",children:i("div",{class:"drop-zone-indicator",children:[i("div",{class:"drop-zone-icon",children:"+"},void 0,!1,void 0,this),i("div",{class:"drop-zone-label",children:"Drop files or URLs to add to canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ob(){let e=[...Ee.value],t=M.value,[n,o]=L(""),[r,s]=L(!1),a=Zx.value,[c,l]=L(null),u=a.length>=2,d=!u&&a.length===1&&a[0].steerable?a[0]:null,p=u?c?a.find((g)=>g.value===c&&g.steerable)??null:null:d,m=p?.value??null,f=async()=>{let g=n.trim();if(!g||r)return;s(!0);let y=await cb(g,m);if(s(!1),y)o("")};return i("div",{class:"command-bar","data-testid":"command-bar",children:[e.length>0&&i("div",{class:"command-bar-chips","aria-label":"Pinned context",children:[e.map((g)=>{let y=t.get(g),x=typeof y?.data.title==="string"&&y.data.title.trim()?y.data.title:y?.type??g;return i("span",{class:"command-bar-chip","data-node-id":g,children:[i("span",{class:"command-bar-chip-glyph","aria-hidden":"true",children:"✦"},void 0,!1,void 0,this),i("span",{class:"command-bar-chip-label",title:x,children:x},void 0,!1,void 0,this),i("button",{type:"button",class:"command-bar-chip-unpin","aria-label":`Unpin ${x}`,title:"Remove from context",onClick:()=>Rn(g),children:"×"},void 0,!1,void 0,this)]},g,!0,void 0,this)}),i("span",{class:"command-bar-chips-note",children:"in agent context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"command-bar-composer",children:[i(br,{size:15,class:"command-bar-icon"},void 0,!1,void 0,this),u&&i("select",{class:"command-bar-target","aria-label":"Steer which agent",title:"Connected agents — steering reaches all of them unless you address one",value:m??"",onChange:(g)=>l(g.target.value||null),children:[i("option",{value:"",children:"All agents"},void 0,!1,void 0,this),a.map((g)=>{let y=g.pendingSteers&&g.pendingSteers>0?` · ${g.pendingSteers} queued`:"",x=g.polling?" · polling":"";return i("option",{value:g.value,disabled:!g.steerable,children:g.attached?`${g.label}${x}${y}`:g.steerable?`${g.label} · writer${x}${y}`:`${g.label} · no inbox`},g.value,!1,void 0,this)})]},void 0,!0,void 0,this),i("input",{class:"command-bar-input",type:"text",value:n,placeholder:`Steer ${p?.label??"the agent"}, or ${Ze("K")} to search the board…`,"aria-label":"Steer the agent",disabled:r,onInput:(g)=>o(g.target.value),onKeyDown:(g)=>{if(g.key==="Enter")g.preventDefault(),f()}},void 0,!1,void 0,this),i("button",{type:"button",class:"command-bar-send",disabled:r||!n.trim(),onClick:()=>void f(),children:r?"Sending…":"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Ed=Oe(()=>{if(Et.value==="disconnected")return"reconnecting";if(Et.value==="connected"&&!Vt.value&&co.value>1)return"resyncing";return null});function Lb(){let e=Ed.value;if(!e)return null;if(e==="reconnecting"){let t=lo.value,n=uo.value;return i("div",{class:"connection-banner is-reconnecting",role:"status","data-testid":"connection-banner",children:[i("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"↻"},void 0,!1,void 0,this),i("span",{class:"connection-banner-text",children:[i("b",{children:"Reconnecting…"},void 0,!1,void 0,this)," live updates are paused; edits still save, the board may be stale until the stream returns."]},void 0,!0,void 0,this),i("span",{class:"connection-banner-meta",children:[t>0?`retry ${t}`:"retrying",n>0?` · ${Math.max(1,Math.round(n/1000))}s`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}return i("div",{class:"connection-banner is-resyncing",role:"status","data-testid":"connection-banner",children:[i("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"⟳"},void 0,!1,void 0,this),i("span",{class:"connection-banner-text",children:[i("b",{children:"Resyncing from snapshot"},void 0,!1,void 0,this)," — the event cursor went stale; the board reloads without losing local edits."]},void 0,!0,void 0,this),i("span",{class:"connection-banner-progress","aria-hidden":"true",children:i("span",{class:"connection-banner-progress-fill"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var hI={markdown:{width:520,height:360},group:{width:600,height:400},html:{width:720,height:640},image:{width:720,height:520},file:{width:720,height:600},webpage:{width:520,height:420}};async function Pt(e){if(e.x!==void 0&&e.y!==void 0)return Bt(e);let t=hI[e.type]??{width:360,height:200},n=e.width??t.width,o=e.height??t.height,r=Fo(),s=re.value,a=await Bt({...e,width:n,height:o,x:Math.round((r.x-s.x)/s.scale-n/2),y:Math.round((r.y-s.y)/s.scale-o/2)});if(a.ok&&a.id)tt(a.id);return a}var tc=!1,Db=!1,Io=null,Tr=null;function Id(){return tc}function nc(){tc=!1,Db=!0,Fb()}function Fb(){if(Io&&Tr)Io.removeEventListener("change",Tr);Io=null,Tr=null}function gI(){if(typeof window>"u"||!window.location)return null;let e=new URLSearchParams(window.location.search).get("theme");if(e==="auto")return"auto";return Gr(e)?e:null}function jb(e){if(Db)return;let t=gI();if(!t)return;if(Fb(),tc=!0,t!=="auto"){e(t);return}Io=window.matchMedia("(prefers-color-scheme: light)"),Tr=()=>{if(tc&&Io)e(Io.matches?"light":"dark")},Tr(),Io.addEventListener("change",Tr)}var vI='a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';function Er(e,t,n={}){D(()=>{if(!t)return;let o=e.current;if(!o)return;let r=document.activeElement,s=n.restoreTo,a=()=>Array.from(o.querySelectorAll(vI)),c=n.initial?.current??a()[0];if(c&&!o.contains(document.activeElement))c.focus();let l=(u)=>{if(u.key!=="Tab")return;let d=a();if(d.length===0)return;let p=d[0],m=d[d.length-1],f=document.activeElement;if(u.shiftKey&&(f===p||!o.contains(f)))u.preventDefault(),m.focus();else if(!u.shiftKey&&f===m)u.preventDefault(),p.focus()};return o.addEventListener("keydown",l),()=>{if(o.removeEventListener("keydown",l),s)requestAnimationFrame(()=>s()?.focus());else if(r&&document.contains(r)&&r!==document.body)r.focus()}},[e,t,n.initial,n.restoreTo])}function yI(e,t){let n=e.toLowerCase(),o=t.toLowerCase(),r=[],s=0,a=0,c=-1;for(let l=0;l<o.length&&s<n.length;l++)if(o[l]===n[s]){if(r.push(l),a+=c===l-1?10:1,l===0||o[l-1]===" "||o[l-1]==="-"||o[l-1]==="_")a+=5;c=l,s++}return{match:s===n.length,score:a,indices:r}}function xI(e,t){if(t.length===0)return e;let n=[],o=0;for(let r of t){if(r>o)n.push(e.slice(o,r));n.push(i("mark",{children:e[r]},r,!1,void 0,this)),o=r+1}if(o<e.length)n.push(e.slice(o));return n}var Ad={md:"markdown",app:"mcp-app",web:"webpage",ui:"json-render",chart:"graph",ctx:"context",log:"ledger"};function bI(e){let t=e.toLowerCase().trim();if(t.startsWith("type:")){let n=t.slice(5).trim(),r=Object.keys(it).find((a)=>a.startsWith(n));if(r)return{typeFilter:r,remaining:""};let s=Ad[n];if(s)return{typeFilter:s,remaining:""}}if(Ad[t])return{typeFilter:Ad[t],remaining:""};return{typeFilter:null,remaining:e}}function Zb({onClose:e,onToggleMinimap:t}){let[n,o]=L(""),[r,s]=L(0),a=R(null),c=R(null),l=R(null);Er(l,!0,{initial:a}),D(()=>{setTimeout(()=>a.current?.focus(),30)},[]);let u=O(()=>{let h=[];for(let b of M.value.values()){let z=b.data.title||it[b.type],F=b.data.content||b.data.path||"",_=b.type==="group"&&Array.isArray(b.data.children)?b.data.children.length:0;h.push({id:`node:${b.id}`,kind:"node",label:z,description:b.type==="group"?`group · ${_} node${_===1?"":"s"}`:F.length>60?`${it[b.type].toLowerCase()} · ${F.slice(0,60)}…`:F?`${it[b.type].toLowerCase()} · ${F}`:it[b.type].toLowerCase(),icon:yn(b.type),nodeType:b.type,action:()=>{tt(b.id),e()}})}let v=[{label:"New markdown note",shortcut:"M",icon:Bn,iconTone:"accent",action:()=>{Pt({type:"markdown",title:"New note",width:520,height:360}),e()}},...ft.value?[]:[{label:"Start agent session",icon:br,iconTone:"purple",action:()=>{Xn(),e()}}],{label:"Fit view",shortcut:"F",icon:$a,iconTone:"muted",action:()=>{er(wt().width,wt().height),e()}},{label:"Auto-arrange (grid)",icon:_o,iconTone:"muted",action:()=>{_s(),e()}},{label:"Auto-arrange (graph-aware)",icon:_o,iconTone:"muted",action:()=>{Ss(),e()}},{label:"Toggle minimap",icon:Ma,iconTone:"muted",action:()=>{t(),e()}},{label:"Toggle theme (dark/light)",icon:Oa,iconTone:"muted",action:()=>{let b=Xe.value==="dark"?"light":"dark";nc(),document.documentElement.setAttribute("data-theme",b),hr(),Xe.value=b,rs(b),e()}}];for(let b of v)h.push({id:`action:${b.label}`,kind:"action",label:b.label,...b.shortcut?{shortcut:b.shortcut}:{},icon:b.icon,...b.iconTone?{iconTone:b.iconTone}:{},action:b.action});return h},[e,t]),{typeFilter:d,remaining:p}=bI(n),m=u(),f;if(!n.trim())f=m.map((h)=>({...h,score:0,indices:[]}));else{f=[];for(let h of m){if(d){if(h.kind!=="node"||h.nodeType!==d)continue;if(!p){f.push({...h,score:0,indices:[]});continue}}let v=yI(p||n,h.label);if(v.match)f.push({...h,score:v.score,indices:v.indices})}f.sort((h,v)=>v.score-h.score)}f=[...f.filter((h)=>h.kind==="action"),...f.filter((h)=>h.kind==="node")];let g=f.findIndex((h)=>h.kind==="node");D(()=>{if(!n.trim()){Nn.value=null;return}let h=new Set;for(let v of f)if(v.kind==="node")h.add(v.id.slice(5));Nn.value=h.size>0?h:null},[n,f]),D(()=>()=>{Nn.value=null},[]);let y=Math.min(r,Math.max(0,f.length-1)),x=O((h)=>{if(h.key==="ArrowDown")h.preventDefault(),s((v)=>Math.min(v+1,f.length-1));else if(h.key==="ArrowUp")h.preventDefault(),s((v)=>Math.max(v-1,0));else if(h.key==="Enter"){if(h.preventDefault(),f[y])f[y].action()}else if(h.key==="Escape")h.preventDefault(),h.stopPropagation(),e()},[f,y,e]);return D(()=>{let h=c.current;if(!h)return;h.children[y]?.scrollIntoView({block:"nearest"})},[y]),D(()=>{s(0)},[n]),i("div",{class:"command-palette-backdrop",onMouseDown:e,children:i("div",{ref:l,class:"command-palette",role:"dialog","aria-modal":"true","aria-label":"Search and commands",onMouseDown:(h)=>h.stopPropagation(),children:[i("div",{class:"command-palette-search",children:[i("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("input",{ref:a,type:"text",class:"command-palette-input",value:n,onInput:(h)=>o(h.target.value),onKeyDown:x,placeholder:"Search nodes, run actions, jump to…","aria-label":"Search nodes, run actions, jump to"},void 0,!1,void 0,this),i("kbd",{class:"command-palette-esc",children:"esc"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"command-palette-results",ref:c,children:[f.length===0&&i("div",{class:"command-palette-empty",children:"No matching nodes or actions"},void 0,!1,void 0,this),f.map((h,v)=>{let b=h.icon,z=v===0&&h.kind==="action"?"Actions":v===g?"Jump to":null;return i("div",{class:"command-palette-row",children:[z&&i("div",{class:"command-palette-group",children:z},void 0,!1,void 0,this),i("button",{type:"button",class:`command-palette-item${v===y?" selected":""}`,onMouseEnter:()=>s(v),onClick:()=>h.action(),children:[i("span",{class:`command-palette-icon tone-${h.iconTone??"kind"}`,"aria-hidden":"true",children:i(b,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"command-palette-label",children:[h.indices.length>0?xI(h.label,h.indices):h.label,h.description&&i("span",{class:"command-palette-desc",children:[" — ",h.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h.shortcut&&i("kbd",{class:"command-palette-kbd",children:h.shortcut},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},h.id,!0,void 0,this)})]},void 0,!0,void 0,this),i("div",{class:"command-palette-hint",children:[i("span",{children:"↑↓ navigate"},void 0,!1,void 0,this),i("span",{children:"↵ open"},void 0,!1,void 0,this),i("span",{children:"esc close"},void 0,!1,void 0,this),i("span",{children:"type: filter"},void 0,!1,void 0,this),i("span",{class:"command-palette-hint-spacer"},void 0,!1,void 0,this),i("span",{children:Ze("K")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Hb(){let[e,t]=L(null),n=O((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"node",x:a.clientX,y:a.clientY,nodeId:c})},[]),o=O((a,c,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"canvas",x:a.clientX,y:a.clientY,canvasX:c,canvasY:l})},[]),r=O((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"edge",x:a.clientX,y:a.clientY,edgeId:c})},[]),s=O(()=>t(null),[]);return D(()=>{if(!e)return;let a=()=>t(null),c=(l)=>{if(l.key==="Escape")t(null)};return document.addEventListener("click",a),document.addEventListener("keydown",c),()=>{document.removeEventListener("click",a),document.removeEventListener("keydown",c)}},[e]),{menu:e,openNodeMenu:n,openCanvasMenu:o,openEdgeMenu:r,closeMenu:s}}var wI="#4bbcFF",_I=[{label:"Blue",value:"#3b82f6"},{label:"Green",value:"#22c55e"},{label:"Yellow",value:"#eab308"},{label:"Red",value:"#ef4444"},{label:"Gray",value:"#6b7280"},{label:"Purple",value:"#a855f7"}];function Bb({menu:e,onClose:t}){let n;if(e.kind==="node"){let c=M.value.get(e.nodeId);if(!c)return null;n=II(c)}else if(e.kind==="edge"){let c=e.edgeId,l=Re.value.get(c);n=[{label:l?.label?`Edit label “${l.label.slice(0,18)}${l.label.length>18?"…":""}”`:"Add label…",action:()=>{Yt("Edge label (empty clears it)","label text",{initial:l?.label??"",allowEmpty:!0,confirm:"Save"}).then((u)=>{if(u===null)return;cs(c,{label:u})})}},{separator:!0},...["flow","depends-on","relation","references"].map((u)=>({label:`${l?.type===u?"✓":" "} ${u}`,action:()=>void cs(c,{type:u})})),{separator:!0},...["solid","dashed","dotted"].map((u)=>({label:`${(l?.style??"solid")===u?"✓":" "} ${u}`,action:()=>void cs(c,{style:u})})),{separator:!0},{label:"Delete edge",danger:!0,action:()=>void ls(c)}]}else n=EI(e.canvasX,e.canvasY);let o=new Map,r=n.some((c)=>c.render)?n.length*32+168:n.length*32+8,s=Math.min(e.x,Math.max(12,window.innerWidth-240)),a=Math.min(e.y,Math.max(12,window.innerHeight-r));return i("div",{class:"context-menu",style:{position:"fixed",left:`${s}px`,top:`${a}px`,zIndex:1e4},onPointerDown:(c)=>c.stopPropagation(),onClick:(c)=>c.stopPropagation(),children:n.map((c)=>{let l=c.separator?"separator":c.render?"custom":`${c.label??"item"}:${c.shortcut??""}`,u=(o.get(l)??0)+1;o.set(l,u);let d=`${l}:${u}`;if(c.separator)return i("div",{class:"context-menu-separator"},d,!1,void 0,this);if(c.render)return i("div",{class:"context-menu-custom",children:c.render(t)},d,!1,void 0,this);return i("button",{type:"button",class:`context-menu-item${c.danger?" is-danger":""}`,onClick:()=>{c.action?.(),t()},children:[i("span",{class:"context-menu-label",children:c.label},void 0,!1,void 0,this),c.shortcut&&i("span",{class:"context-menu-shortcut",children:c.shortcut},void 0,!1,void 0,this)]},d,!0,void 0,this)})},void 0,!1,void 0,this)}function SI(e){return(typeof e.data.path==="string"?e.data.path.trim():"")||null}function oc(e){let t=e.trim().toLowerCase(),n=t.match(/^#([0-9a-f]{3})$/);if(n){let[o,r,s]=n[1].split("");return`#${o}${o}${r}${r}${s}${s}`}return t}function Ub(e){if(typeof e.data.color!=="string"||!e.data.color.trim())return null;return oc(e.data.color)}function kI(e){let t=Ub(e);return t&&/^#[0-9a-f]{6}$/.test(t)?t:oc(wI)}function zd(e,t){let n=t?oc(t):null;st(e.id,{data:{...e.data,color:n}}),rt(e.id,{data:{color:n}})}function CI(e,t){let n=Ub(e);return i("div",{class:"context-menu-section",children:[i("div",{class:"context-menu-section-header",children:[i("span",{class:"context-menu-section-label",children:"Group color"},void 0,!1,void 0,this),i("button",{type:"button",class:"context-menu-reset",onClick:()=>{zd(e,null),t()},children:"Theme default"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"context-menu-color-grid",children:_I.map((o)=>{let r=oc(o.value);return i("button",{type:"button",class:`context-menu-color-swatch${n===r?" active":""}`,"aria-label":`Set group color to ${o.label}`,title:o.label,style:{"--swatch-color":o.value},onClick:()=>{zd(e,o.value),t()},children:[i("span",{class:"context-menu-color-dot",style:{"--swatch-color":o.value}},void 0,!1,void 0,this),i("span",{children:o.label},void 0,!1,void 0,this)]},o.value,!0,void 0,this)})},void 0,!1,void 0,this),i("label",{class:"context-menu-color-custom",children:[i("span",{children:"Custom"},void 0,!1,void 0,this),i("input",{type:"color",class:"context-menu-color-input","aria-label":"Custom group color",value:kI(e),onClick:(o)=>o.stopPropagation(),onInput:(o)=>{zd(e,o.currentTarget.value),t()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Nd(e,t,n,o){return{x:e-n/2,y:t-o/2}}function TI(e,t){return e.trim().replace(/[?#].*$/,"").split("/").filter(Boolean).at(-1)||t}async function Pd(e){let t=await Yt(e.promptLabel,e.placeholder??"");if(!t)return;let n=t.trim();if(!n)return;let o=Nd(e.canvasX,e.canvasY,e.width,e.height);if(!(await Bt({type:e.type,...e.type!=="webpage"?{title:TI(n,e.titleFallback)}:{},content:n,x:o.x,y:o.y,width:e.width,height:e.height})).ok)console.error(`[canvas-menu] ${e.errorMessage}`)}function EI(e,t){return[{label:"New note",action:()=>{let r=Nd(e,t,520,360);Bt({type:"markdown",title:"New note",x:r.x,y:r.y,width:520,height:360})}},{label:"Open webpage...",action:()=>{Pd({promptLabel:"Webpage URL:",type:"webpage",canvasX:e,canvasY:t,width:520,height:420,placeholder:"https://example.com",titleFallback:"Webpage",errorMessage:"Could not create webpage node. Enter a valid http(s) URL."})}},{label:"Open file...",action:()=>{Pd({promptLabel:"Workspace path or absolute file path:",type:"file",canvasX:e,canvasY:t,width:720,height:500,placeholder:"src/server/server.ts",titleFallback:"File",errorMessage:"Could not create file node. Check the path and try again."})}},{label:"Open image...",action:()=>{Pd({promptLabel:"Image path, URL, or data URI:",type:"image",canvasX:e,canvasY:t,width:480,height:360,placeholder:"artifacts/architecture.png",titleFallback:"Image",errorMessage:"Could not create image node. Check the image source and try again."})}},{separator:!0},{label:"New group",action:()=>{let r=Nd(e,t,600,400);jo({title:"Group",x:r.x,y:r.y,width:600,height:400})}}]}function II(e){let t=[],n=SI(e);if(t.push({label:"Focus",action:()=>tt(e.id)}),t.push({label:"Rename…",action:()=>{Yt("Rename node","Node title",{initial:typeof e.data.title==="string"?e.data.title:"",confirm:"Save"}).then((l)=>{if(!l?.trim())return;rt(e.id,{title:l.trim()})})}}),Fr.has(e.type))t.push({label:"Expand",shortcut:"⤢",action:()=>en(e.id)});t.push({label:e.collapsed?"Expand":"Collapse",action:()=>Jo(e.id)});let o=Ee.value.has(e.id);t.push({label:o?"Unpin from context":"Pin as context",action:()=>Rn(e.id)}),t.push({label:e.pinned?"Unlock position":"Lock position (no auto-arrange)",action:()=>{let l=!e.pinned;st(e.id,{pinned:l}),rt(e.id,{pinned:l}),Ye()}});let r=gs.value;if(r&&r.from!==e.id){let l=M.value.get(r.from),u=l?(l.data.title||l.id).slice(0,20):r.from;t.push({label:`Connect from "${u}"`,action:()=>{so(r.from,e.id,"relation"),gs.value=null}})}t.push({label:r?"Connect from here (replace)":"Connect from here",action:()=>{gs.value={from:e.id}}});let s=Array.from(Re.value.values()).filter((l)=>l.from===e.id||l.to===e.id).length;if(s>0)t.push({label:`${s} edge${s!==1?"s":""} connected`});if(t.push({separator:!0}),(e.type==="markdown"||e.type==="file"||e.type==="image")&&n)t.push({label:"Open in browser",action:()=>{window.open(`/artifact?path=${encodeURIComponent(n)}`,"_blank","noopener")}}),t.push({label:"Copy path",action:()=>{navigator.clipboard.writeText(n)}});if(e.type==="mcp-app"||e.type==="json-render"||e.type==="graph")if(e.data.chartConfig){let l=e.data.chartConfig.title||"chart";t.push({label:"Copy chart data",action:()=>{navigator.clipboard.writeText(JSON.stringify(e.data.chartConfig,null,2))}})}else{let l=e.data.url;if(t.push({label:"Open in browser",action:()=>{if(l)window.open(l,"_blank")}}),t.push({label:"Focus in TUI",action:()=>Op("mcp-app-focus",{url:l})}),e.type==="json-render"||e.type==="graph")t.push({label:"Copy spec",action:()=>{navigator.clipboard.writeText(JSON.stringify(e.data.spec??e.data.graphConfig??{},null,2))}})}if(e.type==="webpage"){let l=typeof e.data.url==="string"?e.data.url:"";t.push({label:"Refresh webpage",action:()=>{is(e.id)}}),t.push({label:"Open in browser",action:()=>{if(l)window.open(l,"_blank","noopener")}}),t.push({label:"Copy URL",action:()=>{if(l)navigator.clipboard.writeText(l)}})}if(e.type==="group"){let l=e.data.children??[];if(t.push({separator:!0}),t.push({render:(u)=>CI(e,u)}),l.length>0)t.push({label:`Ungroup (${l.length} node${l.length!==1?"s":""})`,action:()=>{It(e.id),Zo(e.id)}})}let a=typeof e.data.parentGroup==="string"?e.data.parentGroup:null,c=a?M.value.get(a):void 0;if(c&&c.type==="group"){let l=typeof c.data.title==="string"&&c.data.title?c.data.title:"frame",u=Array.isArray(c.data.children)?c.data.children.filter((d)=>d!==e.id):[];t.push({label:`Remove from “${l}”`,action:()=>{as(c.id,u)}})}return t.push({separator:!0}),t.push({label:e.type==="group"?"Delete frame (children stay)":"Delete",danger:!0,action:()=>{It(e.id),In(e.id)}}),t}function Wb(){let e=Ee.value.size;if(e===0||Jt.value)return null;return i("div",{class:"context-pin-bar",children:[i("span",{class:"context-pin-bar-count",children:["✦"," ",e," node",e!==1?"s":""," in context"]},void 0,!0,void 0,this),i("button",{type:"button",class:"context-pin-bar-btn context-pin-bar-clear",onClick:kf,title:"Clear all context pins",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ki(e,t){console.error(`[tool-rail] ${e} failed`,t)}function wn(e){let t={image:{message:"Image URL (https://… or data:image/…)",placeholder:"https://example.com/diagram.png"},file:{message:"Workspace file path",placeholder:"src/server/server.ts"},webpage:{message:"Page URL",placeholder:"https://example.com"}};Yt(t[e].message,t[e].placeholder).then((n)=>{if(!n)return;Pt({type:e,content:n}).catch((o)=>ki(`create ${e}`,o))})}function ot({label:e,shortcut:t,detail:n,ariaLabel:o,active:r,menuOpen:s,onClick:a,btnRef:c,children:l}){let[u,d]=L(null),p=(g)=>{let y=g.currentTarget.getBoundingClientRect();d({left:y.right+10,top:y.top+y.height/2})},m=()=>d(null),f=o??(t?`${e} (${t})`:n?`${e} (${n})`:e);return i(ve,{children:[i("button",{ref:c,type:"button",class:`rail-btn${r?" active":""}`,"aria-label":f,"aria-pressed":r===void 0?void 0:r,onClick:(g)=>{m(),a(g)},onPointerEnter:p,onPointerLeave:m,onFocus:p,onBlur:m,children:l},void 0,!1,void 0,this),u&&!s&&i("span",{class:"toolbar-tooltip rail-tooltip",role:"tooltip","data-testid":"rail-tooltip",style:{left:`${u.left}px`,top:`${u.top}px`},children:[i("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),(t||n)&&i("span",{class:"toolbar-tooltip-meta",children:[t&&i("kbd",{class:"toolbar-tooltip-shortcut",children:t},void 0,!1,void 0,this),n&&i("span",{children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function qb({minimapVisible:e,onToggleMinimap:t,snapshotOpen:n,onToggleSnapshot:o,snapshotBtnRef:r,onOpenPalette:s,onOpenShortcuts:a,annotationTool:c,onSetAnnotationTool:l}){let u=yt.value,d=Go.value,p=Array.from(M.value.values()).filter((k)=>k.type==="trace").length,m=Re.value.size,[f,g]=L(null),[y,x]=L(null),h=R(null),v=(k)=>(T)=>{if(f===k){g(null);return}let P=T.currentTarget.getBoundingClientRect();x({top:P.top,bottom:P.bottom,right:P.right}),g(k)},b=(k)=>y?k?{position:"fixed",left:`${y.right+8}px`,bottom:`${window.innerHeight-y.bottom}px`,top:"auto",right:"auto"}:{position:"fixed",left:`${y.right+8}px`,top:`${y.top}px`,right:"auto"}:void 0;D(()=>{if(!f)return;let k=(P)=>{if(h.current&&P.target instanceof Node&&!h.current.contains(P.target))g(null)},T=(P)=>{if(P.key==="Escape")g(null)};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",T),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",T)}},[f]);let z=(k)=>{nc(),document.documentElement.setAttribute("data-theme",k),hr(),Xe.value=k,rs(k),g(null)},F=Tl(Xe.value),_=(k,T={})=>{fetch(`/api/workbench/intent?_ts=${Date.now()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:k,payload:T})}).catch((P)=>ki("sendIntent",P))};return i("div",{class:"tool-rail",ref:h,role:"toolbar","aria-label":"Canvas tools","aria-orientation":"vertical",children:[i("span",{class:"rail-brand",title:"PMX Canvas","aria-label":"PMX Canvas",children:i(Ex,{size:22},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"rail-divider"},void 0,!1,void 0,this),i(ot,{label:"Select",shortcut:"V",active:u==="select",onClick:()=>yt.value="select",children:i(Ix,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Pan",shortcut:"Space",active:u==="pan",onClick:()=>yt.value="pan",children:i(Ax,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Connect",shortcut:"C",active:u==="connect",onClick:()=>yt.value="connect",children:i("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("circle",{cx:"4",cy:"4",r:"2"},void 0,!1,void 0,this),i("circle",{cx:"12",cy:"12",r:"2"},void 0,!1,void 0,this),i("path",{d:"M5.5 5.5 C 8 8, 8 8, 10.5 10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("div",{class:"rail-divider"},void 0,!1,void 0,this),i(ot,{label:"Markdown note",shortcut:"M",onClick:()=>void Pt({type:"markdown",title:"New note",width:520,height:360}).catch((k)=>ki("create markdown",k)),children:i(Bn,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Image",shortcut:"I",onClick:()=>wn("image"),children:i(rd,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"File",shortcut:"Shift+F",onClick:()=>wn("file"),children:i(Ra,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Webpage",shortcut:"W",onClick:()=>wn("webpage"),children:i(xr,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"HTML surface",shortcut:"H",onClick:()=>void Pt({type:"html",title:"HTML surface"}).catch((k)=>ki("create html",k)),children:i(zx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Group",shortcut:"G",onClick:()=>void Pt({type:"group",title:"Group"}).catch((k)=>ki("create group",k)),children:i(id,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"toolbar-menu-anchor",children:[i(ot,{label:"Annotate",shortcut:"A",detail:"Draw · Text note · Eraser",active:c!==null,menuOpen:f==="annotate",onClick:v("annotate"),children:c==="eraser"?i(nd,{},void 0,!1,void 0,this):c==="text"?i(od,{},void 0,!1,void 0,this):i(td,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),f==="annotate"&&i("div",{class:"toolbar-menu",style:b(!1),role:"menu","aria-label":"Annotate",children:[i("button",{type:"button",class:`toolbar-menu-item${c==="pen"?" active":""}`,onClick:()=>{l(c==="pen"?null:"pen"),g(null)},children:[i(td,{},void 0,!1,void 0,this),i("span",{children:c==="pen"?"Stop annotating":"Draw (A)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:`toolbar-menu-item${c==="text"?" active":""}`,onClick:()=>{l(c==="text"?null:"text"),g(null)},children:[i(od,{},void 0,!1,void 0,this),i("span",{children:c==="text"?"Stop text notes":"Text note"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:`toolbar-menu-item${c==="eraser"?" active":""}`,onClick:()=>{l(c==="eraser"?null:"eraser"),g(null)},children:[i(nd,{},void 0,!1,void 0,this),i("span",{children:c==="eraser"?"Stop erasing":"Eraser"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"rail-spacer"},void 0,!1,void 0,this),i(ot,{label:"Search & commands",shortcut:Ze("K"),onClick:s,children:i(Cx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Arrange",detail:m>0?"graph-aware":"grid",onClick:()=>m>0?Ss():_s(),children:i(_o,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:d?"Disable trace":"Enable trace",active:d,onClick:()=>_("trace-toggle",{enabled:!d}),children:i(Sx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),(d||p>0)&&i(ot,{label:"Clear trace",onClick:()=>_("trace-clear"),children:i(kx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:e?"Hide minimap":"Show minimap",active:e,onClick:t,children:i(Ma,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(ot,{label:"Snapshots",active:n,onClick:o,btnRef:r,children:i(_x,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"toolbar-menu-anchor",children:[i(ot,{label:"Theme",detail:ir[F].label,menuOpen:f==="theme",ariaLabel:"Choose theme",active:f==="theme",onClick:v("theme"),children:sr(F)==="dark"?i(wx,{},void 0,!1,void 0,this):i(Oa,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),f==="theme"&&i("div",{class:"toolbar-menu",style:b(!0),role:"menu","aria-label":"Theme",children:Cl.map((k)=>i("button",{type:"button",role:"menuitemradio","aria-checked":F===k,class:`toolbar-menu-item${F===k?" active":""}`,onClick:()=>z(k),children:[i("span",{class:"theme-swatch",style:{background:ir[k].swatchBg},children:i("span",{class:"theme-swatch-dot",style:{background:ir[k].swatchAccent}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{children:ir[k].label},void 0,!1,void 0,this),F===k&&i("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},k,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(ot,{label:"Shortcuts",shortcut:"?",onClick:a,children:i(Tx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Vb({onOpenPalette:e}){let t=R(null),n=()=>{Pt({type:"markdown",title:"New note",width:520,height:360}).catch(()=>{})},o=async(r)=>{if(!r||r.length===0)return;let s=Fo(),a=re.value;await Pa(Array.from(r),(s.x-a.x)/a.scale,(s.y-a.y)/a.scale)};return i("div",{class:"empty-state","data-testid":"empty-state",children:[i("svg",{class:"empty-state-mark",width:"52",height:"52",viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",children:[i("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7"},void 0,!1,void 0,this),i("rect",{x:"20",y:"20",width:"24",height:"24",rx:"4","stroke-dasharray":"4 4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{children:[i("div",{class:"empty-state-title",children:"Nothing on this board yet"},void 0,!1,void 0,this),i("div",{class:"empty-state-sub",children:"Drop files anywhere, paste a link, or start from a note."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"empty-state-grid",children:[i("button",{type:"button",class:"empty-state-action",onClick:n,children:[i(Bn,{size:16,class:"tone-accent"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-label",children:"New markdown note"},void 0,!1,void 0,this),i("kbd",{children:"M"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-action",onClick:()=>t.current?.click(),children:[i("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round",class:"tone-warn","aria-hidden":"true",children:[i("path",{d:"M8 10 V2 M8 2 L5 5 M8 2 L11 5"},void 0,!1,void 0,this),i("path",{d:"M2 10 V13 H14 V10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"empty-state-action-label",children:"Drop files"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-hint",children:"or pick"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-action",onClick:()=>wn("webpage"),children:[i(xr,{size:16,class:"tone-ok"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-label",children:"Paste a link"},void 0,!1,void 0,this),i("kbd",{children:Ze("V")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-action is-agent",onClick:()=>void Xn(),children:[i(br,{size:16,class:"tone-purple"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-label",children:"Start agent session"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-hint",onClick:e,children:["? shortcuts · ",Ze("K")," palette"]},void 0,!0,void 0,this),i("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:(r)=>{let s=r.currentTarget;o(s.files).finally(()=>{s.value=""})}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Rd({presence:e,size:t=18}){return i("span",{class:"writer-avatar",style:{background:Da(e.sessionId),width:`${t}px`,height:`${t}px`},"aria-hidden":"true",children:jx(e.label)},void 0,!1,void 0,this)}function Gb(){let e=pd.value;if(ft.value||e.length===0)return null;let t=e.reduce((r,s)=>r+s.opCount,0),n=e.length===1?e[0].label:`${e.length} writers`,o=So.value;return i("button",{type:"button",class:"external-indicator","data-testid":"external-indicator","aria-expanded":o,title:`${e.length} external writer${e.length===1?"":"s"} on this board — click for activity`,onClick:()=>{So.value=!o},children:[i("span",{class:"external-indicator-avatars",children:e.slice(0,3).map((r)=>i(Rd,{presence:r},r.sessionId,!1,void 0,this))},void 0,!1,void 0,this),i("span",{class:"external-indicator-label",children:n},void 0,!1,void 0,this),i("span",{class:"external-indicator-ops hud-collapsible-text",children:[t," op",t===1?"":"s"]},void 0,!0,void 0,this),i("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function AI(e){if(e==="node.add"||e==="jsonrender.add"||e==="graph.add"||e==="group.create")return{glyph:"+",tone:"ok"};if(e==="node.remove"||e==="edge.remove"||e==="canvas.clear")return{glyph:"×",tone:"danger"};if(e==="edge.add")return{glyph:"⟶",tone:"accent"};if(e.startsWith("ax."))return{glyph:"◆",tone:"purple"};return{glyph:"✎",tone:"accent"}}function zI(e){return e.reduce((t,n)=>n.lastSeenAt>t?n.lastSeenAt:t,"")}function PI(){return[...Ve.value.values()].filter((e)=>!e.auto&&e.phase==="forming")}function Xb(){let e=So.value,t=pd.value,n=bn(e?1e4:0);if(D(()=>{if(!e)return;let c=(l)=>{if(l.key!=="Escape")return;if(wr.value)wr.value=!1;else So.value=!1};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]),!e||ft.value||t.length===0)return null;let o=dd.value,r=PI().filter((c)=>!o||(c.source??"")===o),s=qn.value.filter((c)=>!o||c.sessionId===o),a=(c,l)=>i("button",{type:"button",class:`activity-filter${o===c?" is-active":""}`,style:c?{"--writer":Da(c)}:void 0,"aria-pressed":o===c,onClick:()=>{dd.value=c},children:l},void 0,!1,void 0,this);return i("div",{class:"activity-feed","data-testid":"activity-feed",role:"dialog","aria-label":"External activity",children:[i("div",{class:"activity-feed-head",children:[i("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"activity-feed-titles",children:[i("div",{class:"activity-feed-title",children:["External activity — ",t.length," writer",t.length===1?"":"s"]},void 0,!0,void 0,this),i("div",{class:"activity-feed-sub",children:[t.reduce((c,l)=>c+l.opCount,0)," writes · last"," ",Fa(zI(t),n)," · no session attached"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"activity-feed-close","aria-label":"Close activity feed",onClick:()=>{So.value=!1},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"activity-filters",children:[a(null,"All"),t.map((c)=>a(c.sessionId,c.label))]},void 0,!0,void 0,this),i("div",{class:"activity-rows",children:[r.map((c)=>i("div",{class:"activity-row is-pending","data-testid":"activity-proposal",children:[i("span",{class:"activity-glyph tone-purple","aria-hidden":"true",children:"▢"},void 0,!1,void 0,this),i("div",{class:"activity-main",children:[i("div",{class:"activity-text",children:["Proposing: ",i("b",{children:c.label?.trim()||`${c.kind} intent`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"activity-meta",children:[c.reason?.trim()||"Intent signalled — a real veto window before the mutation",c.source?` · ${c.source}`:""]},void 0,!0,void 0,this),i("div",{class:"activity-actions",children:[i("button",{type:"button",class:"activity-veto",onClick:()=>{io(c).then((l)=>{if(l)xi(c.id)})},children:"Veto"},void 0,!1,void 0,this),i("span",{class:"activity-hint",children:"or hover ghost + Esc"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"activity-age",children:"now"},void 0,!1,void 0,this)]},c.id,!0,void 0,this)),s.length===0&&r.length===0&&i("div",{class:"activity-empty",children:"No writes yet."},void 0,!1,void 0,this),s.map((c)=>{let{glyph:l,tone:u}=AI(c.op);return i("div",{class:"activity-row","data-testid":"activity-row","data-op":c.op,children:[i("span",{class:`activity-glyph tone-${u}`,"aria-hidden":"true",children:l},void 0,!1,void 0,this),i("div",{class:"activity-main",children:[i("div",{class:"activity-text",children:c.summary},void 0,!1,void 0,this),i("div",{class:"activity-writer",style:{color:Da(c.sessionId)},children:c.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"activity-age",children:Fa(c.at,n)},void 0,!1,void 0,this)]},c.id,!0,void 0,this)})]},void 0,!0,void 0,this),i("div",{class:"activity-feed-foot",children:[i("span",{class:"activity-feed-note",children:"All writes ghost first · Esc vetoes"},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-link",onClick:()=>{wr.value=!0},children:"Writers"},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-link is-accent",onClick:()=>{So.value=!1,Xn()},children:"Start session ↗"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function NI(){let e=[];if(Vn.value)e.push("scoped");if(Co.value.length>0)e.push("gated");return e.length>0?e.join(" + "):"open"}function Kb(){let e=wr.value,t=bn(e?1e4:0),n=R(null);if(Er(n,e),!e)return null;let o=pt.value.filter((a)=>a.attached),r=pt.value.filter((a)=>!a.attached),s=()=>{wr.value=!1};return i(ve,{children:[i("div",{class:"writers-scrim",onClick:s,"aria-hidden":"true"},void 0,!1,void 0,this),i("div",{ref:n,class:"writers-sheet","data-testid":"writers-sheet",role:"dialog","aria-modal":"true","aria-label":"Connected writers",children:[i("div",{class:"writers-head",children:[i("span",{class:"writers-title",children:"Connected writers"},void 0,!1,void 0,this),i("span",{class:"writers-board",children:dn.value.slice(0,12)},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-close","aria-label":"Close writers",onClick:s,children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"writers-body",children:[i("div",{class:"writers-section",children:"Agent sessions"},void 0,!1,void 0,this),o.length===0&&i("div",{class:"writers-empty",children:"None attached — start one from the top bar."},void 0,!1,void 0,this),o.map((a)=>i("div",{class:"writers-row",children:[i(Rd,{presence:a,size:20},void 0,!1,void 0,this),i("span",{class:"writers-name",children:a.label},void 0,!1,void 0,this),i("span",{class:"writers-config",children:NI()},void 0,!1,void 0,this)]},a.sessionId,!0,void 0,this)),i("div",{class:"writers-section",children:"External writers · MCP"},void 0,!1,void 0,this),r.length===0&&i("div",{class:"writers-empty",children:"No external writers right now."},void 0,!1,void 0,this),r.map((a)=>i("div",{class:"writers-row",children:[i(Rd,{presence:a,size:20},void 0,!1,void 0,this),i("span",{class:"writers-name is-mono",children:a.label},void 0,!1,void 0,this),i("span",{class:"writers-meta",children:[a.source!==a.label?`${a.source} · `:"","wrote"," ",Fa(a.lastSeenAt,t)," ago"]},void 0,!0,void 0,this)]},a.sessionId,!0,void 0,this))]},void 0,!0,void 0,this),i("div",{class:"writers-foot",children:[i("span",{class:"writers-note",children:"Local-first: any process on this machine can connect and write. Every write ghosts first — veto is the control, not permissions."},void 0,!1,void 0,this),i("button",{type:"button",class:"writers-done",onClick:s,children:"Done"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Jb(e,t){switch(e.type){case"markdown":return i(Ns,{node:e,expanded:t},void 0,!1,void 0,this);case"mcp-app":return i(Hn,{node:e,expanded:t},void 0,!1,void 0,this);case"webpage":return i(Ea,{node:e,expanded:t},void 0,!1,void 0,this);case"json-render":return i(Hn,{node:e,expanded:t},void 0,!1,void 0,this);case"graph":return i(Hn,{node:e,expanded:t},void 0,!1,void 0,this);case"prompt":return i(Ia,{node:e},void 0,!1,void 0,this);case"response":return i(Aa,{node:e,expanded:t},void 0,!1,void 0,this);case"status":return i(Ca,{node:e},void 0,!1,void 0,this);case"context":return i(ms,{node:e,expanded:t},void 0,!1,void 0,this);case"ledger":return i(Ts,{node:e},void 0,!1,void 0,this);case"trace":return i(za,{node:e},void 0,!1,void 0,this);case"file":return i(Cs,{node:e,expanded:t},void 0,!1,void 0,this);case"diff":return i(hs,{node:e},void 0,!1,void 0,this);case"mermaid":return i(Ds,{node:e,expanded:t},void 0,!1,void 0,this);case"image":return i(Ta,{node:e,expanded:t},void 0,!1,void 0,this);case"html":return i(vi,{node:e,expanded:t},void 0,!1,void 0,this);default:return i("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function Yb(e){switch(e.type){case"markdown":return e.data.content||"";case"diff":return e.data.content||"";case"mermaid":return e.data.content||"";case"file":return e.data.fileContent||"";case"webpage":return e.data.content||"";case"html":return e.data.html||e.data.content||"";case"json-render":case"graph":return JSON.stringify(e.data.spec??e.data.graphConfig??{},null,2);default:return""}}function RI(e){if(!e)return 0;return e.split(/\s+/).filter(Boolean).length}function $I(e,t){return e!==null&&typeof e==="object"&&e.source===Mt&&e.type==="presentation-exit"&&e.token===t}function MI(e){return e==="ArrowRight"||e==="PageDown"||e===" "||e==="ArrowLeft"||e==="PageUp"||e==="Home"||e==="End"}function Qb(e){return e instanceof HTMLElement&&Boolean(e.closest(".html-presentation-exit"))}function ew(){let e=Be.value,t=e?M.value.get(e):void 0,[n,o]=L(!1),[r,s]=L(!1),[a,c]=L(""),l=R(null),u=R(null),d=O(()=>{s(!1),po()},[]),p=O(()=>{c(`presentation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`),s(!0)},[]),m=O((H)=>{document.querySelector(".html-presentation-overlay iframe.html-node-frame-presentation")?.contentWindow?.postMessage({source:Mt,token:a,...H},"*")},[a]),f=O(()=>{s(!1)},[]),g=O((H)=>{if(H.key==="Escape"){H.preventDefault(),H.stopPropagation(),s(!1);return}if(H.key==="Tab"&&!Qb(H.target)){H.preventDefault(),H.stopPropagation(),u.current?.focus();return}if((H.key===" "||H.key==="Enter")&&Qb(H.target))return;if(!MI(H.key))return;H.preventDefault(),H.stopPropagation(),m({type:"presentation-key",key:H.key})},[m]),y=O((H)=>{if(H.target.classList.contains("expanded-overlay-backdrop"))po()},[]),x=O(()=>{if(!t)return;let H=Yb(t);if(!H)return;navigator.clipboard.writeText(H).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},[t]),h=O(()=>{if(!e)return;Rn(e)},[e]);D(()=>{s(!1)},[e]),Bi(()=>{if(!r)return;let H=()=>{let xe=l.current;if(!xe||xe.contains(document.activeElement))return;xe.focus()},U=[0,50,150].map((xe)=>window.setTimeout(H,xe)),ee=(xe)=>{if(!$I(xe.data,a))return;s(!1)};return document.addEventListener("keydown",g,!0),window.addEventListener("message",ee),()=>{U.forEach((xe)=>{window.clearTimeout(xe)}),document.removeEventListener("keydown",g,!0),window.removeEventListener("message",ee)}},[g,a,r]);let v=R(null),b=O(()=>e?document.querySelector(`.canvas-node[data-node-id="${CSS.escape(e)}"]`):null,[e]);if(Er(v,t!==void 0,{restoreTo:b}),!t)return null;let z=t.data.title||t.data.path?.split("/").pop()||it[t.type],F=Yb(t),_=RI(F),k=e?Ee.value.has(e):!1,T=F.length>0,P=Qt.value===e,Z=t.type==="mcp-app"||t.type==="webpage"||t.type==="json-render"||t.type==="graph",j=sx(t),E=yn(t.type),B=t.data.provenance&&typeof t.data.provenance==="object"?t.data.provenance:null,W=B?[B.sourceKind,B.sourceUri,B.syncedAt?`synced ${B.syncedAt.slice(11,16)}`:null].filter((H)=>typeof H==="string"&&H.length>0).join(" · "):null;return i("div",{class:"expanded-overlay-backdrop",onPointerDown:y,style:{pointerEvents:P?"none":"auto"},children:i("div",{ref:v,class:`expanded-overlay-panel${k?" is-pinned":""}`,role:"dialog","aria-modal":"true","aria-label":z,"data-testid":"expanded-node",children:[i("div",{class:"expanded-header",children:[i("span",{class:"expanded-kind-icon","aria-hidden":"true",children:i(E,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"expanded-title",children:z},void 0,!1,void 0,this),i("span",{class:"expanded-kind-pill",children:it[t.type]},void 0,!1,void 0,this),i("button",{type:"button",class:`expanded-pin${k?" is-on":""}`,onClick:h,title:k?"In agent context — click to unpin":"Pin as agent context","aria-pressed":k,children:"✦"},void 0,!1,void 0,this),i("span",{class:"expanded-spacer"},void 0,!1,void 0,this),i("div",{class:"expanded-actions",children:[T&&i("button",{type:"button",class:"expanded-action-btn",onClick:x,title:"Copy content to clipboard",children:n?"Copied!":"Copy"},void 0,!1,void 0,this),Os(t)&&i("button",{type:"button",class:"expanded-action-btn",onClick:()=>void Ls(t),title:"Open as a full-page site in the system browser",children:"Open in tab ↗"},void 0,!1,void 0,this),j&&i("button",{type:"button",class:"expanded-action-btn expanded-action-primary",onClick:p,title:"Present this HTML node fullscreen",children:"Present"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"expanded-close",onClick:d,title:"Close (Esc)","aria-label":"Close",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:`expanded-body${Z?" is-embedded":""}`,children:Z?i("div",{style:{flex:1,minHeight:0,display:"flex"},children:Jb(t,!0)},void 0,!1,void 0,this):Jb(t,!0)},void 0,!1,void 0,this),i("div",{style:{"--ax-dock-bleed":"0px","--ax-dock-pad":"16px"},children:i(Ya,{node:t},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"expanded-footer",children:[i("span",{class:"expanded-footer-meta",children:[W,_>0?`${_.toLocaleString()} word${_!==1?"s":""}`:null].filter(Boolean).join(" · ")||it[t.type].toLowerCase()},void 0,!1,void 0,this),i("span",{class:"expanded-spacer"},void 0,!1,void 0,this),i("span",{class:`expanded-footer-hint${P?" is-saving":""}`,children:P?"Saving edits…":"esc or click outside to close"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j&&r&&i("div",{ref:l,class:"html-presentation-overlay",role:"dialog","aria-modal":"true","aria-label":`Present ${z}`,tabIndex:-1,onKeyDownCapture:g,children:[i("button",{ref:u,type:"button",class:"html-presentation-exit",onClick:f,title:"Exit presentation (Esc)","aria-label":"Exit presentation",children:"Exit presentation"},void 0,!1,void 0,this),i("div",{class:"html-presentation-stage",children:i(vi,{node:t,expanded:!0,presentation:!0,presentationExitToken:a},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var nw=168,ow=112,rc=20;function tw(e,t,n,o){let r=Array.from(e.values()),s=0,a=0,c=1000,l=800;if(r.length>0){s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let x of r)s=Math.min(s,x.position.x),a=Math.min(a,x.position.y),c=Math.max(c,x.position.x+x.size.width),l=Math.max(l,x.position.y+x.size.height)}let u=-t.x/t.scale,d=-t.y/t.scale,p=u+n/t.scale,m=d+o/t.scale,f={minX:Math.min(s,u)-rc,minY:Math.min(a,d)-rc,maxX:Math.max(c,p)+rc,maxY:Math.max(l,m)+rc},g=f.maxX-f.minX||1,y=f.maxY-f.minY||1;return{bounds:f,scale:Math.min(nw/g,ow/y)}}function rw({viewport:e,nodes:t,onNavigate:n,containerWidth:o,containerHeight:r}){let s=R(null),a=R(!1),c=t.value,l=e.value,u=tw(c,l,o,r),{bounds:d,scale:p}=u,m=(_)=>(_-d.minX)*p,f=(_)=>(_-d.minY)*p,g=O((_)=>{let k=s.current;if(!k)return;let T=k.getBoundingClientRect(),P=(_.clientX-T.left)/T.width*nw,Z=(_.clientY-T.top)/T.height*ow,j=tw(t.value,e.value,o,r),E=e.value,B=o/E.scale,W=r/E.scale,H=P/j.scale+j.bounds.minX,U=Z/j.scale+j.bounds.minY;n(-(H-B/2)*E.scale,-(U-W/2)*E.scale)},[t,e,o,r,n]),y=O((_)=>{_.stopPropagation(),_.preventDefault(),a.current=!0,g(_);let k=(P)=>{if(a.current)g(P)},T=()=>{a.current=!1,document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",T)};document.addEventListener("pointermove",k),document.addEventListener("pointerup",T)},[g]),x=ye.value,h=Vn.value,v=h?Va(h.nodeIds.map((_)=>c.get(_)).filter((_)=>_!==void 0),h.padding):null,b=pt.value.map((_)=>({id:_.sessionId,phase:_.phase,worker:_.parentAgentId!=null,external:!_.attached,at:ja(_,(k)=>c.get(k))})).filter((_)=>_.at!==null),z=-l.x/l.scale,F=-l.y/l.scale;return i("div",{ref:s,class:"minimap","data-testid":"minimap",title:"Click to jump · drag the frame to pan",onPointerDown:y,children:[Array.from(c.values()).map((_)=>{let k=_.type==="group";return i("span",{class:`minimap-node${k?" is-group":""}${x.has(_.id)?" is-selected":""}`,"data-kind":_.type,style:{left:`${m(_.position.x)}px`,top:`${f(_.position.y)}px`,width:`${Math.max(k?6:4,_.size.width*p)}px`,height:`${Math.max(k?5:3,_.size.height*p)}px`,"--kind":Ka[_.type]}},_.id,!1,void 0,this)}),v&&i("span",{class:"minimap-fence",style:{left:`${m(v.x)}px`,top:`${f(v.y)}px`,width:`${v.width*p}px`,height:`${v.height*p}px`}},void 0,!1,void 0,this),b.map((_)=>i("span",{class:`minimap-presence phase-${_.phase}${_.worker?" is-worker":""}${_.external?" is-external":""}`,style:{left:`${m(_.at.x)-4}px`,top:`${f(_.at.y)-4}px`,"--identity-color":`hsl(${Wn(_.id)} 65% 62%)`}},_.id,!1,void 0,this)),i("span",{class:"minimap-frame",style:{left:`${m(z)}px`,top:`${f(F)}px`,width:`${o/l.scale*p}px`,height:`${r/l.scale*p}px`}},void 0,!1,void 0,this),i("span",{class:"minimap-zoom",children:[Math.round(l.scale*100),"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Je({label:e,shortcut:t,body:n,align:o="center",side:r="down",tapToOpen:s=!1,children:a}){return i("span",{class:`toolbar-tooltip-anchor toolbar-tooltip-anchor-${o}${r==="up"?" toolbar-tooltip-anchor-up":""}${s?" toolbar-tooltip-anchor-tap":""}`,tabIndex:s?-1:void 0,children:[a,i("span",{class:"toolbar-tooltip",role:"tooltip",children:[i("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),n&&i("span",{class:"toolbar-tooltip-body",children:n},void 0,!1,void 0,this),t&&i("span",{class:"toolbar-tooltip-meta",children:i("kbd",{class:"toolbar-tooltip-shortcut",children:t},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function iw(){let e=ye.value.size,t=O(()=>{let c=Array.from(ye.value);if(c.length===0)return;ys(c),ht()},[]),n=O(()=>{let c=Array.from(ye.value);if(c.length===0)return;jo({title:"Group",childIds:c}),ht()},[]),o=O(()=>{let c=Array.from(ye.value);for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++)so(c[l],c[u],"relation");ht()},[]),r=O(()=>{let c=Array.from(ye.value);for(let l of c)It(l),In(l);ht()},[]);if(e===0)return null;let s=e>=2,a=!ft.value&&Ee.value.size>0&&!Jt.value;return i("div",{class:`selection-bar${a?" is-above-pin-bar":""}`,role:"toolbar","aria-label":"Selection",children:[i("span",{class:"selection-bar-count",children:[e," node",e!==1?"s":""," selected"]},void 0,!0,void 0,this),s&&i(ve,{children:[i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Align left",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align left",onClick:()=>el("left"),children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("line",{x1:"2.5",y1:"2",x2:"2.5",y2:"14"},void 0,!1,void 0,this),i("rect",{x:"5",y:"3.5",width:"8",height:"3.5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"5",y:"9",width:"5",height:"3.5",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Align top",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align top",onClick:()=>el("top"),children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("line",{x1:"2",y1:"2.5",x2:"14",y2:"2.5"},void 0,!1,void 0,this),i("rect",{x:"3.5",y:"5",width:"3.5",height:"8",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9",y:"5",width:"3.5",height:"5",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Distribute horizontally",body:"Evens the gaps. A selection that cannot fit flows into a clean row instead of overlapping.",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Distribute",disabled:e<3,onClick:()=>_f(),children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[i("rect",{x:"1.5",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"6.25",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"11",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Auto-arrange selection",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Auto-arrange",onClick:()=>Sf(),children:i(_o,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Group the selection",shortcut:"G",side:"up",children:i("button",{type:"button",class:"selection-bar-action",onClick:n,children:[i("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-dasharray":"3 2.5","aria-hidden":"true",children:i("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"2"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"Group"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Connect every pair",side:"up",children:i("button",{type:"button",class:"selection-bar-action",onClick:o,children:"Connect"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Je,{label:"Pin to agent context",side:"up",children:i("button",{type:"button",class:"selection-bar-action is-pin",onClick:t,children:[i("span",{"aria-hidden":"true",children:"✦"},void 0,!1,void 0,this),"Pin as context"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Delete selection",side:"up",children:i("button",{type:"button",class:"selection-bar-icon is-danger","aria-label":"Delete selection",onClick:r,children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("path",{d:"M2.5 4 H13.5"},void 0,!1,void 0,this),i("path",{d:"M5.5 4 V2.5 H10.5 V4"},void 0,!1,void 0,this),i("path",{d:"M4 4 L4.8 13.5 H11.2 L12 4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Clear selection",shortcut:"Esc",side:"up",children:i("button",{type:"button",class:"selection-bar-icon",onClick:ht,"aria-label":"Clear selection",children:"×"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ic(e,t=Date.now()){if(!e.expiresAt)return null;let n=Date.parse(e.expiresAt);if(!Number.isFinite(n))return null;return Math.max(0,n-t)}function sc(e){let t=Math.max(0,Math.ceil(e/1000)),n=Math.floor(t/60),o=t%60;return`${n}:${String(o).padStart(2,"0")}`}var OI={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"vetoed"},LI={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"cancelled"},sw=[{id:"all",label:"All",hint:"Everything below in one feed, newest first"},{id:"update",label:"Updates",hint:"Board edits agents made — nodes, edges, pins, work items"},{id:"steer",label:"Steer",hint:"Instructions sent to agents — by you from the composer, or agent-to-agent"},{id:"assistant",label:"Assistant",hint:"Messages agents posted for you to read"},{id:"event",label:"Events",hint:"Run telemetry — tool runs, approvals, failures, policy notes"},{id:"evidence",label:"Evidence",hint:"Proof agents recorded — test results, artifacts, links"}],aw=Object.fromEntries(sw.map((e)=>[e.id,e.hint])),DI={policy:"warn",prompt:"accent","assistant-message":"muted","tool-start":"accent","tool-result":"ok",failure:"danger",approval:"warn",steering:"purple",command:"accent",note:"muted",evidence:"ok",steer:"purple",update:"purple",yield:"warn"};function $d(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function FI({item:e}){let t=OI[e.status]??"queued",n=e.nodeIds[0];return i("li",{class:`session-item status-${t}`,"data-work-item-id":e.id,children:[i("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-item-main",children:[i("button",{type:"button",class:"session-item-title",title:n?"Focus the linked node":void 0,disabled:!n,onClick:()=>n&&tt(n),children:e.title},void 0,!1,void 0,this),e.detail&&i("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"session-item-status",children:LI[e.status]??t},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:$d(e.updatedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function jI({gate:e,now:t}){let[n,o]=L(null),r=async(c)=>{o(c),await sb(e,c),o(null)},s=e.nodeIds[0],a=ic(e,t);return i("li",{class:"session-item status-awaiting session-gate","data-gate-id":e.id,children:[i("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-item-main",children:[i("button",{type:"button",class:"session-item-title",title:s?"Focus the linked node":void 0,disabled:!s,onClick:()=>s&&tt(s),children:e.title},void 0,!1,void 0,this),e.detail&&i("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this),a!==null&&i("div",{class:"session-gate-ttl","data-testid":"gate-countdown",children:["auto-holds in ",sc(a)," if unanswered"]},void 0,!0,void 0,this),i("div",{class:"session-gate-actions",children:[i("button",{type:"button",class:"session-gate-approve",disabled:n!==null,onClick:()=>void r("approved"),children:n==="approved"?"Approving…":"Approve"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-gate-reject",disabled:n!==null,onClick:()=>void r("rejected"),children:n==="rejected"?"Rejecting…":"Reject"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"session-item-time",children:$d(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ZI({gate:e}){let[t,n]=L(!1);return i("li",{class:"session-item status-vetoed session-gate-held","data-gate-id":e.id,children:[i("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-item-main",children:[i("span",{class:"session-item-title",children:e.title},void 0,!1,void 0,this),i("div",{class:"session-item-detail",children:"Auto-held — no answer in time, the action did not proceed."},void 0,!1,void 0,this),i("div",{class:"session-gate-actions",children:i("button",{type:"button",class:"session-gate-reject",disabled:t,onClick:()=>{n(!0),ab(e).finally(()=>n(!1))},children:t?"Reopening…":"Reopen"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"session-item-status",children:"held"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function HI(){let e=Vn.value,t=ye.value.size,[n,o]=L(!1),r=(s)=>{o(!0),tb(s).finally(()=>o(!1))};return i("div",{class:`session-scope${e?" is-fenced":""}`,"data-testid":"session-scope",children:[i("span",{class:"session-scope-dot","aria-hidden":"true"},void 0,!1,void 0,this),e?i(ve,{children:[i("span",{class:"session-scope-text",children:["Scoped to ",i("strong",{children:e.nodeIds.length},void 0,!1,void 0,this)," node",e.nodeIds.length===1?"":"s"," · writes outside are blocked"]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-scope-action",disabled:n,onClick:()=>r(null),children:"Clear"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(ve,{children:[i("span",{class:"session-scope-text",children:"Unscoped — the agent may write anywhere"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-scope-action",disabled:n||t===0,title:t===0?"Select nodes on the canvas first":"Fence the agent to the selected nodes",onClick:()=>r([...ye.value]),children:["Fence to selection",t>0?` (${t})`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function BI(e){if(e==="browser")return"you";return pt.value.find((n)=>n.sessionId===e||n.source===e)?.label??e}function UI({entry:e}){let t=_i.value.has(e.id);return i("li",{class:`session-timeline-row tone-${DI[e.kind]??"muted"}`,children:[i("span",{class:"session-timeline-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-timeline-main",children:[i("div",{class:"session-timeline-head",children:[i("span",{class:"session-timeline-label",title:aw[bd(e.kind)],children:e.label},void 0,!1,void 0,this),e.who&&i("span",{class:"session-timeline-who",style:{"--identity-color":`hsl(${Wn(e.who)} 65% 62%)`},children:BI(e.who)},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:$d(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-timeline-body",children:e.body},void 0,!1,void 0,this),e.undoable&&!t&&i("button",{type:"button",class:"session-timeline-undo","data-testid":"timeline-undo",onClick:()=>void wd(e),children:"↩ undo this edit"},void 0,!1,void 0,this),t&&i("div",{class:"session-timeline-undone",children:"undone · steering sent"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function cw(){let[e,t]=L(!1),n=_r.value,o=Qx.value,r=Co.value,s=nb.value,a=ib.value,[c,l]=L(!1),[u,d]=L(null),p=bn();if(D(()=>{Gn()},[]),!(e||r.length>0))return i("aside",{class:"session-panel is-collapsed","aria-label":"Session (collapsed)",children:[i("button",{type:"button",class:"session-collapse",onClick:()=>t(!0),title:"Expand session panel",children:"‹"},void 0,!1,void 0,this),n&&i("span",{class:`session-collapsed-live phase-${n.phase}`,title:Un(n),"aria-label":`Session live: ${Un(n)}`,children:[i("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this),i("span",{class:"session-collapsed-label",children:"Session"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("aside",{class:"session-panel","aria-label":"Session",children:[i("header",{class:"session-panel-header",children:[i("span",{class:"session-panel-title",children:"Session"},void 0,!1,void 0,this),n&&i("span",{class:`session-live phase-${n.phase}`,title:Un(n),children:[i("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this),i("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),n&&i("button",{type:"button",class:"session-end",title:"End this session — a receipt and a snapshot of the board follow",onClick:()=>void Ga(n),children:"End"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-collapse",onClick:()=>t(!1),title:"Collapse session panel",children:"›"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(HI,{},void 0,!1,void 0,this),(()=>{let f=a.find((g)=>g.undoable&&!_i.value.has(g.id));if(!f)return null;return i("div",{class:"session-undo-row","data-testid":"session-undo-row",children:[i("span",{class:"session-undo-text",title:f.body,children:["Agent edit on top: ",f.body]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-undo-btn",onClick:()=>void wd(f),children:"↩ Undo"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})(),i("div",{class:"session-panel-body",children:[i("section",{class:"session-section",children:(()=>{let f=o.filter((z)=>z.status==="in-progress"||z.status==="todo").length,g=o.filter((z)=>z.status!=="cancelled"),y=g.filter((z)=>z.status==="done").length,x=o.length-g.length,h=r.length>0,v=c||h,b=f>0?`${f} running`:g.length>0?`${y}/${g.length} done${x>0?` · ${x} cancelled`:""}`:o.length>0?`${o.length} cancelled`:"none yet";return i(ve,{children:[i("button",{type:"button",class:"session-section-toggle","aria-expanded":v,"data-testid":"work-items-toggle",onClick:()=>l((z)=>!z),children:[i("span",{class:"session-section-title",children:"Work items"},void 0,!1,void 0,this),i("span",{class:"session-work-summary",children:[f>0&&i("span",{class:"session-work-dot","aria-hidden":"true"},void 0,!1,void 0,this),b]},void 0,!0,void 0,this),i("span",{class:`session-section-chevron${v?" is-open":""}`,"aria-hidden":"true",children:"›"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v&&(r.length===0&&s.length===0&&o.length===0?i("div",{class:"session-empty",children:"No work items yet — the agent's tasks and gates appear here."},void 0,!1,void 0,this):i("ul",{class:"session-list","aria-live":"polite","aria-label":"Work items and gates",children:[r.map((z)=>i(jI,{gate:z,now:p},z.id,!1,void 0,this)),s.map((z)=>i(ZI,{gate:z},z.id,!1,void 0,this)),o.map((z)=>i(FI,{item:z},z.id,!1,void 0,this))]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)})()},void 0,!1,void 0,this),i("section",{class:"session-section",children:[i("h3",{class:"session-section-title",children:"Timeline"},void 0,!1,void 0,this),i("div",{class:"session-timeline-filters",role:"group","aria-label":"Filter timeline",children:sw.map((f)=>i("button",{type:"button",class:`activity-filter${To.value===f.id?" is-active":""}`,"aria-pressed":To.value===f.id,title:f.hint,onMouseEnter:()=>d(f.id),onMouseLeave:()=>d((g)=>g===f.id?null:g),onFocus:()=>d(f.id),onBlur:()=>d((g)=>g===f.id?null:g),onClick:()=>{To.value=f.id},children:f.label},f.id,!1,void 0,this))},void 0,!1,void 0,this),i("div",{class:"session-timeline-hint","data-testid":"timeline-filter-hint",children:aw[u??To.value]},void 0,!1,void 0,this),a.length===0?i("div",{class:"session-empty",children:To.value==="all"?"Nothing recorded yet.":"Nothing of this kind yet."},void 0,!1,void 0,this):i("ul",{class:"session-list session-timeline","aria-live":"polite","aria-label":"Timeline",children:a.map((f)=>i(UI,{entry:f},f.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Md(e){if(!e||typeof e!=="object")return null;let t=e,n=(o)=>Array.isArray(o)?o.length:0;return{added:n(t.addedNodes)+n(t.addedEdges),removed:n(t.removedNodes)+n(t.removedEdges),modified:n(t.modifiedNodes)}}function lw({onOpenSnapshots:e}){let t=Xa.value,[n,o]=L(null),[r,s]=L(!1);if(!t)return null;let a=async()=>{if(!t.snapshot)return;s(!0);try{let u=await fetch(`/api/canvas/snapshots/${encodeURIComponent(t.snapshot.id)}/diff`,{headers:{"x-pmx-workbench":"1"}});if(u.ok){let d=await u.json();o(Md(d.diff)??{added:0,removed:0,modified:0})}}finally{s(!1)}},c=new Date(t.endedAt),l=Number.isNaN(c.getTime())?"":`${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}`;return i("div",{class:"session-receipt","data-testid":"session-receipt",role:"status",children:[i("div",{class:"session-receipt-head",children:[i("span",{class:"session-receipt-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"session-receipt-title",children:[t.endedBy==="human"?"Session ended by you":t.endedBy==="idle-timeout"?"Session ended — idle timeout":t.endedBy==="agent"?"Session ended by the agent":"Session ended",l?` · ${l}`:""]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-receipt-close",onClick:ub,"aria-label":"Dismiss receipt",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-tiles",children:[i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Items"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value",children:t.counts.items},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Done"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-ok",children:t.counts.done},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.counts.cancelled>0&&i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Cancelled"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-muted",children:t.counts.cancelled},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.counts.rejected>0&&i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Rejected"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-danger",children:t.counts.rejected},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.counts.held>0&&i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Held"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-warn",children:t.counts.held},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-note",children:t.snapshot?"A snapshot of the board from before this session is saved — restore it to undo the session.":t.unchanged?"This session changed nothing on the board — no snapshot kept.":"The board was empty when the session started — nothing to restore."},void 0,!1,void 0,this),n&&i("div",{class:"session-receipt-diff","data-testid":"session-receipt-diff",children:["This session: ",n.added," added · ",n.removed," removed · ",n.modified," modified"]},void 0,!0,void 0,this),i("div",{class:"session-receipt-actions",children:[t.snapshot&&i("button",{type:"button",class:"session-receipt-primary",disabled:r,onClick:()=>void a(),children:r?"Comparing…":"View diff"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-receipt-secondary",title:"Open the History drawer — saved boards and past sessions",onClick:e,children:"History"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var WI=[{title:"Tools",shortcuts:[{keys:"V",desc:"Select tool — drag empty space to lasso"},{keys:"Space (hold)",desc:"Pan — drag anywhere moves the board"},{keys:"A",desc:"Annotate — draw on the canvas"}]},{title:"Navigation",shortcuts:[{keys:Ze("K"),desc:"Command palette — search nodes & actions"},{keys:"Tab / Shift+Tab",desc:"Cycle through nodes"},{keys:"← ↑ → ↓",desc:"Walk graph along edges (when node focused)"},{keys:"F",desc:"Fit all nodes on screen"},{keys:Ze("0"),desc:"Reset viewport to origin"},{keys:`${Ze("+")} / ${Ze("−")}`,desc:"Zoom in / out"}]},{title:"Creation",shortcuts:[{keys:"M",desc:"New markdown note"},{keys:"I / W / H",desc:"New image / webpage / HTML surface"},{keys:"Shift+F",desc:"New file node (workspace path)"},{keys:"G / Shift+G",desc:"Group the selection (new frame when empty) / ungroup"},{keys:"Double-click",desc:"Open actions on a node or create menu on canvas"},{keys:"Drag port → node",desc:"Connect two nodes (hover to reveal ports)"}]},{title:"Selection",shortcuts:[{keys:"Click",desc:"Focus node (highlights neighbors & edges)"},{keys:"Shift+Click",desc:"Toggle node in multi-selection"},{keys:"Drag empty space",desc:"Lasso select multiple nodes"},{keys:Ur?"Delete / ⌫":"Delete / Backspace",desc:"Delete the selection (or the focused node)"},{keys:Ur?"⌘Z / ⇧⌘Z":"Ctrl+Z / Ctrl+Y",desc:"Undo / redo — agent edits included"},{keys:"Esc",desc:"Clear selection / close overlay"}]},{title:"View",shortcuts:[{keys:"?",desc:"Toggle this shortcut overlay"},{keys:"Minimap",desc:"Click/drag to navigate (toggle in the rail)"},{keys:"Right-drag",desc:"Pan the board from anywhere"}]}];function uw({onClose:e}){return i("div",{class:"shortcut-overlay-backdrop",onMouseDown:e,children:i("div",{class:"shortcut-overlay",onMouseDown:(t)=>t.stopPropagation(),children:[i("div",{class:"shortcut-overlay-header",children:[i("span",{class:"shortcut-overlay-title",children:"Keyboard Shortcuts"},void 0,!1,void 0,this),i("span",{class:"shortcut-overlay-hint",children:["Press ",i("kbd",{children:"?"},void 0,!1,void 0,this)," or ",i("kbd",{children:"Esc"},void 0,!1,void 0,this)," to close"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"shortcut-overlay-body",children:WI.map((t)=>i("div",{class:"shortcut-group",children:[i("div",{class:"shortcut-group-title",children:t.title},void 0,!1,void 0,this),t.shortcuts.map((n)=>i("div",{class:"shortcut-row",children:[i("kbd",{class:"shortcut-keys",children:n.keys},void 0,!1,void 0,this),i("span",{class:"shortcut-desc",children:n.desc},void 0,!1,void 0,this)]},n.keys,!0,void 0,this))]},t.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var dw="Before session · ";function pw(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function qI(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let o=Math.floor(n/60);if(o<24)return`${o}h ago`;return`${Math.floor(o/24)}d ago`}function ac(e){if(!e.startsWith(dw))return null;let t=e.slice(dw.length),n=t.lastIndexOf(" · ");return n>0?t.slice(0,n):t}function fw({open:e,onClose:t,anchorRef:n}){let[o,r]=L([]),[s,a]=L(!1),[c,l]=L(!1),[u,d]=L(null),[p,m]=L(""),[f,g]=L(null),[y,x]=L({}),h=R(null),v=R(null);D(()=>{if(!e)return;a(!0),Wp().then((T)=>{r(T),a(!1)})},[e]),D(()=>{if(e)setTimeout(()=>v.current?.focus(),50)},[e]),D(()=>{if(!e)return;let T=(P)=>{let Z=h.current,j=n.current;if(Z&&!Z.contains(P.target)&&j&&!j.contains(P.target))t()};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[e,t]),D(()=>{if(!e)return;let T=(P)=>{if(P.key==="Escape")t()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[e,t]);let b=O(async()=>{let T=p.trim();if(!T)return;l(!0);let P=await qp(T);if(l(!1),P.ok&&P.snapshot)r((Z)=>[P.snapshot,...Z]),m("")},[p]),z=O(async(T)=>{g(null),d(T);let P=await Vp(T);if(d(null),P.ok)t()},[t]),F=O(async(T)=>{if((await Gp(T)).ok)r((Z)=>Z.filter((j)=>j.id!==T));g(null)},[]),_=O(async(T)=>{x((Z)=>({...Z,[T]:"loading"}));let P=await ge("snapshotDiff",`/api/canvas/snapshots/${encodeURIComponent(T)}/diff`,{});x((Z)=>({...Z,[T]:Md(P.diff)??{added:0,removed:0,modified:0}}))},[]);if(!e)return null;let k=(T,P)=>f?.id===T.id?i(ve,{children:[i("button",{type:"button",class:`snapshot-action-btn ${f.action==="delete"?"snapshot-action-confirm":"snapshot-action-restore"}`,onClick:()=>f.action==="delete"?F(T.id):z(T.id),title:f.action==="delete"?"Confirm delete":"Confirm restore",disabled:u!==null,children:f.action==="delete"?"Delete":u===T.id?"Restoring…":"Confirm"},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn",onClick:()=>g(null),title:"Cancel",disabled:u!==null,children:"Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(ve,{children:[i("button",{type:"button",class:"snapshot-action-btn snapshot-action-restore",onClick:()=>g({id:T.id,action:"restore"}),title:"Restore this snapshot — replaces the current canvas (undoable)",disabled:u!==null,children:u===T.id?"Restoring…":P},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn snapshot-action-delete",onClick:()=>g({id:T.id,action:"delete"}),title:"Delete this snapshot","aria-label":"Delete snapshot",disabled:u!==null,children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{ref:h,class:"snapshot-panel","data-testid":"history-drawer",role:"dialog","aria-label":"History",children:[i("div",{class:"snapshot-panel-header",children:[i("span",{class:"snapshot-panel-title",children:"History"},void 0,!1,void 0,this),i("span",{class:"snapshot-panel-sub",children:"snapshots + sessions"},void 0,!1,void 0,this),i("span",{class:"snapshot-panel-spacer"},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-panel-close",onClick:t,title:"Close","aria-label":"Close history",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-save-form",children:[i("input",{ref:v,type:"text",class:"snapshot-name-input",value:p,onInput:(T)=>m(T.target.value),onKeyDown:(T)=>{if(T.key==="Enter")b()},placeholder:"Save a snapshot as…","aria-label":"Snapshot name",maxLength:80,disabled:c},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-save-btn",onClick:b,disabled:!p.trim()||c,children:c?"…":"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-restore-note",children:"Restoring replaces the current canvas. You can undo it if needed."},void 0,!1,void 0,this),i("div",{class:"snapshot-list",children:[s&&i("div",{class:"snapshot-empty",children:"Loading…"},void 0,!1,void 0,this),!s&&o.length===0&&i("div",{class:"snapshot-empty",children:"No history yet. Save a snapshot, or start an agent session — it snapshots for you."},void 0,!1,void 0,this),!s&&[...o.filter((T)=>ac(T.name)===null),...o.some((T)=>ac(T.name)!==null)?[{id:"__sessions-header__"}]:[],...o.filter((T)=>ac(T.name)!==null)].map((T)=>{if(T.id==="__sessions-header__")return i("div",{class:"snapshot-section-header","data-testid":"history-sessions-header",children:"Sessions"},T.id,!1,void 0,this);let P=ac(T.name),Z=y[T.id];if(P!==null)return i("div",{class:"snapshot-item is-session","data-testid":"history-session",children:[i("div",{class:"snapshot-item-head",children:[i("span",{class:"snapshot-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"snapshot-item-name",children:["Agent session — ",P]},void 0,!0,void 0,this),i("span",{class:"snapshot-item-time",children:pw(T.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:["snapshot at session start · ",T.nodeCount," node",T.nodeCount!==1?"s":"",Z&&Z!=="loading"&&i("span",{class:"snapshot-item-diff",children:[" ","· since: ",Z.added," added · ",Z.removed," removed · ",Z.modified," modified"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-actions is-session",children:[i("button",{type:"button",class:"snapshot-action-btn snapshot-action-diff",disabled:Z==="loading",onClick:()=>void _(T.id),children:Z==="loading"?"Comparing…":"View diff"},void 0,!1,void 0,this),k(T,"Restore pre-state")]},void 0,!0,void 0,this)]},T.id,!0,void 0,this);return i("div",{class:"snapshot-item","data-testid":"history-snapshot",children:[i("div",{class:"snapshot-item-head",children:[i("span",{class:"snapshot-item-glyph","aria-hidden":"true",children:"◫"},void 0,!1,void 0,this),i("span",{class:"snapshot-item-name",children:T.name},void 0,!1,void 0,this),i("span",{class:"snapshot-item-time",children:pw(T.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:[T.nodeCount," node",T.nodeCount!==1?"s":"",T.edgeCount>0?` · ${T.edgeCount} edge${T.edgeCount!==1?"s":""}`:""," · ",qI(T.createdAt)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-actions",children:k(T,"Restore")},void 0,!1,void 0,this)]},T.id,!0,void 0,this)})]},void 0,!0,void 0,this),i("div",{class:"snapshot-panel-foot",children:"Every agent session start writes a snapshot automatically."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var mw=3,hw={"waiting-approval":0,thinking:1,tooling:2,idle:3};function VI(){let e=Hx.value;if(e.length===0)return null;let t=[...e].sort((a,c)=>(hw[a.phase]??4)-(hw[c.phase]??4)),n=t.slice(0,mw),o=t.slice(mw),r=e.reduce((a,c)=>(a[c.phase]=(a[c.phase]??0)+1,a),{}),s=[r["waiting-approval"]&&`${r["waiting-approval"]} waiting on approval`,r.thinking&&`${r.thinking} thinking`,r.tooling&&`${r.tooling} running tools`,r.idle&&`${r.idle} idle`].filter(Boolean).join(", ");return i(ve,{children:[i("span",{class:"agent-chips",children:n.map((a)=>{let c=pt.value.filter((l)=>l.parentAgentId!=null&&(l.parentAgentId===a.sessionId||l.parentAgentId===a.source)).length;return i(Je,{label:`Agent session — ${a.label}`,tapToOpen:!0,body:"What this attached agent is doing right now: idle, thinking, running a tool, or waiting on your approval. Steer it from the composer below.",children:i("span",{class:`agent-chip phase-${a.phase}`,"data-phase":a.phase,style:{"--identity-color":`hsl(${Wn(a.sessionId)} 65% 62%)`},children:[i("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"agent-chip-label",children:Un(a)},void 0,!1,void 0,this),i("span",{class:"agent-chip-who hud-collapsible-text",children:a.label},void 0,!1,void 0,this),c>0&&i("span",{class:"agent-chip-workers",children:["+",c," worker",c===1?"":"s"]},void 0,!0,void 0,this),i("button",{type:"button",class:"agent-chip-end","aria-label":`End ${a.label} session`,title:`End ${a.label}'s session`,onClick:(l)=>{l.stopPropagation(),Ga({source:a.source,agentId:a.agentId})},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},a.sessionId,!1,void 0,this)})},void 0,!1,void 0,this),o.length>0&&i(Je,{label:`${e.length} agent sessions attached`,tapToOpen:!0,body:`${e.length} agents on this board — ${s}. The most active wear their own chips; the rest are here, and idle agents' cursors leave the board until they work again.`,children:i("span",{class:"agent-chip agent-chip-more","data-testid":"agent-chip-more",children:["+",o.length," · ",e.length," agents"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function GI(){let e=Co.value.length,t=_r.value!==null&&e>0,n=bn(t?1000:0);if(!t)return null;let o=Co.value.map((r)=>ic(r,n)).filter((r)=>r!==null).sort((r,s)=>r-s)[0];return i(Je,{label:"Approval gates waiting on you",tapToOpen:!0,body:"The agent is blocked until you approve or reject in the session panel; unanswered gates auto-hold when the countdown runs out.",children:i("span",{class:"gate-badge",children:[e," gate",e===1?"":"s",o!==void 0&&` · ${sc(o)}`]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function XI(e){if(e>0.9)return"danger";if(e>=0.7)return"warn";return"ok"}function Ci(e){return e>=1000?`${(e/1000).toFixed(e>=1e4?0:1)}k`:String(e)}function KI(){let e=_r.value;if(!e)return null;let t=ud.value,n=e.contextUsage,o=n?n.used:t.used,r=n?n.total:t.total,s=r>0?Math.min(1,o/r):0,a=Math.round(s*100),c=n?{label:`Context window — reported by ${e.label}`,body:`${Ci(n.used)} of ${Ci(n.total)} tokens of the agent's actual context window are used. Your ✦-pinned nodes account for ≈ ${Ci(t.used)} tokens of it.`}:{label:"Pins — pinned-context size (estimate)",body:`The nodes you pinned (✦) are what the agent is asked to carry as context: ≈ ${Ci(t.used)} of a ${Ci(t.total)}-token budget. When the agent's host reports its real context window, this meter switches to showing that instead.`};return i(Je,{label:c.label,body:c.body,tapToOpen:!0,children:i("span",{class:`context-budget tone-${XI(s)}`,"data-mode":n?"window":"pins",children:[i("span",{class:"context-budget-caption hud-collapsible-text",children:n?"Context":"Pins"},void 0,!1,void 0,this),i("span",{class:"context-budget-track","aria-hidden":"true",children:i("span",{class:"context-budget-fill",style:{width:`${a}%`}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"context-budget-label","data-testid":"budget-label",children:[o>0&&a===0?"<1":a,"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function JI(){let[e,t]=L(!1);if(_r.value)return null;return i(Je,{label:"Start an agent session",body:"Attaches a session to this board: the next agent that writes here is adopted into it, and you get the panel, composer, and receipt.",children:i("button",{type:"button",class:"start-session-btn",disabled:e,onClick:()=>{t(!0),Xn().finally(()=>t(!1))},children:[i("span",{class:"start-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),"Start agent session",i("span",{class:"beta-tag",children:"beta"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function gw(){let e=Et.value,t=Vt.value,n=re.value,o=M.value.size,r=Re.value.size,s=Go.value,a=Array.from(M.value.values()).filter((f)=>f.type==="trace").length,[c,l]=L("");D(()=>{let f=!1;return fetch("/health").then((g)=>g.ok?g.json():null).then((g)=>{if(f||typeof g?.workspace!=="string"||!g.workspace)return;let y=g.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop();if(y)l(y)}).catch(()=>{}),()=>{f=!0}},[]);let u=Ed.value,d=u??(e==="connected"&&!t?"syncing":e),p=t?[`${o} node${o!==1?"s":""}`,...r>0?[`${r} edge${r!==1?"s":""}`]:[],...a>0?[`${a} trace${a!==1?"s":""}`]:s?["trace armed"]:[]].join(" · "):"Syncing canvas…",m=()=>{let f=wt();er(f.width,f.height)};return i("div",{class:"top-bar",children:[i(Je,{label:`Canvas status: ${d}`,tapToOpen:!0,body:"Live updates stream in over SSE; amber means reconnecting.",align:"start",children:i("span",{class:`connection-dot ${u??e}`,"aria-label":`Canvas status: ${d}`},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"top-bar-title",title:c||"PMX Canvas",children:c||"PMX Canvas"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:dn.value?dn.value.slice(0,12):"…"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:p},void 0,!1,void 0,this),i("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),i(VI,{},void 0,!1,void 0,this),i(GI,{},void 0,!1,void 0,this),i(KI,{},void 0,!1,void 0,this),i(Gb,{},void 0,!1,void 0,this),i(JI,{},void 0,!1,void 0,this),i("div",{class:"top-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Zoom out",shortcut:Ze("−"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>Yo(0.8),"aria-label":"Zoom out",children:i(bx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Reset zoom",shortcut:Ze("0"),children:i("button",{type:"button",class:"top-bar-zoom-label",onClick:()=>$n({x:0,y:0,scale:1},250),"aria-label":"Reset view",children:[Math.round(n.scale*100),"%"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Zoom in",shortcut:Ze("+"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>Yo(1.25),"aria-label":"Zoom in",children:i(xx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Fit all",shortcut:"F",align:"end",children:i("button",{type:"button",class:"top-bar-btn",onClick:m,"aria-label":"Fit canvas",children:i($a,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function vw(e,t,n,o,r){return e.x<o.position.x+o.size.width+r&&e.x+t+r>o.position.x&&e.y<o.position.y+o.size.height+r&&e.y+n+r>o.position.y}function YI(e,t,n,o,r){return o.some((s)=>vw(e,t,n,s,r))}function QI(e,t,n,o,r){return o.find((s)=>vw(e,t,n,s,r))}function cc(e,t,n,o=24){if(e.length===0)return{x:40,y:80};let r=e[e.length-1],s={x:r.position.x+r.size.width+o,y:r.position.y};if(!YI(s,t,n,e,o))return s;let a=40,c=80,l=3000,u=c;for(let p=0;p<20;p++){let m=a;while(m+t<l){let y=QI({x:m,y:u},t,n,e,o);if(!y)return{x:m,y:u};m=y.position.x+y.size.width+o}u=e.filter((y)=>y.position.y<=u+n+o&&y.position.y+y.size.height+o>u).reduce((y,x)=>Math.max(y,x.position.y+x.size.height),u)+o}let d=e.reduce((p,m)=>Math.max(p,m.position.y+m.size.height),0);return{x:a,y:d+o}}var Kn={status:{x:40,y:80,w:300,h:120},markdown:{x:380,y:80,w:720,h:600},context:{x:1130,y:80,w:320,h:400},"mcp-app":{x:380,y:720,w:960,h:600},webpage:{x:380,y:80,w:520,h:420},"json-render":{x:380,y:720,w:840,h:620},graph:{x:380,y:720,w:760,h:520},ledger:{x:1130,y:520,w:320,h:280},trace:{x:40,y:900,w:200,h:56},file:{x:380,y:80,w:720,h:600},diff:{x:380,y:80,w:640,h:420},mermaid:{x:380,y:80,w:640,h:460},image:{x:380,y:80,w:720,h:520},html:{x:380,y:80,w:720,h:640},group:{x:220,y:60,w:840,h:560},prompt:{x:380,y:1260,w:520,h:400},response:{x:380,y:1480,w:720,h:400}};function Ti(e,t,n,o={}){let r=Kn[t];return{id:e,type:t,position:o.position??{x:r.x,y:r.y},size:o.size??{width:r.w,height:r.h},zIndex:t==="status"?0:1,collapsed:!1,pinned:!1,data:n}}var Ao=null,dc=null,lc=0,Jn=null,eA=3000,tA=2000,yw=5000,Ei=!1,_n=null,Ir=null,Qn=0,Yn=null;function nA(){if(typeof location>"u"||typeof window>"u")return null;let e=new URLSearchParams(location.search).get("transport");if(e==="poll"||e==="sse")return e;if(window.__PMX_AMP_ORB===!0)return"poll";return null}var Ar=new Map;function Ii(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function pc(e){if(!dc)return e;let t=dc.get(e.id);if(!t)return e;return{...e,position:t.position??e.position,size:t.size??e.size,collapsed:t.collapsed??e.collapsed,pinned:t.pinned??e.pinned}}function Ai(e,t,n){return pc(Ti(e,t,n))}function oA(){return cc([...M.value.values()],Kn.markdown.w,Kn.markdown.h)}function zr(){if(!M.value.has("status-main"))pn(Ai("status-main","status",{phase:"idle",message:"",elapsed:0}))}function rA(e,t){let n=`md-${Ii(e)}`;if(M.value.get(n))oe(n,{path:e,title:t}),ke.value=n;else{let r=oA(),s=Ai(n,"markdown",{path:e,title:t,content:"",rendered:""});s.position=r,pn(s),tt(n)}}function iA(e){if(M.value.get("context-main"))oe("context-main",{cards:e});else if(e.length>0){let o=Ai("context-main","context",{cards:e});pn(o)}}function sA(e){let t=e.url,n=`mcp-${Ii(t)}`;if(M.value.get(n))oe(n,e);else pn(Ai(n,"mcp-app",e)),tt(n)}function aA(e){let t=e.toolCallId,o=(typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null)??(t.startsWith("ext-app-")?t:`ext-app-${t}`);if(M.value.get(o)){oe(o,e);return}let{serverName:s,toolName:a}=e;if(s&&a){for(let[x,h]of M.value.entries())if(h.type==="mcp-app"&&h.data.mode==="ext-app"&&h.data.serverName===s&&h.data.toolName===a&&!h.data.toolResult){oe(x,{...e});return}}let{_x:c,_y:l,_width:u,_height:d}=e,p=Kn["mcp-app"],m=u??p.w,f=d??p.h,g=c===void 0||l===void 0?cc([...M.value.values()],m,f):null,y=pc(Ti(o,"mcp-app",{mode:"ext-app",...e},{position:{x:c??g?.x??p.x,y:l??g?.y??p.y},size:{width:m,height:f}}));pn(y),tt(o,{recordHistory:!1})}function cA(e){let t=e.startsWith("ext-app-")?e:`ext-app-${e}`;if(M.value.has(t))return t;let n=`ext-app-${e}`;if(n!==t&&M.value.has(n))return n;for(let[o,r]of M.value.entries())if(r.type==="mcp-app"&&r.data.mode==="ext-app"&&r.data.toolCallId===e)return o;return null}function Sw(e){let t=typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null;if(t&&M.value.has(t))return t;if(typeof e.toolCallId!=="string"||!e.toolCallId)return null;return cA(e.toolCallId)}function kw(e,t){if(typeof e!=="string"||!e)return null;if(typeof t!=="string"||!t)return null;let n=null;for(let[o,r]of M.value.entries())if(r.type==="mcp-app"&&r.data.mode==="ext-app"&&r.data.serverName===e&&r.data.toolName===t&&!r.data.toolResult){if(n)return null;n=o}return n}function Cw(e){if(M.value.get("ledger-main"))oe("ledger-main",e);else{let o=Ai("ledger-main","ledger",e);o.collapsed=!0,pn(o)}}function Od(e){if(!Gr(e))return;if(document.documentElement.setAttribute("data-theme",e),hr(),Xe.value!==e)Xe.value=e}function lA(e){return e==="markdown"||e==="mcp-app"||e==="webpage"||e==="json-render"||e==="graph"||e==="prompt"||e==="response"||e==="status"||e==="context"||e==="ledger"||e==="trace"||e==="file"||e==="diff"||e==="mermaid"||e==="image"||e==="html"||e==="group"}function uA(e){return e==="relation"||e==="depends-on"||e==="flow"||e==="references"}function Ld(e){if(!e||typeof e!=="object")return null;let t=e;if(typeof t.x!=="number"||typeof t.y!=="number")return null;return{x:t.x,y:t.y}}function Tw(e){if(!e||typeof e!=="object")return null;let t=e;if(typeof t.width!=="number"||typeof t.height!=="number")return null;return{width:t.width,height:t.height}}function dA(e){let t=Ld(e),n=Tw(e);return t&&n?{...t,...n}:null}function pA(e){if(typeof e.id!=="string"||!e.id)return null;if(!lA(e.type))return null;let t=Ld(e.position),n=Tw(e.size);if(!t||!n)return null;let o=e.data&&typeof e.data==="object"?Object.fromEntries(Object.entries(e.data)):{};return{id:e.id,type:e.type,position:t,size:n,zIndex:typeof e.zIndex==="number"?e.zIndex:1,collapsed:e.collapsed===!0,pinned:e.pinned===!0,data:o}}function fA(e){if(typeof e.id!=="string"||!e.id)return null;if(typeof e.from!=="string"||!e.from)return null;if(typeof e.to!=="string"||!e.to)return null;if(!uA(e.type))return null;return{id:e.id,from:e.from,to:e.to,type:e.type,...typeof e.label==="string"?{label:e.label}:{},...e.style==="solid"||e.style==="dashed"||e.style==="dotted"?{style:e.style}:{},...e.animated===!0?{animated:!0}:{}}}function mA(e){if(typeof e.id!=="string"||!e.id)return null;if(e.type!=="freehand"&&e.type!=="text")return null;if(!Array.isArray(e.points))return null;let t=e.points.map((o)=>Ld(o)).filter((o)=>o!==null),n=dA(e.bounds);if(t.length<(e.type==="text"?1:2)||!n)return null;return{id:e.id,type:e.type,points:t,bounds:n,color:typeof e.color==="string"?e.color:"#f97316",width:typeof e.width==="number"?e.width:4,...typeof e.text==="string"?{text:e.text}:{},...typeof e.label==="string"?{label:e.label}:{},createdAt:typeof e.createdAt==="string"?e.createdAt:""}}var xw="pmx-canvas-version-reload";function hA(e,t){if(typeof window>"u")return;let n=window,o=(s,a)=>typeof s==="string"&&s!==""&&s!=="unknown"&&typeof a==="string"&&a!==""&&a!=="unknown"&&s!==a;if(!o(e,n.__PMX_BOOT_SERVER_VERSION)&&!o(t,n.__PMX_BOOT_BUNDLE_STAMP))return;let r=`${String(e)}::${String(t)}`;try{if(window.sessionStorage.getItem(xw)===r)return;window.sessionStorage.setItem(xw,r)}catch{return}window.location.reload()}function gA(e){let t=qn.value[0]?.id;if(fd(e),ft.value&&qn.value[0]?.id!==t)Gn()}function vA(e){lb(e)}var bw=null;function yA(e){gd(e)}function xA(e){if(dn.value=e.sessionId||"",Et.value="connected",co.value+=1,hA(e.version,e.bundleStamp),Dr(),Zp().then(fd),bw?.(),!ns)bw=Jx();if(ge("fetchHumanPresence","/api/canvas/human-presence",null).then(gd),Dc().then((t)=>{if(Gt.value=t,ft.value)Gn()}),typeof e.theme==="string"&&!Id())Od(e.theme);if(e.ledgerSummary)Cw(e.ledgerSummary)}function bA(e){if(typeof e.path!=="string"||!e.path)return;let t=e.path,n=(typeof e.title==="string"?e.title:"")||t.split("/").pop()||"Untitled";if(rA(t,n),e.ledgerSummary)Cw(e.ledgerSummary)}function wA(e){zr(),oe("status-main",{message:typeof e.message==="string"?e.message:String(e.message??""),level:e.level??"ok",source:e.source})}function _A(e){zr(),oe("status-main",{phase:e.phase,detail:e.detail})}function SA(e){let t=e.cards??[];iA(t)}function kA(e){if(typeof e.url==="string"&&e.url)sA({url:e.url,sourceServer:e.sourceServer,sourceTool:e.sourceTool,inferredType:e.inferredType,trustedDomain:e.trustedDomain,hostMode:e.hostMode??"hosted"})}function CA(e){let t=e.sessions??[];for(let n of t){let o=n.url;if(!o)continue;let r=`mcp-${Ii(o)}`;if(M.value.has(r))oe(r,{sessionState:n.state,lastSeenAt:n.lastSeenAt})}}function TA(e){if(typeof e.url==="string"&&e.url){let t=`mcp-${Ii(e.url)}`;if(M.value.has(t))oe(t,{hostMode:"fallback",fallbackReason:e.reasonCode})}}function EA(e){let n=M.value.get("context-main");if(!n)return;let o=(n.data.auxTabs??[]).concat(e);oe("context-main",{auxTabs:o})}function IA(e){if(M.value.has("context-main"))if(e.mode==="all")oe("context-main",{auxTabs:[]});else{let o=M.value.get("context-main");if(!o)return;let r=(o.data.auxTabs??[]).filter((s)=>s.id!==e.id);oe("context-main",{auxTabs:r})}}function AA(e){zr(),oe("status-main",{phase:"idle",lastCompletion:{tokenCount:e.tokenCount,artifactCount:e.artifactCount}})}function zA(e){zr(),oe("status-main",{phase:"tooling",detail:`${e.name}`,activeTool:e.name})}function PA(e){zr(),oe("status-main",{activeTool:null})}function NA(e){if(e.state==="active"&&e.path){let n=`md-${Ii(e.path)}`;if(M.value.has(n))oe(n,{reviewActive:!0})}}function RA(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;aA({toolCallId:e.toolCallId,...typeof e.nodeId==="string"&&e.nodeId.length>0?{nodeId:e.nodeId}:{},title:e.title,html:e.html,toolInput:e.toolInput,serverName:e.serverName,toolName:e.toolName,appSessionId:e.appSessionId,resourceUri:e.resourceUri,toolDefinition:e.toolDefinition,resourceMeta:e.resourceMeta,hostMode:"hosted",trustedDomain:!0,...e.chartConfig?{chartConfig:e.chartConfig}:{},...typeof e.x==="number"&&{_x:e.x},...typeof e.y==="number"&&{_y:e.y},...typeof e.width==="number"&&{_width:e.width},...typeof e.height==="number"&&{_height:e.height}})}function $A(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=Sw(e)??kw(e.serverName,e.toolName);if(!t)return;if(M.value.has(t))oe(t,{html:e.html})}function MA(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=Sw(e)??kw(e.serverName,e.toolName);if(!t)return;if(M.value.has(t)){if(e.success===!1){It(t);return}oe(t,{toolResult:Uu({result:e.result,success:typeof e.success==="boolean"?e.success:void 0,error:typeof e.error==="string"?e.error:void 0,content:typeof e.content==="string"?e.content:void 0,detailedContent:typeof e.detailedContent==="string"?e.detailedContent:void 0})})}}function OA(e){zr(),oe("status-main",{subagent:{state:e.state,name:e.agentDisplayName??e.agentName}})}function LA(e){let t=e.nodeId;if(!t)return;let n=e.text||"",{position:o,parentNodeId:r,contextNodeIds:s}=e;if(e.threadNodeId&&M.value.has(e.threadNodeId)){let a=e.threadNodeId,c=M.value.get(a);if(!c)return;let l=Array.isArray(c.data.turns)?[...c.data.turns]:[],u=l[l.length-1];if(!u||u.role!=="user"||u.text!==n)l.push({role:"user",text:n,status:"pending"});oe(a,{turns:l,threadStatus:"pending"});return}if(!M.value.has(t)){let a=o??Kn.prompt;pn(pc(Ti(t,"prompt",{text:n,turns:n?[{role:"user",text:n,status:"pending"}]:[],threadStatus:n?"pending":"draft",status:n?"pending":"draft",parentNodeId:r,contextNodeIds:s},{position:{x:a.x,y:a.y}}))),tt(t)}if(r&&M.value.has(r))ws({id:`edge-${r}-${t}`,from:r,to:t,type:"flow",style:"dashed"})}function DA(e){let{nodeId:t,status:n}=e;if(t&&M.value.has(t))oe(t,{status:n})}function FA(e){let{responseNodeId:t,promptNodeId:n}=e;if(!t)return;let o=n?M.value.get(n):void 0;if(o&&Array.isArray(o.data.turns)){Ar.set(t,n);let s=[...o.data.turns];s.push({role:"assistant",text:"",status:"streaming"}),oe(n,{turns:s,threadStatus:"streaming",_activeResponseId:t}),tt(n);return}let r=o?{x:o.position.x,y:o.position.y+o.size.height+24}:{x:Kn.response.x,y:Kn.response.y};if(!M.value.has(t))pn(pc(Ti(t,"response",{content:"",status:"streaming",promptNodeId:n},{position:r})));if(n)ws({id:`edge-${n}-${t}`,from:n,to:t,type:"flow",animated:!0});tt(t)}function jA(e){let t=e.responseNodeId;if(!t)return;let n=Ar.get(t);if(n){let o=M.value.get(n);if(o&&Array.isArray(o.data.turns)){let r=[...o.data.turns],s=r[r.length-1];if(s&&s.role==="assistant")s.text=e.content,s.status="streaming";oe(n,{turns:r,threadStatus:"streaming"})}return}if(!M.value.has(t))return;oe(t,{content:e.content,status:"streaming"})}function ZA(e){let t=e.responseNodeId;if(!t)return;let n=Ar.get(t);if(n){let s=M.value.get(n);if(s&&Array.isArray(s.data.turns)){let a=[...s.data.turns],c=a[a.length-1];if(c&&c.role==="assistant")c.text=e.content,c.status="complete";oe(n,{turns:a,threadStatus:"answered",_activeResponseId:void 0})}Ar.delete(t);return}if(!M.value.has(t))return;oe(t,{content:e.content,status:"complete"});let r=M.value.get(t)?.data.promptNodeId;if(r){let s=`edge-${r}-${t}`,a=Re.value.get(s);if(a)Tf(s),ws({...a,animated:!1})}}function HA(e){let t=e.layout;if(!t?.nodes)return;let n=!Vt.value;Vt.value=!0;let o=t.nodes.map(pA).filter((c)=>c!==null),r=Array.isArray(t.edges)?t.edges.map(fA).filter((c)=>c!==null):Array.from(Re.value.values()),s=Array.isArray(t.annotations)?t.annotations.map(mA).filter((c)=>c!==null):void 0,a=t.viewport?{x:typeof t.viewport.x==="number"?t.viewport.x:0,y:typeof t.viewport.y==="number"?t.viewport.y:0,scale:typeof t.viewport.scale==="number"?t.viewport.scale:1}:void 0;if(n)Qo();Nf({...a?{viewport:a}:{},nodes:o,edges:r,...s?{annotations:s}:{}},{applyViewport:n}),Vc({event:"canvas-layout-update",data:e})}function BA(e){if(e<=1)return 500;if(e===2)return 1000;return Math.min(2500,1500+(e-3)*500)}function UA(e){let t=e.nodeId;if(t&&M.value.has(t)){if(e.noPan===!0){fn(t);return}tt(t)}}function WA(e){let t=e.viewport;if(!t)return;let n=typeof t.x==="number"?t.x:0,o=typeof t.y==="number"?t.y:0,r=typeof t.scale==="number"?t.scale:1;Qo(),Af({x:n,y:o,scale:r})}function qA(e){if(M.value.get("context-main"))oe("context-main",{currentTokens:e.currentTokens,tokenLimit:e.tokenLimit,messagesLength:e.messagesLength,utilization:e.utilization,nearLimit:e.nearLimit})}function VA(e){Go.value=e.enabled===!0}function GA(e){if(typeof e.theme==="string"&&!Id())Od(e.theme)}function XA(e){let t=Array.isArray(e.nodeIds)?e.nodeIds.filter((n)=>typeof n==="string"):[];Cf(t),Vc({event:"context-pins-changed",data:e})}var uc=null;function ww(){if(uc)clearTimeout(uc);uc=setTimeout(()=>{if(uc=null,Dc().then((e)=>{Gt.value=e}),ft.value)Gn()},150)}function KA(e){let t=e.intent;if(!t||typeof t.id!=="string"||typeof t.kind!=="string"||typeof t.expiresAt!=="number")return;hx(t)}function JA(e){let t=typeof e.id==="string"?e.id:"";if(!t)return;if(e.settled===!0)vx(t,typeof e.nodeId==="string"?e.nodeId:void 0);else Qu(t)}var Ew={connected:xA,"workbench-open":bA,"canvas-status":wA,"execution-phase":_A,"context-cards":SA,"mcp-app-candidate":kA,"mcp-app-host-snapshot":CA,"mcp-app-host-fallback":TA,"aux-open":EA,"aux-close":IA,"assistant-complete":AA,"tool-start":zA,"tool-complete":PA,"review-state":NA,"subagent-status":OA,"ext-app-open":RA,"ext-app-update":$A,"ext-app-result":MA,"context-pins-changed":XA,"canvas-layout-update":HA,"canvas-focus-node":UA,"canvas-viewport-update":WA,"context-usage":qA,"trace-state":VA,"theme-changed":GA,"canvas-prompt-created":LA,"canvas-prompt-status":DA,"canvas-response-start":FA,"canvas-response-delta":jA,"canvas-response-complete":ZA,"ax-state-changed":ww,"ax-event-created":ww,"ax-intent":KA,"ax-intent-clear":JA,"agent-presence":gA,"human-presence":yA,"agent-session-ended":vA};function Iw(e,t){let n=Ew[e];if(!n)return;let o=n;try{o(t)}catch(r){console.warn(`[sse-bridge] Handler for "${e}" failed:`,r)}}function _w(){Ei=!0,Qn+=1;let e=Qn;Et.value="connecting";let t=null,n=!1,o=async()=>{if(e!==Qn)return;try{let r=new URLSearchParams;if(Ir!==null)r.set("since",String(Ir));let s=dn.value;if(s)r.set("session",s);let a=r.toString(),c=await fetch(`/api/workbench/poll${a?`?${a}`:""}`);if(e!==Qn)return;if(!c.ok)throw Error(`poll failed with HTTP ${c.status}`);let l=await c.json();if(e!==Qn)return;if(!l.ok)throw Error("poll returned ok: false");let u=t;if(t=l.sessionId??null,u!==null&&l.sessionId&&u!==l.sessionId&&!l.snapshot){Ir=null,_n=setTimeout(()=>void o(),0);return}if(l.snapshot&&n)dc=ol(),Vt.value=!1,qc(),ed(),Ar.clear();for(let d of l.events)Iw(d.event,d.payload);n=!0,Ir=l.seq,lo.value=0,uo.value=0,Et.value="connected",_n=setTimeout(()=>void o(),tA)}catch(r){if(e!==Qn)return;console.warn("[sse-bridge] poll transport error:",r),Et.value="disconnected",lo.value+=1,uo.value=yw,_n=setTimeout(()=>void o(),yw)}};return o(),()=>{if(Qn+=1,Ei=!1,Ir=null,_n)clearTimeout(_n),_n=null}}function Dd(){if(jb(Od),dc=ol(),Vt.value=!1,qc(),ed(),Ar.clear(),Jn)clearTimeout(Jn),Jn=null;let e=nA();if(e==="poll"||Ei)return _w();let t=dn.value,n=t?`/api/workbench/events?session=${t}`:"/api/workbench/events";Et.value="connecting";let o=new EventSource(n);Ao=o;let r=!1;if(Yn)clearTimeout(Yn);if(Yn=null,e!=="sse")Yn=setTimeout(()=>{if(Yn=null,r||Ao!==o)return;console.warn("[sse-bridge] No SSE event within watchdog window — switching to polling transport."),window.dispatchEvent(new Event("pmx-canvas-boot-extend")),o.close(),Ao=null,_w()},eA);for(let[s]of Object.entries(Ew))o.addEventListener(s,(a)=>{r=!0;try{Iw(s,JSON.parse(a.data))}catch(c){console.warn(`[sse-bridge] Failed to parse "${s}" event:`,c)}});return o.onopen=()=>{if(Ao!==o)return;lc=0,lo.value=0,uo.value=0,Et.value="connected"},o.onerror=()=>{if(Ao!==o)return;Et.value="disconnected",o.close(),Ao=null,lc+=1;let s=BA(lc);lo.value=lc,uo.value=s,Jn=setTimeout(()=>{Jn=null,Dd()},s)},()=>{if(Jn)clearTimeout(Jn),Jn=null;if(Yn)clearTimeout(Yn),Yn=null;if(Ei){if(Qn+=1,Ei=!1,Ir=null,_n)clearTimeout(_n),_n=null}o.close(),Ao=null}}function zo(e,t){console.error(`[app] ${e} failed`,t)}function Aw(){let[e,t]=L(!0),[n,o]=L(!1),[r,s]=L(!1),[a,c]=L(!1),[l,u]=L(null),d=R(null),{menu:p,openNodeMenu:m,openCanvasMenu:f,openEdgeMenu:g,closeMenu:y}=Hb(),x=Vt.value,h=ft.value,v=O(()=>t((P)=>!P),[]),b=O(()=>o((P)=>!P),[]),z=O(()=>o(!1),[]),F=O((P)=>u(P),[]),_=O((P,Z)=>{$n({x:P,y:Z,scale:re.value.scale},200)},[]);D(()=>Dd(),[]),D(()=>{let P=null,Z=()=>{if(P!==null)window.clearTimeout(P);P=window.setTimeout(()=>{P=null,Dr()},400)};return window.addEventListener("resize",Z),()=>{if(P!==null)window.clearTimeout(P);window.removeEventListener("resize",Z)}},[]),D(()=>{let P=(E)=>{let B=(E.metaKey||E.ctrlKey)&&!E.altKey;if(B&&E.key==="k"){E.preventDefault(),s((U)=>!U);return}if(E.key==="Escape"&&l){E.preventDefault(),u(null);return}if(E.key==="Escape"&&Be.value&&!Qt.value){E.preventDefault(),po();return}if(E.key==="Escape"&&r){E.preventDefault(),s(!1);return}if(E.key==="Escape"&&a){E.preventDefault(),c(!1);return}let W=E.target,H=W?.tagName;if(H==="INPUT"||H==="TEXTAREA"||W?.isContentEditable)return;if(E.key===" "&&!E.repeat&&!B){E.preventDefault(),Br.value=!0;return}if(E.key==="?"||E.key==="/"&&E.shiftKey){E.preventDefault(),c((U)=>!U);return}if(B&&(E.key==="z"||E.key==="Z"))E.preventDefault(),_d(E.shiftKey);else if(B&&(E.key==="y"||E.key==="Y"))E.preventDefault(),_d(!0);else if(B&&E.key==="0")E.preventDefault(),$n({x:0,y:0,scale:1},250);else if(B&&(E.key==="="||E.key==="+"))E.preventDefault(),Yo(1.25);else if(B&&E.key==="-")E.preventDefault(),Yo(0.8);else if(E.key==="Escape"){if(ye.value.size>0||un.value!==null){ht();return}ke.value=null,y()}else if(E.key==="Tab")E.preventDefault(),$f(E.shiftKey?-1:1);else if(E.key==="Delete"||E.key==="Backspace"){if(un.value!==null){let ee=un.value;E.preventDefault(),un.value=null,ls(ee).catch((xe)=>zo("delete-edge",xe));return}let U=ye.value.size>0?[...ye.value]:ke.value?[ke.value]:[];if(U.length===0)return;E.preventDefault();for(let ee of U)It(ee),In(ee).catch((xe)=>zo("delete",xe));ht(),ke.value=null}else if(ke.value&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(E.key)){E.preventDefault();let U=E.key.replace("Arrow","").toLowerCase();Mf(U)}else if(!B&&!E.altKey){let U=E.key.toLowerCase();if(U==="v"&&!E.shiftKey)yt.value="select";else if(U==="c"&&!E.shiftKey&&!B)E.preventDefault(),yt.value=yt.value==="connect"?"select":"connect";else if(U==="m"&&!E.shiftKey)E.preventDefault(),Pt({type:"markdown",title:"New note",width:520,height:360}).catch((ee)=>zo("create markdown",ee));else if(U==="a"&&!E.shiftKey)E.preventDefault(),u((ee)=>ee==="pen"?null:"pen");else if(U==="g"&&!E.shiftKey){E.preventDefault();let ee=Array.from(ye.value);if(ee.length>=2)jo({title:"Group",childIds:ee}).catch((xe)=>zo("group selection",xe)),ht();else Pt({type:"group",title:"Group"}).catch((xe)=>zo("create group",xe))}else if(U==="g"&&E.shiftKey){E.preventDefault();for(let ee of wf())It(ee),Zo(ee).catch((xe)=>zo("ungroup",xe));ht()}else if(U==="i"&&!E.shiftKey)E.preventDefault(),wn("image");else if(U==="w"&&!E.shiftKey)E.preventDefault(),wn("webpage");else if(U==="h"&&!E.shiftKey)E.preventDefault(),Pt({type:"html",title:"HTML surface"}).catch((ee)=>zo("create html",ee));else if(U==="f"&&E.shiftKey)E.preventDefault(),wn("file");else if(U==="f"&&!E.shiftKey){E.preventDefault();let ee=wt();er(ee.width,ee.height)}}},Z=(E)=>{if(E.key===" ")Br.value=!1},j=()=>{Br.value=!1};return document.addEventListener("keydown",P),document.addEventListener("keyup",Z),window.addEventListener("blur",j),()=>{document.removeEventListener("keydown",P),document.removeEventListener("keyup",Z),window.removeEventListener("blur",j)}},[l,y,r,a]),D(()=>{let P=window.setTimeout(()=>void Dr(),250);return()=>window.clearTimeout(P)},[h]),D(()=>{if(!x)return;let P=window.__pmxCanvasBootstrapReady;if(typeof P==="function")P()},[x]);let k=Array.from(M.value.values()),T=wt();return i("div",{class:"app-shell","data-session-active":h?"true":"false",children:[i(qb,{minimapVisible:e,onToggleMinimap:v,snapshotOpen:n,onToggleSnapshot:b,snapshotBtnRef:d,onOpenPalette:()=>s(!0),onOpenShortcuts:()=>c((P)=>!P),annotationTool:l,onSetAnnotationTool:F},void 0,!1,void 0,this),i("div",{class:"app-main",children:[i(gw,{},void 0,!1,void 0,this),i(Lb,{},void 0,!1,void 0,this),i("div",{class:"canvas-region",ref:(P)=>Rp(P),children:[i(Mb,{onNodeContextMenu:m,onCanvasContextMenu:f,onEdgeContextMenu:g,annotationMode:l!==null,annotationTool:l},void 0,!1,void 0,this),i(Np,{},void 0,!1,void 0,this),i(Pp,{},void 0,!1,void 0,this),i(Xb,{},void 0,!1,void 0,this),i(Kb,{},void 0,!1,void 0,this),x&&k.length===0&&Ve.value.size===0&&i(Vb,{onOpenPalette:()=>s(!0)},void 0,!1,void 0,this),ye.value.size>0&&i(iw,{},void 0,!1,void 0,this),h?i(Ob,{},void 0,!1,void 0,this):Ee.value.size>0&&i(Wb,{},void 0,!1,void 0,this),i(lw,{onOpenSnapshots:()=>o(!0)},void 0,!1,void 0,this),i(Mp,{},void 0,!1,void 0,this),Be.value&&i(ew,{},void 0,!1,void 0,this),i(fw,{open:n,onClose:z,anchorRef:d},void 0,!1,void 0,this),e&&i(rw,{viewport:re,nodes:M,edges:Re,onNavigate:_,containerWidth:T.width,containerHeight:T.height},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h&&i(cw,{},void 0,!1,void 0,this),p&&i(Bb,{menu:p,onClose:y},void 0,!1,void 0,this),r&&i(Zb,{onClose:()=>s(!1),onToggleMinimap:v},void 0,!1,void 0,this),a&&i(uw,{onClose:()=>c(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}Df();var zw=document.getElementById("app");if(zw)sp(i(Aw,{},void 0,!1,void 0,this),zw);
313
+ </script>`}function px(){return"<style data-pmx-canvas-ext-app-base>html, body { background: transparent !important; }</style>"}function fx(e,t){if(!t)return e;let n=/<head\b[^>]*>/i.exec(e);if(n?.index!==void 0){let r=n.index+n[0].length;return`${e.slice(0,r)}${t}${e.slice(r)}`}let o=/<body\b[^>]*>/i.exec(e);if(o?.index!==void 0){let r=o.index+o[0].length;return`${e.slice(0,r)}${t}${e.slice(r)}`}return`${t}${e}`}function gr(e,t){if(Number.isFinite(e)&&e>0)return Math.round(e);if(Number.isFinite(t)&&t>0)return Math.round(t);return 1}function od(e,t){let n=e?.getBoundingClientRect();return{width:gr(e?.clientWidth??0,gr(n?.width??0,t.width)),height:gr(e?.clientHeight??0,gr(n?.height??0,t.height))}}function oE(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0&&!t}function rE(e,t){return Math.max(gr(e,1),gr(t,1))}function hx({node:e,expanded:t=!1}){let n=M(null),o=M(null),r=M(null),s=M(null),a=M({}),c=M(void 0),l=M(!1),u=M(void 0),d=M(null),p=M(!1),m=M(null),f=M(0),g=M([]),y=M(""),x=M(!1),h=M(!1),v=M([]),b=M(!1),z=M(!1),F=M(!1),_=M(!1),[k,T]=L("loading"),[P,Z]=L(null),[j,E]=L(0),[B,W]=L(!1),[H,U]=L(!1),[ee,xe]=L(()=>t||typeof navigator>"u"||typeof window>"u"||!_o(navigator.userAgent)),Fe=e.data.html,We=e.data.serverName,Te=e.data.appSessionId,eo=e.data.toolInput??{},jt=e.data.toolResult,Kt=e.data.toolName??"ext-app",I=e.data.toolDefinition,K=e.data.toolCallId,le=typeof K==="string"||typeof K==="number"?K:void 0,Y=e.data.resourceMeta,J=e.data.sessionStatus,Q=e.data.sessionError,te=e.size.height,q=e.id,ae=YT(e,j),mt=eE(null),N=e.data.axCapabilities?.enabled===!0&&typeof Fe==="string"&&Fe.length>0,se=Ae(()=>`ax-${crypto.randomUUID()}`,[]),Me=N?tE(se,q):"",de=typeof Fe==="string"&&Fe.length>0?nE(se,q):"",Zt=sx(fx(Fe??"",px()+de+Me),mt);D(()=>{function G(ne){if(ne.source!==n.current?.contentWindow)return;let me=ne.data;if(!me||me.source!==Ds||me.token!==se||me.nodeId!==q)return;if(h.current=!0,me.kind==="paint-tick"){let Pe=me,Nt={content:Pe.content===!0,detail:typeof Pe.detail==="string"?Pe.detail:""};for(let Cn of g.current.splice(0))Cn(Nt)}}return window.addEventListener("message",G),()=>window.removeEventListener("message",G)},[se,q]),D(()=>{if(ee)return;ux({remount:()=>{if(_.current)return!1;return ot(q,"mount-slot"),xe(!0),!0},awaitBoot:()=>new Promise((G)=>{let ne=window.setTimeout(me,ax);function me(){window.clearTimeout(ne),G()}v.current.push(me)})})},[]),hr({enabled:N,token:se,nodeId:q,sourceSurface:"mcp-app",iframeRef:n});let Pi=3,Ht=(G)=>{if(f.current>=Pi)return ot(q,`remount-cap-hit (${G})`),!1;if(b.current)return!0;return f.current+=1,b.current=!0,ot(q,`remount-queued #${f.current} (${G})`),ux({remount:()=>{if(b.current=!1,_.current||!t&&Be.value===q)return ot(q,"remount-skipped"),W(!1),!1;return z.current=typeof document<"u"&&document.visibilityState==="hidden",ot(q,`remount-run #${f.current}`),T("loading"),E((ne)=>ne+1),!0},awaitBoot:()=>new Promise((ne)=>{let me=window.setTimeout(Pe,ax);function Pe(){window.clearTimeout(me),ne()}v.current.push(Pe)})}),!0},Sn=1500,gc=()=>new Promise((G)=>{let ne=n.current?.contentWindow;if(!ne||_.current){G("timeout");return}let me=!1,Pe=window.setTimeout(()=>{if(me)return;me=!0,G("timeout")},Sn);g.current.push((Nt)=>{if(me)return;me=!0,window.clearTimeout(Pe),y.current=Nt.detail,G(Nt.content?"content-verified":"tick-no-content")}),ne.postMessage({source:kl,token:se},"*")}),Zd=async(G)=>{let ne=Date.now()+G;while(Date.now()<ne&&!_.current){if(await gc()==="content-verified")return!0;await new Promise((me)=>window.setTimeout(me,400))}return!1},Rw=()=>new Promise((G)=>{let ne=n.current;if(!ne){G();return}let me=ne.style.width,Pe=ne.style.height;ne.style.width="140%",ne.style.height="140%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{ne.style.width=me,ne.style.height=Pe,ot(q,"soft-expand-cycle"),G()})})}),$w=600,Ni=()=>{if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;let G=n.current;if(!G||_.current)return;if(!KT({userAgent:navigator.userAgent,visibilityState:document.visibilityState,rect:G.getBoundingClientRect(),viewport:{width:window.innerWidth,height:window.innerHeight},alreadyRearmed:F.current}))return;F.current=!0,window.setTimeout(()=>{if(_.current||document.visibilityState==="visible")return;f.current=0,U(!1),z.current=!1,ot(q,"assume-visible-rearm"),Ht("assume-visible")},$w)},vc=(G="")=>{let ne=y.current?` [${y.current}]`:"";return typeof document<"u"&&document.visibilityState==="hidden"?`paint-ok (content-verified)${ne}${G} (host hidden)`:`paint-ok (content-verified)${ne}${G}`},Mw=async()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!_o(navigator.userAgent))return;W(!0);let G=await gc();if(G==="content-verified"){ot(q,vc()),W(!1),Ni();return}if(ot(q,G==="tick-no-content"?`paint-fail (tick without content: ${y.current||"unknown"})`:"paint-fail (no tick)"),await Rw(),G=await gc(),G==="content-verified"){ot(q,vc(" (after soft-expand)")),W(!1),Ni();return}if(_.current)return;if(G==="tick-no-content"&&await Zd(3000)){ot(q,vc(" (after content wait)")),W(!1),Ni();return}if(_.current)return;if(!Ht("paint-fail"))ot(q,"recovery-exhausted"),W(!1),U(!0),Ni()};D(()=>{if(t)return;if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;if(!_o(navigator.userAgent))return;function G(){if(document.visibilityState!=="visible")return;if(!z.current||_.current)return;z.current=!1,f.current=0,U(!1),ot(q,"visible-again-rearm"),Ht("visible-after-hidden-boot")}return document.addEventListener("visibilitychange",G),()=>document.removeEventListener("visibilitychange",G)},[t,q]);let Ow=6000;D(()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!_o(navigator.userAgent))return;if(!Zt.ready||!ee)return;let G=window.setTimeout(()=>{if(x.current||h.current||_.current)return;Ht("boot-watchdog")},Ow);return()=>window.clearTimeout(G)},[ae,Zt.ready,t,ee]),D(()=>()=>{_.current=!0;for(let G of v.current.splice(0))G();for(let G of g.current.splice(0))G({content:!1,detail:"unmounted"})},[]);let yc=(G)=>cr(G),kn=t||Be.value===q;a.current=eo,c.current=jt;let Ri=J==="error"&&typeof Fe==="string"&&Fe.length>0,xc=J==="error"?Ri?`Live session unavailable — showing saved content. Reopen the app to restore interactivity.${Q?` (${Q})`:""}`:Q??"Saved app session is unavailable. Reopen the app to restore interactivity.":"Reconnecting saved app session...",bc=(G)=>{let ne=c.current;if(!G||!p.current||!ne)return null;if(u.current===ne)return null;if(u.current&&rx(u.current,ne))return u.current=ne,null;if(d.current)return d.current;let me=G.sendToolResult(ne).then(()=>{u.current=ne,l.current=!0,T("done")}).catch((Pe)=>{let Nt=Pe instanceof Error?Pe.message:String(Pe);throw Z(`Tool result delivery failed: ${Nt}`),Pe}).finally(()=>{d.current=null});return d.current=me,me};if(D(()=>{if(!Fe||!Zt.ready||!ee)return;let G=n.current;if(!G)return;let ne=!1,me=null,Pe=null,Nt=null,Cn=null,to=null;l.current=!1,u.current=void 0,d.current=null,p.current=!1,x.current=!1,h.current=!1;let $i=()=>{if(!me)return;clearTimeout(me),me=null};return(async()=>{if(!Fe)return;let Tn=G.contentWindow;if(!Tn)throw Error("Ext-app iframe window is unavailable");let no=(pe=Be.value===q?"fullscreen":"inline")=>({theme:yc(Xe.value),platform:"web",containerDimensions:od(G,{width:e.size.width,height:te}),displayMode:pe,locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,...I?{toolInfo:{id:le,tool:I}}:{}}),Lw=()=>{if(Cn!==null)return;Cn=requestAnimationFrame(()=>{if(Cn=null,ne||!p.current)return;Ne.setHostContext?.(no())})},Hd=()=>{if(to!==null)return;to=requestAnimationFrame(()=>{to=requestAnimationFrame(()=>{if(to=null,ne||!p.current)return;Ne.sendHostContextChange?.(no())})})},Bd=()=>{if(!_o(navigator.userAgent))return;if(Pe)clearTimeout(Pe);Pe=setTimeout(()=>{if(Pe=null,ne)return;Mw()},mx+200)},Ne=new Qu(null,{name:"PMX Canvas",version:"1.0.0"},{openLinks:{},serverTools:{listChanged:!1},serverResources:{listChanged:!1},logging:{},updateModelContext:{text:{},structuredContent:{}}},{hostContext:no(kn?"fullscreen":"inline")});Ne.onsizechange=async({height:pe})=>{if(oE(pe,Be.value===q)){let Ye=od(G.parentElement??G,{width:e.size.width,height:te}),Rt=rE(pe,Ye.height);G.style.height=`${Rt}px`;let oo=R.value.get(q)?.size??e.size,Wd=Math.max(oo.height,Rt+rr);if(Math.abs(Wd-oo.height)>8){if(ks(q,{width:oo.width,height:Wd}),s.current!==null)window.clearTimeout(s.current);s.current=window.setTimeout(()=>{nt({recordHistory:!1}),s.current=null},0)}}return{}},Ne.onopenlink=async({url:pe})=>(window.open(pe,"_blank","noopener"),{}),Ne.onsandboxready=async()=>{await Ne.sendSandboxResourceReady({html:fx(Fe,px()),sandbox:Cl,...Y?.csp?{csp:Y.csp}:{},...Y?.permissions?{permissions:Y.permissions}:{}})},Ne.onrequestdisplaymode=async({mode:pe})=>{let{nextMode:Ye,shouldExpand:Rt,shouldCollapse:oo}=QT(pe,kn);if(Rt)en(q);else if(oo)po();return{mode:Ye}},Ne.oncalltool=async(pe)=>{if(!Te)throw Error(xc);try{let Ye=await wo("/api/ext-app/call-tool",{sessionId:Te,nodeId:q,serverName:We,toolName:pe.name,arguments:pe.arguments??{}});return Z(null),Ye}catch(Ye){let Rt=Ye instanceof Error?Ye.message:String(Ye);throw Z(`Tool call failed: ${Rt}`),Ye}},Ne.setRequestHandler(Pa,async()=>{if(!Te)return{tools:[]};return wo("/api/ext-app/list-tools",{sessionId:Te})}),Ne.onlistresources=async()=>Te?wo("/api/ext-app/list-resources",{sessionId:Te}):{resources:[]},Ne.onlistresourcetemplates=async()=>Te?wo("/api/ext-app/list-resource-templates",{sessionId:Te}):{resourceTemplates:[]},Ne.onreadresource=async(pe)=>{if(!Te)throw Error(xc);return wo("/api/ext-app/read-resource",{sessionId:Te,uri:pe.uri})},Ne.onlistprompts=async()=>Te?wo("/api/ext-app/list-prompts",{sessionId:Te}):{prompts:[]},Ne.onupdatemodelcontext=async(pe)=>{if(!Te)return{};return await wo("/api/ext-app/model-context",{nodeId:q,...Array.isArray(pe.content)?{content:pe.content}:{},...pe.structuredContent&&typeof pe.structuredContent==="object"?{structuredContent:pe.structuredContent}:{}}),{}};let wc=new Yu(Tn,Tn);if(Ne.oninitialized=()=>{if(ne)return;$i(),p.current=!0,x.current=!0,ot(q,"initialized"),T("ready"),Z(null),Promise.resolve(Ne.sendHostContextChange(no(kn?"fullscreen":"inline"))).then(()=>dx(Ne,a.current,void 0)).then(()=>bc(Ne)).then(()=>{let pe=()=>{for(let Ye of v.current.splice(0))Ye()};if(typeof navigator<"u"&&_o(navigator.userAgent))Zd(4000).then((Ye)=>{ot(q,Ye?"settled (content-verified)":`settled (content-timeout${y.current?`: ${y.current}`:""})`),pe()});else ot(q,"settled"),pe();Hd(),Bd()}).catch((pe)=>{let Ye=pe instanceof Error?pe.message:String(pe);Z(`Bridge bootstrap failed: ${Ye}`)})},me=setTimeout(()=>{if(ne||p.current)return;let pe=c.current,Ye=no(kn?"fullscreen":"inline");p.current=!0,Ne.setHostContext?.(Ye),Promise.resolve(Ne.sendHostContextChange(Ye)).then(()=>dx(Ne,a.current,pe)).then(()=>{if(l.current=Boolean(pe),pe)u.current=pe;if(T(pe?"done":"ready"),Z(null),Hd(),Bd(),h.current){ot(q,"settled (fallback)");for(let Rt of v.current.splice(0))Rt()}}).catch((Rt)=>{let oo=Rt instanceof Error?Rt.message:String(Rt);Z(`Bridge bootstrap fallback failed: ${oo}`)})},1200),await Ne.connect(wc),ne){$i(),await wc.close();return}if(o.current=Ne,r.current=wc,Nt=new ResizeObserver(Lw),Nt.observe(G),G.parentElement)Nt.observe(G.parentElement);let Ud=!0;m.current=Xe.subscribe((pe)=>{if(Ud){Ud=!1;return}if(ne)return;Ne.setHostContext?.({...no(),theme:yc(pe)}),Ne.sendHostContextChange?.(no())}),bc(Ne)})().catch((Tn)=>{$i(),console.error("[ext-app] Bridge init failed:",Tn),Z(Tn?.message??"Bridge initialization failed")}),()=>{if(ne=!0,$i(),Pe)clearTimeout(Pe),Pe=null;if(Nt?.disconnect(),Nt=null,Cn!==null)cancelAnimationFrame(Cn),Cn=null;if(to!==null)cancelAnimationFrame(to),to=null;if(p.current=!1,d.current=null,m.current?.(),m.current=null,s.current!==null)window.clearTimeout(s.current),s.current=null;if(o.current=null,r.current)r.current.close().catch((Tn)=>{console.error("[ext-app] transport close failed:",Tn)}),r.current=null}},[ae,Zt.key,ee]),D(()=>{if(jt&&o.current&&(k==="ready"||k==="done"))bc(o.current)},[jt,k]),D(()=>{let G=o.current;if(n.current)n.current.style.height="100%";if(!G||!p.current)return;let ne=null,me=null;return ne=requestAnimationFrame(()=>{ne=null,me=requestAnimationFrame(()=>{if(me=null,!p.current)return;let Pe={theme:yc(Xe.value),platform:"web",containerDimensions:od(n.current,{width:e.size.width,height:te}),displayMode:kn?"fullscreen":"inline",locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone};G.setHostContext?.(Pe),G.sendHostContextChange?.(Pe)})}),()=>{if(ne!==null)cancelAnimationFrame(ne);if(me!==null)cancelAnimationFrame(me)}},[kn,te]),!Fe)return i("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--c-muted)",fontSize:"13px",flexDirection:"column",gap:"8px"},children:[i("div",{style:{opacity:0.6},children:["Loading ",Kt," viewer..."]},void 0,!0,void 0,this),i("div",{style:{width:"24px",height:"24px",border:"2px solid var(--c-line)",borderTopColor:"var(--c-muted)",borderRadius:"50%",animation:"spin 1s linear infinite"}},void 0,!1,void 0,this),i("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{style:{flex:1,width:"100%",height:"100%",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[J&&J!=="ready"&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:J==="error"&&!Ri?"var(--c-danger-12)":"var(--c-warn-10)",color:J==="error"&&!Ri?"var(--c-danger)":"var(--c-warn)",borderBottom:`1px solid ${J==="error"&&!Ri?"var(--c-danger-12)":"var(--c-warn-15)"}`},children:xc},void 0,!1,void 0,this),P&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:"var(--c-danger-12)",color:"var(--c-danger)",borderBottom:"1px solid var(--c-danger-12)",display:"flex",alignItems:"center",gap:"6px"},children:[i("span",{children:"⚠"},void 0,!1,void 0,this),i("span",{style:{flex:1},children:P},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>{Z(null),T("loading"),E((G)=>G+1)},style:{background:"var(--c-surface-hover)",border:"1px solid var(--c-danger-12)",borderRadius:"3px",color:"var(--c-danger)",cursor:"pointer",fontSize:"10px",padding:"1px 6px"},children:"Retry"},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>Z(null),style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{flex:1,position:"relative",display:"flex",minHeight:0,height:"100%"},children:[ee&&i("iframe",{ref:n,...Zt.attributes,sandbox:mt,allow:ox(Y?.permissions),style:{flex:1,width:"100%",height:"100%",minHeight:0,border:"none",background:"var(--c-panel)",pointerEvents:kn?"auto":"none"},title:`Ext App: ${Kt}`},ae,!1,void 0,this),H&&!P&&i("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"10px",background:"var(--c-panel)",color:"var(--c-warn)",fontSize:"12px"},children:[i("div",{children:"App surface failed to paint."},void 0,!1,void 0,this),i("button",{type:"button",onClick:(G)=>{G.stopPropagation(),ot(q,"manual-retry"),f.current=0,U(!1),T("loading"),E((ne)=>ne+1)},style:{background:"var(--c-surface-hover)",border:"1px solid var(--c-warn-15)",borderRadius:"4px",color:"var(--c-warn)",cursor:"pointer",fontSize:"11px",padding:"3px 10px"},children:"Retry"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(k==="loading"||B)&&!P&&!H&&i("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"10px",background:"var(--c-panel)",color:"var(--c-muted)",fontSize:"12px",pointerEvents:"none"},children:[i("div",{style:{width:"22px",height:"22px",border:"2px solid var(--c-line)",borderTopColor:"var(--c-muted)",borderRadius:"50%",animation:"spin 1s linear infinite"}},void 0,!1,void 0,this),i("div",{children:k==="loading"?`Connecting to ${Kt}...`:"Finishing paint..."},void 0,!1,void 0,this),i("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!kn&&!(H&&!P)&&i("button",{type:"button",onClick:(G)=>{G.stopPropagation(),en(q)},class:"ext-app-preview-catcher",title:"Click to open",style:{position:"absolute",top:0,right:"56px",bottom:"56px",left:0,background:"transparent",border:"none",padding:0,margin:0,cursor:"zoom-in"},"aria-label":"Open full view to edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function iE(e,t,n,o,r,s,a){if(!e)return e;try{let c=new URL(e,window.location.origin);if(c.searchParams.set("theme",cr(Xe.value)),t)c.searchParams.set("display","expanded");if(typeof n==="number")c.searchParams.set("v",String(n));if(o)c.searchParams.set("axToken",o);if(r)c.searchParams.set("axNodeId",r);if(s)c.searchParams.set("frameToken",s);if(a)c.searchParams.set("fit","content");return c.toString()}catch{return e}}function sE(e,t=window.location.origin){if(!e)return!1;try{let n=new URL(t).origin,o=new URL(e,n);return o.origin===n&&o.pathname.startsWith("/api/canvas/frame-documents/")}catch{return!1}}function Hn({node:e,expanded:t=!1}){if(e.data.mode==="ext-app")return i(hx,{node:e,expanded:t},void 0,!1,void 0,this);return i(aE,{node:e,expanded:t},void 0,!1,void 0,this)}function aE({node:e,expanded:t}){let n=M(null),o=e.type==="mcp-app"&&e.data.viewerType==="web-artifact",r=e.type==="json-render"||e.type==="graph",s=e.data.axCapabilities?.enabled,c=(r||o)&&(o?s===!0:s!==!1),l=o?"mcp-app":"json-render",u=Ae(()=>c?`ax-${crypto.randomUUID()}`:"",[c]),d=Ml(e)&&!t,p=Ae(()=>d?`frame-${crypto.randomUUID()}`:"",[d]);ir(e,n,p),hr({enabled:c&&Boolean(u),token:u,nodeId:e.id,sourceSurface:l,iframeRef:n});let m=Xt.value,f=()=>{if(!c||!u||m==null)return;n.current?.contentWindow?.postMessage({source:Ot,type:"ax-update",token:u,state:m},"*")};D(f,[c,u,m]);let g=typeof e.data.specVersion==="number"?e.data.specVersion:void 0,y=iE(e.data.url||"",t,g,u||void 0,c?e.id:void 0,p||void 0,d),x=sr(y),h=e.data.sourceServer||"",v=e.data.hostMode||"hosted",b=e.data.fallbackReason,z=e.data.trustedDomain===!0||sE(y);if(v==="fallback")return i("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[i("div",{style:{color:"var(--c-warn)",display:"flex",alignItems:"center",gap:"6px"},children:[i("span",{children:"⚠"},void 0,!1,void 0,this),i("span",{children:"Cannot embed — opened externally"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b&&i("div",{style:{color:"var(--c-muted)",fontSize:"11px"},children:["Reason: ",b]},void 0,!0,void 0,this),i("a",{href:y,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all"},children:y},void 0,!1,void 0,this),h&&i("div",{style:{color:"var(--c-dim)",fontSize:"10px"},children:["Source: ",h]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return i("div",{style:{height:"100%",display:"flex",flexDirection:"column",...t?{flex:1,minHeight:0,width:"100%"}:{}},children:[!z&&i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"var(--c-warn-10)",color:"var(--c-warn)",borderBottom:"1px solid var(--c-warn-15)"},children:"Unverified domain"},void 0,!1,void 0,this),i("iframe",{ref:n,...x,class:"mcp-app-frame",sandbox:"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",allow:"clipboard-read; clipboard-write",loading:gt.value==="srcdoc"?void 0:"lazy",onLoad:f,style:{flex:1,minHeight:0,width:"100%"},title:`MCP App: ${h}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var cE=null;function vr(){cE=null}var gx={idle:"var(--c-muted)",running:"var(--c-accent)",planning:"var(--c-thinking)",thinking:"var(--c-thinking)",drafting:"var(--c-accent)",tooling:"var(--c-accent)",review:"var(--c-ok)","waiting-approval":"var(--c-warn)",waiting:"var(--c-warn-alt)"};function lE(e){let t=typeof e.data.phase==="string"&&e.data.phase.trim().length>0?e.data.phase.trim():"";if(t)return t;let n=typeof e.data.content==="string"&&e.data.content.trim().length>0?e.data.content.trim():"";if(n)return n;return(typeof e.data.status==="string"&&e.data.status.trim().length>0?e.data.status.trim():"")||"idle"}function Oa({node:e}){let t=lE(e),n=e.data.detail||"",o=e.data.message||"",r=e.data.level||"ok",s=e.data.activeTool,a=e.data.subagent,c=gx[t]??"var(--c-muted)",l=t!=="idle";return i("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[i("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:c,boxShadow:l?`0 0 8px ${c}`:"none",animation:l?"pulse 1.5s infinite":"none",flexShrink:0}},void 0,!1,void 0,this),i("span",{style:{fontWeight:600,color:c,textTransform:"uppercase",letterSpacing:"0.05em"},children:t},void 0,!1,void 0,this),n&&i("span",{style:{color:"var(--c-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s&&i("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-warn)"},children:[i("span",{style:{fontSize:"10px"},children:"⚙"},void 0,!1,void 0,this),i("span",{style:{fontFamily:"var(--mono)",fontSize:"11px"},children:s},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a&&a.state!=="completed"&&i("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-subagent)"},children:[i("span",{style:{fontSize:"10px"},children:"⠉"},void 0,!1,void 0,this),i("span",{children:a.name},void 0,!1,void 0,this),i("span",{style:{color:"var(--c-muted)",fontSize:"10px"},children:["(",a.state,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o&&i("div",{style:{color:r==="warn"?"var(--c-warn)":r==="error"?"var(--c-danger)":"var(--c-muted)",lineHeight:1.4},children:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yr(e){return typeof e==="string"&&e.trim().length>0?e.trim():null}function vx(e){if(typeof e==="string"){let r=yr(e);return r?{title:"Evidence warning",detail:r}:null}if(!e||typeof e!=="object")return null;let t=e,n=yr(t.title)??"Evidence warning",o=yr(t.detail);return o?{title:n,detail:o}:null}function uE(e){let t=[],n=vx(e.data.warning);if(n)t.push(n);let o=e.data.warnings;if(Array.isArray(o))for(let s of o){let a=vx(s);if(a)t.push(a)}let r=yr(e.data.validationStatus)?.toLowerCase();if(r==="failed"||r==="invalid")t.push({title:"Image failed validation",detail:yr(e.data.validationMessage)??"Review this image before using it as evidence."});return t}function dE(e){let t=[e.data.title,e.data.caption,e.data.alt,e.data.src,e.data.path].map((n)=>yr(n)?.toLowerCase()??"").join(" ");if(t.length===0)return!1;return["login","log in","sign in","signin","password","2fa","mfa","authenticate","authentication","sso"].some((n)=>t.includes(n))}function yx(e){let t=uE(e);if(t.length>0)return t;if(dE(e))return[{title:"Captured login page",detail:"This image looks like an auth screen. Treat it as environment context, not product evidence."}];return[]}function La({node:e,expanded:t=!1}){let n=e.data.src||"",o=e.data.alt||e.data.title||"Image",r=e.data.caption||"",s=yx(e),a=n.startsWith("data:")||n.startsWith("http://")||n.startsWith("https://")?n:`/api/canvas/image/${e.id}`,[c,l]=L(!1),[u,d]=L(!1),[p,m]=L(1),[f,g]=L({x:0,y:0}),[y,x]=L({w:0,h:0}),h=M(null),v=M(!1),b=M({x:0,y:0}),z=O((B)=>{let W=B.target;x({w:W.naturalWidth,h:W.naturalHeight}),l(!0),d(!1)},[]),F=O(()=>{d(!0),l(!1)},[]);D(()=>{m(1),g({x:0,y:0})},[n]);let _=O((B)=>{B.preventDefault(),B.stopPropagation();let W=B.deltaY>0?0.9:1.1;m((H)=>Math.max(0.25,Math.min(10,H*W)))},[]),k=O((B)=>{if(p<=1)return;B.stopPropagation(),v.current=!0,b.current={x:B.clientX,y:B.clientY},B.target.setPointerCapture(B.pointerId)},[p]),T=O((B)=>{if(!v.current)return;let W=B.clientX-b.current.x,H=B.clientY-b.current.y;b.current={x:B.clientX,y:B.clientY},g((U)=>({x:U.x+W,y:U.y+H}))},[]),P=O(()=>{v.current=!1},[]),Z=O(()=>{m(1),g({x:0,y:0})},[]);if(!n)return i("div",{class:"image-node-empty",children:[i("div",{class:"image-node-empty-icon",children:"\uD83D\uDDBC"},void 0,!1,void 0,this),i("div",{class:"image-node-empty-text",children:"No image source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let j=y.w>0?`${y.w}×${y.h}`:"",E=Math.round(p*100);return i("div",{class:`image-node ${t?"image-node-expanded":""}`,ref:h,children:[s.length>0&&i("div",{class:"image-node-warning-stack",children:s.map((B)=>i("div",{class:"image-node-warning",children:[i("span",{class:"image-node-warning-title",children:B.title},void 0,!1,void 0,this),i("span",{class:"image-node-warning-detail",children:B.detail},void 0,!1,void 0,this)]},`${B.title}-${B.detail}`,!0,void 0,this))},void 0,!1,void 0,this),i("div",{class:"image-node-viewport",onWheel:_,onPointerDown:k,onPointerMove:T,onPointerUp:P,style:{cursor:p>1?"grab":"default"},children:[!c&&!u&&i("div",{class:"image-node-loading",children:"Loading…"},void 0,!1,void 0,this),u&&i("div",{class:"image-node-error",children:[i("div",{class:"image-node-error-icon",children:"⚠"},void 0,!1,void 0,this),i("div",{children:"Failed to load image"},void 0,!1,void 0,this),i("div",{class:"image-node-error-path",children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("img",{src:a,alt:o,onLoad:z,onError:F,draggable:!1,style:{transform:`translate(${f.x}px, ${f.y}px) scale(${p})`,opacity:c?1:0,display:u?"none":"block"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(r||j||p!==1)&&i("div",{class:"image-node-footer",children:[r&&i("span",{class:"image-node-caption",children:r},void 0,!1,void 0,this),i("span",{class:"image-node-meta",children:[j&&i("span",{children:j},void 0,!1,void 0,this),p!==1&&i("button",{type:"button",class:"image-node-zoom-reset",onClick:Z,title:"Reset zoom",children:[E,"% ↺"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function xx({node:e}){if((e.data.children??[]).filter((o)=>R.value.has(o)).length>0)return null;return i("div",{class:"group-empty-hint",children:"Drop nodes here — release while the frame lights up to add them"},void 0,!1,void 0,this)}function pE(e){try{return new URL(e).host}catch{return e}}function fE(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Da({node:e,expanded:t=!1}){let n=typeof e.data.url==="string"?e.data.url:"",o=typeof e.data.pageTitle==="string"?e.data.pageTitle:"",r=typeof e.data.description==="string"?e.data.description:"",s=typeof e.data.excerpt==="string"?e.data.excerpt:typeof e.data.content==="string"?e.data.content:"",a=typeof e.data.status==="string"?e.data.status:"idle",c=typeof e.data.error==="string"?e.data.error:"",l=fE(typeof e.data.fetchedAt==="string"?e.data.fetchedAt:void 0),u=typeof e.data.statusCode==="number"?e.data.statusCode:null,d=typeof e.data.imageUrl==="string"?e.data.imageUrl:"",p=e.data.frameBlocked===!0,m=typeof e.data.frameBlockedReason==="string"?e.data.frameBlockedReason:"",[f,g]=L(!1),[y,x]=L(t);D(()=>{if(t)x(!0)},[t]);let h=O(async()=>{if(!n||f)return;g(!0);try{await as(e.id)}finally{g(!1)}},[e.id,f,n]);if(!n)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No webpage URL set"},void 0,!1,void 0,this);let v=a==="ready"?"var(--c-ok)":a==="error"?"var(--c-danger)":"var(--c-warn)";return i("div",{style:{display:"flex",flexDirection:"column",gap:"12px",height:"100%"},children:[i("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[i("div",{style:{minWidth:0,flex:1},children:[i("div",{style:{fontSize:"12px",color:"var(--c-muted)"},children:pE(n)},void 0,!1,void 0,this),i("div",{style:{fontSize:t?"18px":"15px",fontWeight:700,color:"var(--c-text)"},children:o||e.data.title||n},void 0,!1,void 0,this),i("a",{href:n,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all",textDecoration:"none"},children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 8px",borderRadius:"999px",background:"rgba(255,255,255,0.04)",color:v,fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.04em",flexShrink:0},children:[i("span",{style:{width:"7px",height:"7px",borderRadius:"999px",background:v}},void 0,!1,void 0,this),a]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(r||d)&&i("div",{style:{display:"grid",gridTemplateColumns:d&&t?"160px 1fr":"1fr",gap:"12px",alignItems:"start"},children:[d&&t&&i("img",{src:d,alt:o||"Webpage preview image",style:{width:"160px",height:"96px",objectFit:"cover",borderRadius:"10px",border:"1px solid var(--c-line)",background:"var(--c-panel-soft)"}},void 0,!1,void 0,this),r&&i("p",{style:{margin:0,color:"var(--c-text-soft)",lineHeight:1.5,fontSize:t?"14px":"12px"},children:r},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:[i("button",{type:"button",onClick:h,disabled:f,style:{border:"1px solid var(--c-line)",background:"var(--c-panel-soft)",color:"var(--c-text)",borderRadius:"8px",padding:"6px 10px",cursor:f?"progress":"pointer",fontSize:"12px"},children:f||a==="fetching"?"Refreshing…":"Refresh"},void 0,!1,void 0,this),t&&!p&&i("button",{type:"button",onClick:()=>x((b)=>!b),style:{border:"1px solid var(--c-line)",background:"var(--c-panel-soft)",color:"var(--c-text)",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px"},children:y?"Hide live preview":"Show live preview"},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>window.open(n,"_blank","noopener"),style:{border:"1px solid var(--c-line)",background:"transparent",color:"var(--c-accent)",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px"},children:"Open in browser"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&p&&i("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[i("div",{style:{padding:"8px 12px",fontSize:"11px",color:"var(--c-muted)",borderBottom:"1px solid var(--c-line)",background:"rgba(255,255,255,0.03)"},children:"Live preview unavailable. This site refuses embedding, so PMX Canvas cannot show it inline."},void 0,!1,void 0,this),i("div",{style:{padding:"20px",color:"var(--c-text-soft)",lineHeight:1.6,fontSize:"13px"},children:m||"The remote site blocks iframe embedding."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&y&&!p&&i("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[i("div",{style:{padding:"8px 12px",fontSize:"11px",color:"var(--c-muted)",borderBottom:"1px solid var(--c-line)",background:"rgba(255,255,255,0.03)"},children:"Live preview (best effort). If this stays blank, the site likely blocks framing. The cached text snapshot below still works."},void 0,!1,void 0,this),i("iframe",{class:"webpage-node-iframe",title:o||e.data.title||n,src:n,loading:"lazy",referrerPolicy:"no-referrer",sandbox:"allow-downloads allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-presentation allow-scripts",style:{display:"block",width:"100%",height:t?"320px":"180px",border:"none",background:"#fff"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(l||u!==null)&&i("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",color:"var(--c-muted)",fontSize:"11px"},children:[l&&i("span",{children:["Fetched ",l]},void 0,!0,void 0,this),u!==null&&i("span",{children:["HTTP ",u]},void 0,!0,void 0,this),p&&i("span",{children:"Preview blocked by site"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c&&i("div",{style:{color:"var(--c-danger)",fontSize:"12px",lineHeight:1.5},children:c},void 0,!1,void 0,this),i("div",{style:{flex:1,minHeight:0,overflow:"auto",border:"1px solid var(--c-line)",borderRadius:"10px",background:"var(--c-panel-soft)",padding:t?"14px":"10px"},children:s?i("div",{style:{whiteSpace:"pre-wrap",lineHeight:1.55,color:"var(--c-text)",fontSize:t?"14px":"12px"},children:s},void 0,!1,void 0,this):i("div",{style:{color:"var(--c-dim)",fontStyle:"italic"},children:a==="error"?"No cached page text available.":"Waiting for page text..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bx(e){return e.type==="html"&&e.data.presentation===!0}function wi({node:e,expanded:t=!1,presentation:n=!1,presentationExitToken:o,autoFocus:r=!1}){let s=M(null),a=Xe.value,c=Ae(()=>`theme-${crypto.randomUUID()}`,[]),l=Ae(()=>`ax-${crypto.randomUUID()}`,[]),u=Ae(()=>`frame-${crypto.randomUUID()}`,[]),d=typeof e.data.html==="string"?e.data.html:typeof e.data.content==="string"?e.data.content:"",p=Ae(()=>er(d),[d]),m=Ae(()=>d?Vr(e.id,{theme:a,themeToken:c,present:n,presentToken:o,v:p,axToken:l,frameToken:u}):"",[d,n,o,c,p,e.id,l,u]),f=sr(m);ir(e,s,t?"":u),hr({enabled:!0,token:l,nodeId:e.id,sourceSurface:"html-node",iframeRef:s}),D(()=>{if(s.current?.contentWindow?.postMessage({source:Ot,type:"theme-update",token:c,theme:a},"*"),r)s.current?.focus()},[a,c]);let g=e.data.axCapabilities,y=g?.enabled===!0&&(!Array.isArray(g.allowed)||g.allowed.length>0),x=Xt.value;D(()=>{if(!y||x==null)return;s.current?.contentWindow?.postMessage({source:Ot,type:"ax-update",token:l,state:x},"*")},[y,x,l]),D(()=>{if(!r)return;let v=window.setTimeout(()=>s.current?.focus(),0);return()=>window.clearTimeout(v)},[r,m]);let h=()=>{if(s.current?.contentWindow?.postMessage({source:Ot,type:"theme-update",token:c,theme:a},"*"),y&&Xt.value!=null)s.current?.contentWindow?.postMessage({source:Ot,type:"ax-update",token:l,state:Xt.value},"*");if(r)s.current?.focus()};if(!d)return i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No HTML content set"},void 0,!1,void 0,this);return i("iframe",{ref:s,class:n?"html-node-frame html-node-frame-presentation":"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"HTML node",sandbox:"allow-scripts",...f,tabIndex:r?0:void 0,onLoad:h,style:{width:"100%",height:"100%",minHeight:n?0:t?"70vh":"300px",border:"none",background:"var(--c-bg)",borderRadius:n?0:"6px",display:"block"}},void 0,!1,void 0,this)}var rd=null;async function wx(){if(!rd)rd=await jp();return rd}function _x(e,t){if(!e)return null;let n=e.toLowerCase(),o=t.find((s)=>s.name.toLowerCase()===n);if(o)return o.name;let r=t.filter((s)=>s.name.toLowerCase().startsWith(n));return r.length===1?r[0].name:null}function mE(e){return e.replace(/<script[\s>][\s\S]*?<\/script>/gi,"").replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi,"").replace(/<object[\s>][\s\S]*?<\/object>/gi,"").replace(/<embed[\s>][\s\S]*?(?:\/>|<\/embed>)/gi,"").replace(/<link[\s>][\s\S]*?(?:\/>|<\/link>)/gi,"").replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/href\s*=\s*"javascript:[^"]*"/gi,'href="#"').replace(/href\s*=\s*'javascript:[^']*'/gi,"href='#'")}function hE({html:e}){let t=M(null);return D(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=e,n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function gE(e,t){return`${e.role}:${e.status??"none"}:${t}:${e.text}`}function Sx({count:e}){if(e===0)return null;return i("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--c-accent)",background:"rgba(70,182,255,0.08)",borderRadius:"var(--radius-sm)",flexShrink:0},children:["✦"," ",e," context node",e!==1?"s":""," attached"]},void 0,!0,void 0,this)}function kx({message:e,onDismiss:t}){if(!e)return null;return i("div",{style:{padding:"4px 8px",fontSize:"11px",color:"var(--c-danger)",background:"rgba(255,80,80,0.08)",borderRadius:"var(--radius-sm)",display:"flex",alignItems:"center",gap:"6px",flexShrink:0},children:[i("span",{style:{flex:1},children:e},void 0,!1,void 0,this),i("button",{type:"button",onClick:t,style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Fa({node:e,expanded:t=!1}){let n=Array.isArray(e.data.turns)?e.data.turns:[],o=n.length===0,r=e.data.text||"",s=e.data.status||"draft",a=o?s:e.data.threadStatus||"draft",c=a==="draft",l=a==="pending"||a==="sending",u=a==="streaming",d=a==="answered",[p,m]=L(""),[f,g]=L(""),[y,x]=L(null),[h,v]=L(new Map),b=M(null),z=M(null),F=n[n.length-1],_=`${n.length}:${F?.role??""}:${F?.status??""}:${Math.floor((F?.text?.length??0)/200)}`;D(()=>{if(t&&c&&b.current)b.current.focus()},[t,c]),D(()=>{if(!_)return;if(z.current)z.current.scrollTo({top:z.current.scrollHeight,behavior:"smooth"})},[_]);let k=M(null),T=M(n);T.current=n,D(()=>{let W=n.some((U)=>U.role==="assistant"&&U.status==="streaming"),H=()=>{let U=!1,xe=T.current.map((Fe,We)=>({turn:Fe,index:We})).filter(({turn:Fe})=>Fe.role==="assistant"&&Fe.text);if(xe.length===0)return;return Promise.all(xe.map(async({turn:Fe,index:We})=>{let Te=await an(Fe.text);return{index:We,html:mE(Te)}})).then((Fe)=>{if(U)return;let We=new Map;for(let Te of Fe)We.set(Te.index,Te.html);v(We)}),()=>{U=!0}};if(!W){if(k.current)clearTimeout(k.current),k.current=null;return H()}if(k.current)clearTimeout(k.current);return k.current=setTimeout(()=>{k.current=null,H()},400),()=>{if(k.current)clearTimeout(k.current),k.current=null}},[n]);let P=O(async()=>{let W=p.trim();if(!W)return;let H=p;x(null),oe(e.id,{turns:[{role:"user",text:W,status:"pending"}],threadStatus:"pending",text:W}),m("");let U=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds:void 0;if(!(await Lr(W,e.position,e.id,U,e.id)).ok)oe(e.id,{turns:[],threadStatus:"draft",text:"",status:"draft"}),m(H),x("Failed to send prompt. Your draft has been restored.")},[p,e.id,e.position,e.data.contextNodeIds]),Z=O(async()=>{let W=f.trim();if(!W)return;let H=f;x(null);let U=Array.isArray(e.data.turns)?[...e.data.turns]:[];if(U.push({role:"user",text:W,status:"pending"}),oe(e.id,{turns:U,threadStatus:"pending"}),g(""),!(await Zp(e.id,W)).ok)U.pop(),oe(e.id,{turns:U,threadStatus:"answered"}),g(H),x("Failed to send reply. Your draft has been restored.")},[f,e.id,e.data.turns]),j=O((W)=>{if(W.key==="Enter"&&(W.metaKey||W.ctrlKey)){W.preventDefault(),P();return}if(W.key==="Tab"&&p.startsWith("/")){W.preventDefault();let H=p.slice(1).split(/\s/)[0];if(H)wx().then((U)=>{let ee=_x(H,U);if(ee)m(`/${ee}`)})}},[P,p]),E=O((W)=>{if(W.key==="Enter"&&(W.metaKey||W.ctrlKey)){W.preventDefault(),Z();return}if(W.key==="Tab"&&f.startsWith("/")){W.preventDefault();let H=f.slice(1).split(/\s/)[0];if(H)wx().then((U)=>{let ee=_x(H,U);if(ee)g(`/${ee}`)})}},[Z,f]),B=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds.length:0;if(c&&n.length===0)return i("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%",gap:"8px"},children:[i(Sx,{count:B},void 0,!1,void 0,this),i(kx,{message:y,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("textarea",{ref:b,value:p,onInput:(W)=>m(W.target.value),onKeyDown:j,placeholder:"Ask the agent something…",spellcheck:!1,style:{flex:1,resize:"none",background:"rgba(10,14,30,0.4)",border:"1px solid var(--c-line)",borderRadius:"var(--radius-sm)",color:"var(--c-text)",fontFamily:"var(--font)",fontSize:"13px",lineHeight:"1.5",padding:"8px 10px",outline:"none"}},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter to send"]},void 0,!0,void 0,this),i("button",{type:"button",onClick:P,disabled:!p.trim(),style:{padding:"5px 14px",fontSize:"12px",fontWeight:600,background:p.trim()?"var(--c-accent)":"var(--c-line)",color:p.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:p.trim()?"pointer":"default"},children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(o)return i("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[i("div",{style:{flex:1,padding:"2px 0",fontSize:"13px",lineHeight:"1.55",color:"var(--c-text)",whiteSpace:"pre-wrap",wordBreak:"break-word",overflow:"auto"},children:r},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px"},children:i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:l?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:l?"Sending…":d?"Answered":s},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[i(Sx,{count:B},void 0,!1,void 0,this),i(kx,{message:y,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("div",{ref:z,style:{flex:1,overflow:"auto",minHeight:0},children:n.map((W,H)=>i("div",{children:[H>0&&i("div",{class:"thread-turn-divider"},void 0,!1,void 0,this),W.role==="user"?i("div",{class:"thread-turn-user",children:[i("div",{class:"thread-turn-role",children:[i("span",{class:"status-dot"},void 0,!1,void 0,this),"You"]},void 0,!0,void 0,this),i("div",{style:{fontSize:t?"15px":"13px",lineHeight:t?"1.7":"1.55",color:"var(--c-text)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:W.text},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i("div",{class:"thread-turn-assistant",children:[i("div",{class:"thread-turn-role",children:[i("span",{class:`status-dot${W.status==="streaming"?" pulsing":""}`},void 0,!1,void 0,this),"PMX"]},void 0,!0,void 0,this),W.status==="streaming"&&!W.text&&i("div",{style:{height:"2px",background:"linear-gradient(90deg, transparent, var(--c-ok), transparent)",animation:"response-stream-pulse 1.5s ease-in-out infinite",borderRadius:"1px",marginBottom:"4px"}},void 0,!1,void 0,this),i("div",{class:t?"md-reader-content":void 0,style:{fontSize:t?void 0:"13px",lineHeight:t?void 0:"1.55",opacity:W.text?1:0.4},children:h.get(H)?i(ve,{children:[i(hE,{html:h.get(H)??""},void 0,!1,void 0,this),W.status==="streaming"&&i("span",{class:"streaming-cursor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i("div",{style:{color:"var(--c-muted)",fontStyle:"italic"},children:W.status==="streaming"?"Waiting for response…":W.text||"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},gE(W,H),!0,void 0,this))},void 0,!1,void 0,this),i("div",{style:{flexShrink:0,borderTop:"1px solid var(--c-line)",marginTop:"4px",paddingTop:"6px"},children:[i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:d?"6px":0},children:[i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:u?"var(--c-accent)":l?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:u?"Streaming…":l?"Sending…":d?"Answered":a},void 0,!1,void 0,this),i("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:[n.length," turn",n.length!==1?"s":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d&&i("div",{class:"thread-reply-area",children:[i("textarea",{value:f,onInput:(W)=>g(W.target.value),onKeyDown:E,placeholder:"Reply…",spellcheck:!1,rows:2,style:{width:"100%",resize:"none",background:"rgba(10,14,30,0.4)",border:"1px solid var(--c-line)",borderRadius:"var(--radius-sm)",color:"var(--c-text)",fontFamily:"var(--font)",fontSize:"12px",lineHeight:"1.5",padding:"6px 8px",outline:"none"}},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"4px"},children:[i("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter"]},void 0,!0,void 0,this),i("button",{type:"button",onClick:Z,disabled:!f.trim(),style:{padding:"3px 10px",fontSize:"11px",fontWeight:600,background:f.trim()?"var(--c-accent)":"var(--c-line)",color:f.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:f.trim()?"pointer":"default"},children:"Reply"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function vE(e){return e.replace(/<script[\s>][\s\S]*?<\/script>/gi,"").replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi,"").replace(/<object[\s>][\s\S]*?<\/object>/gi,"").replace(/<embed[\s>][\s\S]*?(?:\/>|<\/embed>)/gi,"").replace(/<link[\s>][\s\S]*?(?:\/>|<\/link>)/gi,"").replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/href\s*=\s*"javascript:[^"]*"/gi,'href="#"').replace(/href\s*=\s*'javascript:[^']*'/gi,"href='#'")}function yE({html:e}){let t=M(null);return D(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=e,n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function ja({node:e,expanded:t=!1}){let n=e.data.content||"",o=e.data.status||"streaming",[r,s]=L(""),a=o==="streaming",c=o==="complete";D(()=>{if(!n){s("");return}let u=!1;return an(n).then((d)=>{if(!u)s(vE(d))}),()=>{u=!0}},[n]);let l=O(()=>{Lr("",{x:e.position.x,y:e.position.y+e.size.height+24},e.id)},[e]);return i("div",{class:"response-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[a&&i("div",{class:"response-streaming-bar",style:{height:"2px",background:"linear-gradient(90deg, transparent, var(--c-accent), transparent)",animation:"response-stream-pulse 1.5s ease-in-out infinite",borderRadius:"1px",marginBottom:"4px",flexShrink:0}},void 0,!1,void 0,this),i("div",{class:t?"md-reader":void 0,style:{flex:1,overflow:"auto",minHeight:0,opacity:n?1:0.4,transition:"opacity 0.2s ease"},children:r?i("div",{class:t?"md-reader-content":void 0,children:i(yE,{html:r},void 0,!1,void 0,this)},void 0,!1,void 0,this):i("div",{style:{color:"var(--c-muted)",fontStyle:"italic",fontSize:"13px"},children:a?"Waiting for response…":"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px",flexShrink:0},children:[i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:a?"var(--c-accent)":c?"var(--c-ok)":"var(--c-muted)"},children:a?"Streaming…":c?"Complete":o},void 0,!1,void 0,this),c&&i("button",{type:"button",onClick:l,style:{padding:"3px 10px",fontSize:"11px",background:"rgba(70,182,255,0.1)",border:"1px solid rgba(70,182,255,0.3)",borderRadius:"var(--radius-sm)",color:"var(--c-accent)",cursor:"pointer"},children:"Reply"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Cx(e){return{toolName:e.toolName||e.title||"unknown",category:e.category||"other",status:e.status||"running",duration:e.duration||"",resultSummary:e.resultSummary||e.content||"",error:e.error||""}}var Tx={mcp:"var(--c-accent)",file:"var(--c-warn)",subagent:"var(--c-purple)",other:"var(--c-muted)"},xE={running:"⠋",success:"✓",failed:"✕"},bE={running:"var(--c-accent)",success:"var(--c-ok)",failed:"var(--c-danger)"};function Za({node:e}){let{toolName:t,category:n,status:o,duration:r,resultSummary:s,error:a}=Cx(e.data),c=Tx[n]??Tx.other,l=xE[o]??"◌",u=bE[o]??"var(--c-muted)",d=o==="running",p=a?a.slice(0,30):s.length>30?`${s.slice(0,28)}…`:s;return i("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"0 12px",height:"100%",overflow:"hidden"},children:[i("span",{style:{fontSize:"14px",color:u,flexShrink:0,animation:d?"pulse 1.5s infinite":"none"},children:l},void 0,!1,void 0,this),i("div",{style:{flex:1,minWidth:0,overflow:"hidden"},children:[i("div",{style:{fontFamily:"var(--mono)",fontSize:"11px",fontWeight:600,color:c,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t},void 0,!1,void 0,this),p&&i("div",{style:{fontSize:"10px",color:a?"var(--c-danger)":"var(--c-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1.3},children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r&&i("span",{style:{fontSize:"9px",padding:"1px 5px",borderRadius:"3px",background:"rgba(255,255,255,0.06)",color:"var(--c-muted)",flexShrink:0,whiteSpace:"nowrap"},children:r},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sd(e){let t=R.value.get(e);if(!t)return null;return{left:t.position.x,top:t.position.y,width:t.size.width,height:t.size.height}}function wE(e){let t=e.map((l)=>sd(l)).filter((l)=>l!==null);if(t.length===0)return null;let n=Math.min(...t.map((l)=>l.left)),o=Math.min(...t.map((l)=>l.top)),r=Math.max(...t.map((l)=>l.left+l.width)),s=Math.max(...t.map((l)=>l.top+l.height)),a=54,c=46;return{left:n-a,top:o-c,width:r-n+a*2,height:s-o+c*2}}function id(e,t){return{left:`${e.left}px`,top:`${e.top}px`,width:`${e.width}px`,height:`${e.height}px`,borderRadius:`${t}px`}}function Ex(){let e=Array.from(Lo.value),t=Array.from(Do.value),n=Yi.value;if(e.length===0&&t.length===0)return null;let o=[...R.value.values()],r=o.length>0?(Math.max(...o.map((s)=>s.position.x+s.size.width))-Math.min(...o.map((s)=>s.position.x)))*(Math.max(...o.map((s)=>s.position.y+s.size.height))-Math.min(...o.map((s)=>s.position.y))):0;return i("div",{class:"attention-field-layer","aria-hidden":"true",children:[n.map((s)=>{let a=wE(s.nodeIds);if(!a)return null;if(r>0&&a.width*a.height>=r*0.75)return null;return i("div",{class:"attention-field-region",style:id(a,42)},s.id,!1,void 0,this)}),t.map((s)=>{let a=sd(s);if(!a)return null;return i("div",{class:"attention-field-node attention-field-secondary",style:id({left:a.left-18,top:a.top-18,width:a.width+36,height:a.height+36},28)},`secondary-${s}`,!1,void 0,this)}),e.map((s)=>{let a=sd(s);if(!a)return null;return i("div",{class:"attention-field-node attention-field-primary",style:id({left:a.left-24,top:a.top-24,width:a.width+48,height:a.height+48},30)},`primary-${s}`,!1,void 0,this)})]},void 0,!0,void 0,this)}var _E=new Set(["png","jpg","jpeg","gif","svg","webp","bmp","ico","avif"]),SE=new Set(["md","mdx","markdown"]);function kE(e){let t=e.split(".").pop()?.toLowerCase()??"";if(_E.has(t))return"image";if(SE.has(t))return"markdown";return"file"}async function Ha(e,t,n){let a=Math.ceil(Math.sqrt(e.length));for(let c=0;c<e.length;c++){let l=e[c],u=c%a,d=Math.floor(c/a),p=t-a*420/2+u*420,m=n-150+d*320,f=kE(l.name),g=l.name;if(f==="image"){let y=new FileReader,x=await new Promise((h)=>{y.onload=()=>h(y.result),y.readAsDataURL(l)});await Ut({type:"image",title:g,content:x,x:p,y:m,width:400,height:300})}else{let y=await l.text(),x=f==="markdown"||f==="file";await Ut({type:f,title:g,content:y,x:p,y:m,width:x?720:400,height:x?500:300})}}}var CE={fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"};function we({size:e=16,children:t,...n}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",...CE,...n,children:t},void 0,!1,void 0,this)}function Ua(e){return i(we,{...e,children:[i("polyline",{points:"1 5 1 1 5 1"},void 0,!1,void 0,this),i("polyline",{points:"11 1 15 1 15 5"},void 0,!1,void 0,this),i("polyline",{points:"15 11 15 15 11 15"},void 0,!1,void 0,this),i("polyline",{points:"5 15 1 15 1 11"},void 0,!1,void 0,this),i("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ax(e){return i(we,{...e,children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),i("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this),i("line",{x1:"7",y1:"5",x2:"7",y2:"9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zx(e){return i(we,{...e,children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),i("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function So(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"4",x2:"9.5",y2:"4"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"12",x2:"9.5",y2:"12"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"6.5",x2:"4",y2:"9.5"},void 0,!1,void 0,this),i("line",{x1:"12",y1:"6.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Wa(e){return i(we,{...e,children:[i("rect",{x:"1",y:"2",width:"14",height:"12",rx:"1.5"},void 0,!1,void 0,this),i("rect",{x:"8",y:"7",width:"6",height:"6",rx:"1",fill:"currentColor","fill-opacity":"0.2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Px(e){return i(we,{...e,children:[i("circle",{cx:"8",cy:"8",r:"3"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"1",x2:"8",y2:"3"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"13",x2:"8",y2:"15"},void 0,!1,void 0,this),i("line",{x1:"1",y1:"8",x2:"3",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"13",y1:"8",x2:"15",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"3.05",y1:"3.05",x2:"4.46",y2:"4.46"},void 0,!1,void 0,this),i("line",{x1:"11.54",y1:"11.54",x2:"12.95",y2:"12.95"},void 0,!1,void 0,this),i("line",{x1:"3.05",y1:"12.95",x2:"4.46",y2:"11.54"},void 0,!1,void 0,this),i("line",{x1:"11.54",y1:"4.46",x2:"12.95",y2:"3.05"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function qa(e){return i(we,{...e,children:i("path",{d:"M13 9.5A5.5 5.5 0 1 1 6.5 3 4.5 4.5 0 0 0 13 9.5Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ad(e){return i(we,{...e,children:[i("path",{d:"M3 13l2.8-.7L13 5.1 10.9 3 3.7 10.2 3 13Z"},void 0,!1,void 0,this),i("path",{d:"M9.8 4.1l2.1 2.1"},void 0,!1,void 0,this),i("path",{d:"M2.5 14h11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function cd(e){return i(we,{...e,children:[i("path",{d:"M3 10.5 8.5 5a2 2 0 0 1 2.8 0l1.7 1.7a2 2 0 0 1 0 2.8L8.5 14H5.8L3 11.2Z"},void 0,!1,void 0,this),i("path",{d:"M7.5 6 12 10.5"},void 0,!1,void 0,this),i("path",{d:"M8.5 14H14"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ld(e){return i(we,{...e,children:[i("path",{d:"M3 4h10"},void 0,!1,void 0,this),i("path",{d:"M8 4v8"},void 0,!1,void 0,this),i("path",{d:"M6 12h4"},void 0,!1,void 0,this),i("path",{d:"M4.5 4 4 6"},void 0,!1,void 0,this),i("path",{d:"M11.5 4 12 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Nx(e){return i(we,{...e,children:[i("rect",{x:"1",y:"4",width:"14",height:"10",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M5.5 4 L6.5 2.5 H9.5 L10.5 4"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"9",r:"2.3"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Rx(e){return i(we,{...e,children:[i("circle",{cx:"8",cy:"8",r:"6"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"8",r:"3"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"8",r:"0.8",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function $x(e){return i(we,{...e,children:[i("circle",{cx:"8",cy:"8",r:"6"},void 0,!1,void 0,this),i("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"10.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"5.5",x2:"5.5",y2:"10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Mx(e){return i(we,{...e,children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ox(e){return i(we,{...e,children:[i("rect",{x:"1",y:"3",width:"14",height:"10",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"6",x2:"5",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"7.5",y1:"6",x2:"8.5",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"11",y1:"6",x2:"12",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"10",x2:"12",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function br(e){return i(we,{...e,children:i("path",{d:"M2 13 L2 4 A2 2 0 0 1 4 2 L12 2 A2 2 0 0 1 14 4 L14 9 A2 2 0 0 1 12 11 L5 11 Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Lx({size:e=22,class:t}){return i("svg",{width:e,height:e,viewBox:"0 0 64 64",xmlns:"http://www.w3.org/2000/svg",class:t,"aria-hidden":"true",children:[i("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.35"},void 0,!1,void 0,this),i("rect",{x:"16",y:"16",width:"32",height:"32",rx:"5",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.6"},void 0,!1,void 0,this),i("rect",{x:"24",y:"24",width:"16",height:"16",rx:"3",fill:"none",stroke:"currentColor","stroke-width":"2.2"},void 0,!1,void 0,this),i("rect",{x:"29",y:"29",width:"6",height:"6",rx:"1",fill:"currentColor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Dx({size:e=15}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M3 2l10 5.5-4.2 1.3L7.5 13z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Fx({size:e=15}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M5 7.5V3.8a1 1 0 0 1 2 0V7m0-3.9a1 1 0 0 1 2 0V7m0-2.7a1 1 0 0 1 2 0V7.4m0-.9a1 1 0 0 1 2 0v3.2A4.3 4.3 0 0 1 8.7 14H8a4.3 4.3 0 0 1-3.6-2L2.7 9.3a1 1 0 0 1 1.6-1.2L5 9.2"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function jx({size:e=15}){return i("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M6 4.5L2.5 8 6 11.5M10 4.5L13.5 8 10 11.5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Bn(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"6",x2:"10",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"8.5",x2:"8",y2:"8.5"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"11",x2:"11",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function TE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M4 13.5 L5.5 11.5 L8 11.5"},void 0,!1,void 0,this),i("polyline",{points:"5 6 7 8 5 10"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"10",x2:"11",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function EE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M12 13.5 L10.5 11.5 L8 11.5"},void 0,!1,void 0,this),i("circle",{cx:"5",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"11",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ba(e){return i(we,{...e,children:[i("path",{d:"M3 1.5h6l3.5 3.5v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V2.5a1 1 0 0 1 1-1z"},void 0,!1,void 0,this),i("polyline",{points:"9 1.5 9 5 12.5 5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"8.5",x2:"10.5",y2:"8.5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"11",x2:"9",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ud(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("circle",{cx:"5.5",cy:"6.5",r:"1.2"},void 0,!1,void 0,this),i("path",{d:"M1.8 12 L6 8.5 L9 11 L11.5 9 L14.2 12"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xr(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"1.5",y1:"5.5",x2:"14.5",y2:"5.5"},void 0,!1,void 0,this),i("circle",{cx:"3.3",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"5",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"6.7",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"8",x2:"12",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"4",y1:"10",x2:"10",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function IE(e){return i(we,{...e,children:[i("rect",{x:"2",y:"4",width:"12",height:"10",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"2",y1:"6.5",x2:"14",y2:"6.5"},void 0,!1,void 0,this),i("path",{d:"M11 1.5 L11 4"},void 0,!1,void 0,this),i("circle",{cx:"11",cy:"4",r:"1.6",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function dd(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"1.5","stroke-dasharray":"2 1.5"},void 0,!1,void 0,this),i("rect",{x:"4",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),i("rect",{x:"8.5",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),i("rect",{x:"6.25",y:"8.5",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function AE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M3.5 10.5 L6 6.5 L8.5 9.5 L12.5 5"},void 0,!1,void 0,this),i("circle",{cx:"12.5",cy:"5",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function PE(e){return i(we,{...e,children:[i("rect",{x:"2",y:"2",width:"12",height:"12",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"5.5",x2:"11.5",y2:"5.5"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"8",x2:"11.5",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"4.5",y1:"10.5",x2:"8",y2:"10.5"},void 0,!1,void 0,this),i("line",{x1:"6.5",y1:"2",x2:"6.5",y2:"14",opacity:"0.45"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function NE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"2"},void 0,!1,void 0,this),i("path",{d:"M4 11 L4 6 L6 8.5 L8 6 L8 11"},void 0,!1,void 0,this),i("path",{d:"M10 11 L10 6 L12.5 11 L12.5 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function RE(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("polyline",{points:"10 5 13 5 13 8"},void 0,!1,void 0,this),i("line",{x1:"13",y1:"5",x2:"8",y2:"10"},void 0,!1,void 0,this),i("path",{d:"M6 6 L3.5 6 L3.5 11.5 L10 11.5 L10 9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function $E(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("path",{d:"M7 5.5 C 5.5 5.5 5.5 8 4 8 C 5.5 8 5.5 10.5 7 10.5"},void 0,!1,void 0,this),i("path",{d:"M9 5.5 C 10.5 5.5 10.5 8 12 8 C 10.5 8 10.5 10.5 9 10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ix(e){return i(we,{...e,children:[i("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),i("line",{x1:"5.2",y1:"6",x2:"8",y2:"8"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"8",x2:"10.8",y2:"6"},void 0,!1,void 0,this),i("line",{x1:"8",y1:"8",x2:"8",y2:"11"},void 0,!1,void 0,this),i("circle",{cx:"5.2",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"10.8",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"8",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),i("circle",{cx:"8",cy:"11",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yn(e){switch(e){case"markdown":return Bn;case"prompt":return TE;case"response":return EE;case"file":return Ba;case"diff":return Ba;case"mermaid":return Ix;case"image":return ud;case"webpage":return xr;case"context":return IE;case"group":return dd;case"status":return AE;case"trace":return zE;case"ledger":return PE;case"mcp-app":return NE;case"ext-app":return RE;case"json-render":return $E;case"graph":return Ix;case"html":return xr;default:return Bn}}var Zx={width:260,height:150},ME={markdown:{width:300,height:170},status:{width:280,height:110},context:{width:300,height:200},trace:{width:220,height:64},file:{width:300,height:190},image:{width:260,height:200},webpage:{width:320,height:210},html:{width:320,height:210},group:{width:340,height:210},graph:{width:320,height:210},"json-render":{width:320,height:210},"mcp-app":{width:340,height:230}};function fd(e){return!!e&&e in st}function xn(e){if(!e)return null;let t=R.value.get(e);if(!t)return null;return{left:t.position.x,top:t.position.y,width:t.size.width,height:t.size.height}}function pd(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function _i(e){let t=typeof e.confidence!=="number"?0.82:0.4+Math.max(0,Math.min(1,e.confidence))*0.55;return e.auto?t*0.62:t}function Hx(e,t){let n=Math.max(40,Math.abs(t.x-e.x)/2);return`M ${e.x} ${e.y} C ${e.x+n} ${e.y}, ${t.x-n} ${t.y}, ${t.x} ${t.y}`}function md({intent:e}){let t=fd(e.nodeType)?yn(e.nodeType):null,n=e.label||e.kind,o=typeof e.confidence==="number"?`${Math.round(e.confidence*100)}%`:null;return i("div",{class:"intent-info",onMouseEnter:()=>nr.value=e.id,onMouseLeave:()=>{if(nr.value===e.id)nr.value=null},children:[i("div",{class:"intent-chip",children:[typeof e.seq==="number"&&i("span",{class:"intent-seq",children:e.seq},void 0,!1,void 0,this),t&&i("span",{class:"intent-chip-icon","aria-hidden":"true",children:i(t,{size:12},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"intent-chip-label",children:n},void 0,!1,void 0,this),o&&i("span",{class:"intent-confidence",children:o},void 0,!1,void 0,this),e.phase==="forming"&&!e.auto&&i("button",{type:"button",class:"intent-veto",title:"Veto this move (Esc)","aria-label":"Veto this move",onClick:(r)=>{r.stopPropagation(),io(e)},children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.reason&&i("div",{class:"intent-reason",children:e.reason},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Bx({intent:e,rect:t}){let n=fd(e.nodeType)?yn(e.nodeType):null,o=fd(e.nodeType)?st[e.nodeType]:"Node";return i("div",{class:`intent-ghost intent-ghost-box is-${e.phase}${e.auto?" is-auto":""}`,"data-intent-id":e.id,style:{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`,opacity:_i(e)},children:[i("div",{class:"intent-ghost-titlebar",children:[i("span",{class:"intent-ghost-icon","aria-hidden":"true",children:n?i(n,{size:13},void 0,!1,void 0,this):"◇"},void 0,!1,void 0,this),i("span",{class:"intent-ghost-badge",children:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(md,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ux({intent:e,rect:t,variant:n}){return i("div",{class:`intent-ghost intent-ghost-${n} is-${e.phase}${e.auto?" is-auto":""}`,"data-intent-id":e.id,style:{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`,opacity:_i(e)},children:[n==="edit"&&i("div",{class:"intent-edit-bar"},void 0,!1,void 0,this),i(md,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function OE(e){let t=e.phase==="settling"?xn(e.settledNodeId):null;switch(e.kind){case"create":{if(!e.position)return null;let n=e.nodeType&&ME[e.nodeType]||Zx,o=t??{left:e.position.x,top:e.position.y,...n};return i(Bx,{intent:e,rect:o},e.id,!1,void 0,this)}case"move":{if(!e.position)return null;let o=xn(e.nodeId)??Zx,r=t??{left:e.position.x,top:e.position.y,width:o.width,height:o.height};return i(Bx,{intent:e,rect:r},e.id,!1,void 0,this)}case"remove":{let n=t??xn(e.nodeId);if(!n)return null;return i(Ux,{intent:e,rect:n,variant:"remove"},e.id,!1,void 0,this)}case"edit":{let n=t??xn(e.nodeId);if(!n)return null;return i(Ux,{intent:e,rect:n,variant:"edit"},e.id,!1,void 0,this)}case"connect":{if(!e.edge)return null;let n=xn(e.edge.from),o=xn(e.edge.to);if(!n||!o)return null;let r={x:(n.left+n.width/2+o.left+o.width/2)/2,y:(n.top+n.height/2+o.top+o.height/2)/2},s={left:r.x-110,top:r.y-18,width:220,height:36};return i("div",{class:`intent-ghost intent-ghost-connect is-${e.phase}${e.auto?" is-auto":""}`,"data-intent-id":e.id,style:{left:`${s.left}px`,top:`${s.top}px`,width:`${s.width}px`,opacity:_i(e)},children:i(md,{intent:e},void 0,!1,void 0,this)},e.id,!1,void 0,this)}default:return null}}function Wx(){let e=Array.from(Ve.value.values());if(D(()=>{function t(n){if(n.key!=="Escape")return;let o=nr.value;if(!o)return;let r=Ve.value.get(o);if(!r||r.phase!=="forming")return;n.stopImmediatePropagation(),n.preventDefault(),io(r)}return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[]),e.length===0)return null;return i("div",{class:"intent-layer",children:[i("svg",{class:"intent-line-layer",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"},children:[i("defs",{children:i("marker",{id:"intent-arrow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"3",orient:"auto",children:i("path",{d:"M0,0 L6,3 L0,6 Z",class:"intent-arrow-head"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e.map((t)=>{if(t.kind==="connect"&&t.edge){let n=xn(t.edge.from),o=xn(t.edge.to);if(!n||!o)return null;return i("path",{d:Hx(pd(n),pd(o)),class:`intent-edge type-${t.edge.type}`,style:{opacity:_i(t)}},`line-${t.id}`,!1,void 0,this)}if(t.kind==="move"&&t.position){let n=xn(t.nodeId);if(!n)return null;let o=n,r={x:t.position.x+o.width/2,y:t.position.y+o.height/2};return i("path",{d:Hx(pd(n),r),class:"intent-trail",markerEnd:"url(#intent-arrow)",style:{opacity:_i(t)}},`line-${t.id}`,!1,void 0,this)}return null})]},void 0,!0,void 0,this),e.map(OE)]},void 0,!0,void 0,this)}var qx=32000;var Va="Agent session";function Vx(e){return e.some((t)=>t.attached)}function Gx(e){return e.filter((t)=>!t.attached)}function Un(e){switch(e.phase){case"thinking":return"Thinking";case"tooling":return e.detail?`Running ${e.detail}`:"Working";case"waiting-approval":return"Waiting on you";default:return"Idle"}}function Wn(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t%360+360)%360}var pt=V([]),gd=V({used:0,total:qx}),qn=V([]),ko=V(!1),wr=V(!1),vd=V(null),Xx=["var(--c-purple)","var(--c-accent)","var(--c-ok)","var(--c-warn)","var(--c-danger)"],hd=new Map;function Ga(e){let t=hd.get(e);if(t)return t;let n=Xx[hd.size%Xx.length];return hd.set(e,n),n}function Kx(e){return(e.trim().replace(/^[^a-z0-9]+/i,"").charAt(0)||e.trim().charAt(0)||"?").toUpperCase()}function Xa(e,t=Date.now()){let n=t-Date.parse(e);if(!Number.isFinite(n)||n<5000)return"now";if(n<60000)return`${Math.floor(n/1000)}s`;if(n<3600000)return`${Math.floor(n/60000)}m`;return`${Math.floor(n/3600000)}h`}var ft=Oe(()=>Vx(pt.value)),yd=Oe(()=>Gx(pt.value)),Jx=Oe(()=>{let e=new Set;return[...pt.value].filter((t)=>t.label!==Va).sort((t,n)=>Number(n.attached)-Number(t.attached)).map((t)=>({value:t.sessionId==="browser"?t.label:t.sessionId,label:t.label,attached:t.attached,steerable:t.attached||t.steerable===!0,pendingSteers:t.pendingSteers??0,polling:t.lastClaimAt!==void 0&&Date.now()-Date.parse(t.lastClaimAt)<300000})).filter((t)=>e.has(t.value)?!1:(e.add(t.value),!0))}),Yx=Oe(()=>pt.value.filter((e)=>e.attached)),_r=Oe(()=>pt.value.find((e)=>e.attached)??null);function LE(e){let t=new Set;for(let n of e)if(n.nodeId&&n.kind!=="create")t.add(n.nodeId);return t}var Qx=Oe(()=>LE(Ve.value.values()));function Ka(e,t){if(e.cursor)return{x:e.cursor.x,y:e.cursor.y};if(!e.focusNodeId)return null;let n=t(e.focusNodeId);if(!n)return null;return{x:n.position.x+Math.max(24,n.size.width-28),y:n.position.y+16}}function xd(e){if(!e)return;if(Array.isArray(e.presences))pt.value=e.presences;if(e.budget&&Number.isFinite(e.budget.used)&&Number.isFinite(e.budget.total))gd.value={used:e.budget.used,total:e.budget.total};if(Array.isArray(e.activity))qn.value=e.activity}function eb(){let e=M(new Map),t=re.value.scale,n=R.value,o=1/Math.max(0.05,t),r=pt.value.map((s)=>{let a=Ka(s,(l)=>n.get(l));if(a)e.current.set(s.sessionId,a);let c=a??e.current.get(s.sessionId)??null;return c?{presence:s,position:c}:null}).filter((s)=>s!==null);if(r.length===0)return null;return i("div",{class:"agent-presence-layer","aria-hidden":"true",children:r.map(({presence:s,position:a})=>i("div",{class:`agent-cursor phase-${s.phase}${s.attached?"":" is-external"}${s.parentAgentId?" is-worker":""}`,"data-session-id":s.sessionId,style:{transform:`translate(${a.x}px, ${a.y}px)`,"--identity-color":`hsl(${Wn(s.sessionId)} 65% 62%)`},children:i("div",{class:"agent-cursor-inner",style:{transform:`scale(${o})`},children:[i("svg",{class:"agent-cursor-glyph",width:"16",height:"18",viewBox:"0 0 16 18","aria-hidden":"true",children:i("path",{d:"M1.5 1.5L14.5 9.2 8.3 10.6 5.2 16.5z",fill:"currentColor",stroke:"var(--c-bg)","stroke-width":"1.2"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"agent-cursor-chip",children:[i("span",{class:"agent-cursor-dot"},void 0,!1,void 0,this),i("span",{class:"agent-cursor-label",children:Un(s)},void 0,!1,void 0,this),i("span",{class:"agent-cursor-who",children:s.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},s.sessionId,!1,void 0,this))},void 0,!1,void 0,this)}function bn(e=1000){let[t,n]=L(()=>Date.now());return D(()=>{if(e<=0)return;n(Date.now());let o=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(o)},[e]),t}function tb(){let e=bn(Jr.value.length>0?5000:0),t=Jr.value.filter((o)=>o.cursor!==null&&(!o.lastSeenAt||e-Date.parse(o.lastSeenAt)<km+5000));if(t.length===0)return null;let n=1/Math.max(0.05,re.value.scale);return i("div",{class:"human-presence-layer","aria-hidden":"true",children:t.map((o)=>i("div",{class:`human-cursor${o.grabbingNodeId?" is-grabbing":""}`,"data-client-id":o.clientId,style:{transform:`translate(${o.cursor.x}px, ${o.cursor.y}px)`},children:i("div",{class:"human-cursor-inner",style:{transform:`scale(${n})`},children:[i("svg",{class:"human-cursor-glyph",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",children:i("path",{d:"M3 2 L13 8 L8.5 9.5 L6.5 14 Z",fill:"currentColor",stroke:"var(--c-bg)","stroke-width":"1"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"human-cursor-tag",children:o.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},o.clientId,!1,void 0,this))},void 0,!1,void 0,this)}function Ja(e,t){let{POSITIVE_INFINITY:n,POSITIVE_INFINITY:o,NEGATIVE_INFINITY:r,NEGATIVE_INFINITY:s}=Number,a=0;for(let c of e)a+=1,n=Math.min(n,c.position.x),o=Math.min(o,c.position.y),r=Math.max(r,c.position.x+c.size.width),s=Math.max(s,c.position.y+c.size.height);if(a===0)return null;return{x:n-t,y:o-t,width:r-n+t*2,height:s-o+t*2}}function wd(){let e=Xt.value;return e&&typeof e==="object"?e:{}}var nb=Oe(()=>wd().workItems??[]),ob=Oe(()=>wd().approvalGates??[]),Co=Oe(()=>ob.value.filter((e)=>e.status==="pending")),Vn=Oe(()=>{let e=wd().policy?.scope;return e&&Array.isArray(e.nodeIds)&&e.nodeIds.length>0?{nodeIds:e.nodeIds,padding:typeof e.padding==="number"?e.padding:40}:null});async function rb(e){return(await Ct("setScopeFence","/api/canvas/ax/policy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e&&e.length>0?{nodeIds:e}:null,source:"browser"})})).ok}var ib=Oe(()=>ob.value.filter((e)=>e.status==="held")),sb=V({events:[],evidence:[],steering:[]}),To=V("all");function _d(e){if(e==="update")return"update";if(e==="steer"||e==="steering"||e==="yield")return"steer";if(e==="assistant-message")return"assistant";if(e==="evidence")return"evidence";return"event"}var DE=new Set(["api","mcp","sdk","cli"]);function bd(e,t){if(e?.trim())return e.trim();let n=t?.trim();if(n&&!DE.has(n))return n;return null}var FE=/^(node|edge|group|annotation|jsonrender|graph|render)\.|^arrange$|^canvas\.clear$|^snapshot\.restore$/,ab=V(null),Si=V(new Set),jE={prompt:"Prompt","assistant-message":"Assistant","tool-start":"Tool run","tool-result":"Tool result",failure:"Failure",approval:"Approval",steering:"Steering",command:"Command",note:"Note",policy:"Policy",yield:"Yield"};function ZE(e,t=40,n=[],o=null,r="all"){let s=n.find((l)=>FE.test(l.op)),a=[...n.map((l)=>({id:`update-${l.id}`,kind:"update",label:"Update",body:l.summary,createdAt:l.at,who:l.sessionId??null,...o?.actor==="agent"&&s?.id===l.id?{undoable:!0}:{}})),...e.events.map((l)=>({id:`event-${l.id}`,kind:l.kind,label:jE[l.kind]??l.kind,body:l.detail?`${l.summary} — ${l.detail}`:l.summary,createdAt:l.createdAt,who:bd(l.agentId,l.source)})),...e.evidence.map((l)=>({id:`evidence-${l.id}`,kind:"evidence",label:"Evidence",body:l.body?`${l.title} — ${l.body}`:l.title,createdAt:l.createdAt,who:bd(l.agentId,l.source)})),...e.steering.map((l)=>{let u=l.agentId??(l.source&&l.source!=="browser"?l.source:null),d=l.target?`→ ${l.target} · `:u?"→ all · ":"",p=l.target&&l.delivered===!1?` — waiting for ${l.target} to pick it up`:"";return{id:`steer-${l.id}`,kind:"steer",label:"Steer",body:`${u?`${u} `:""}${d}${l.message}${p}`,createdAt:l.createdAt,who:bd(l.agentId,l.source)}})],c=r==="all"?a:a.filter((l)=>_d(l.kind)===r);return c.sort((l,u)=>l.createdAt<u.createdAt?1:l.createdAt>u.createdAt?-1:0),c.slice(0,t)}var cb=Oe(()=>ZE(sb.value,40,qn.value,ab.value,To.value));async function Gn(){let[e,t]=await Promise.all([ge("refreshTimeline","/api/canvas/ax/timeline?limit=40",null),ge("refreshHistoryTop","/api/canvas/history",null)]);if(t)ab.value=t.top??null;if(!e)return;sb.value={events:Array.isArray(e.events)?e.events:[],evidence:Array.isArray(e.evidence)?e.evidence:[],steering:Array.isArray(e.steering)?e.steering:[]}}async function Sd(e){if(!(await Ct("undoAgentEdit","/api/canvas/undo",{method:"POST"})).ok)return!1;return Si.value=new Set([...Si.value,e.id]),await Bt("undoAgentEditSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:`Undid your edit: ${e.body} — it was reverted on the board.`,source:"browser"})}),Gn(),!0}async function kd(e=!1){let t=await Ct(e?"redo":"undo",e?"/api/canvas/redo":"/api/canvas/undo",{method:"POST"});if(t.ok)Gn();return t.ok}async function lb(e,t){if(!(await Ct("resolveGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/resolve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:t,source:"browser"})})).ok)return!1;if(t==="rejected")await Bt("rejectGateSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:`Rejected gate "${e.title}" — do not proceed with it.`,source:"browser"})});return!0}async function ub(e){return(await Ct("reopenGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/reopen`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser"})})).ok}async function db(e,t){return(await Ct("sendSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e,source:"browser",...t?{target:t}:{}})})).ok}async function Xn(){return(await Ct("startSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser",label:Va,attached:!0,phase:"idle"})})).ok}async function Ya(e){return(await Ct("endSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:e.source,agentId:e.agentId,attached:!1,endedBy:"human"})})).ok}var Qa=V(null);function pb(e){let{counts:t,snapshot:n}=e;if(typeof e.label!=="string"||typeof e.endedAt!=="string")return;Qa.value={label:e.label,endedAt:e.endedAt,endedBy:e.endedBy==="human"||e.endedBy==="agent"||e.endedBy==="idle-timeout"?e.endedBy:void 0,unchanged:e.unchanged===!0,counts:{items:Number(t?.items??0)||0,done:Number(t?.done??0)||0,cancelled:Number(t?.cancelled??0)||0,rejected:Number(t?.rejected??0)||0,held:Number(t?.held??0)||0},snapshot:n&&typeof n.id==="string"?{id:n.id,name:String(n.name??"")}:null}}function fb(){Qa.value=null}function mb(){if(!ft.value)return null;let e=Vn.value;if(!e)return null;let t=R.value,n=e.nodeIds.map((s)=>t.get(s)).filter((s)=>s!==void 0),o=Ja(n,e.padding);if(!o)return null;let r=1/Math.max(0.05,re.value.scale);return i("div",{class:"scope-fence","data-fenced-count":n.length,style:{transform:`translate(${o.x}px, ${o.y}px)`,width:`${o.width}px`,height:`${o.height}px`},"aria-hidden":"true",children:[i("span",{class:"scope-fence-pill scope-fence-pill-top",style:{transform:`scale(${r})`},children:["Agent scope · ",n.length," node",n.length===1?"":"s"]},void 0,!0,void 0,this),i("span",{class:"scope-fence-pill scope-fence-pill-bottom",style:{transform:`scale(${r})`},children:"writes outside are blocked · reads allowed"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ec={markdown:"var(--c-accent)","mcp-app":"var(--c-ok)",webpage:"var(--c-warn)","json-render":"var(--c-ok)",graph:"var(--c-purple)",prompt:"var(--c-accent)",response:"var(--c-ok)",status:"var(--c-warn)",context:"var(--c-muted)",ledger:"var(--c-dim)",trace:"var(--c-purple)",file:"var(--c-accent)",diff:"var(--c-ok)",mermaid:"var(--c-purple)",image:"var(--c-ok)",html:"var(--c-warn)",group:"var(--c-accent)"};function HE(e){let t=typeof e==="number"&&Number.isFinite(e)?Math.floor(e):1;return Math.max(1,Math.min(20,t))}function tc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ki(e){return typeof e==="string"&&e.length>0}function hb(e){let t=e.axStep;if(!tc(t))return null;if(!ki(t.flowId)||!ki(t.workItemId))return null;if(typeof t.index!=="number"||typeof t.total!=="number")return null;return{flowId:t.flowId,index:t.index,total:t.total,workItemId:t.workItemId}}function gb(e){let t=e.axFlow;if(!tc(t)||!ki(t.flowId)||!Array.isArray(t.steps))return null;let n=[];for(let r of t.steps){if(!tc(r)||!ki(r.nodeId)||!ki(r.workItemId))return null;if(typeof r.index!=="number")return null;n.push({index:r.index,nodeId:r.nodeId,workItemId:r.workItemId,title:typeof r.title==="string"?r.title:""})}if(n.length===0)return null;let o=tc(t.loop)?t.loop:{};return{flowId:t.flowId,title:typeof t.title==="string"?t.title:"Flow",steps:n,loop:{running:o.running===!0,run:typeof o.run==="number"&&Number.isFinite(o.run)?Math.max(0,Math.floor(o.run)):0,maxRuns:HE(o.maxRuns)}}}var BE={position:"sticky",bottom:"calc(-1 * var(--ax-dock-bleed, 12px))",marginTop:"12px",marginLeft:"calc(-1 * var(--ax-dock-bleed, 12px))",marginRight:"calc(-1 * var(--ax-dock-bleed, 12px))",marginBottom:"calc(-1 * var(--ax-dock-bleed, 12px))",padding:"9px var(--ax-dock-pad, 12px) 10px",background:"var(--c-panel-overlay)",borderTop:"1px solid var(--c-line)",backdropFilter:"blur(6px)"},yb={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},xb={fontSize:"10px",color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginRight:"auto"},bb={...ao,background:"var(--c-accent-25)",color:"var(--c-text)"},UE=[{status:"in-progress",label:"Start",toast:"Step started"},{status:"done",label:"Done",toast:"Step done"},{status:"blocked",label:"Blocked",toast:"Step blocked"}];async function vb(e,t,n){let o={...t,loop:n};oe(e.id,{axFlow:o}),await it(e.id,{data:{axFlow:o}})}function wb(e){return typeof e?.axWorkStatus==="string"?e.axWorkStatus:"todo"}function WE({node:e,flow:t}){let[n,o]=L(""),{running:r,run:s,maxRuns:a}=t.loop,c=async()=>{await vb(e,t,{running:!0,run:s>=a?0:s,maxRuns:a});let u=t.steps.find((p)=>wb(R.value.get(p.nodeId)?.data)!=="done"),d=u??t.steps[t.steps.length-1];await zn(e,"ax.work.update",{id:d.workItemId,status:u?"in-progress":"done"},"Loop running")},l=async()=>{let u=n.trim();if(!u)return;await zn(e,"ax.steer",{message:u},"Steering sent"),o("")};return i("div",{class:"ax-flow-controls",style:{...yb,marginTop:"6px",rowGap:"4px"},children:[i("span",{class:"ax-flow-runs",style:xb,children:r?`Loop running · run ${s+1}/${a}`:`Loop idle · ${s}/${a} runs`},void 0,!1,void 0,this),r?i("button",{type:"button",class:"ax-node-action",style:bb,title:"Stop the loop now. The stop is persisted on this node, so it survives a refresh and no further step is opened.",onClick:(u)=>{u.stopPropagation(),vb(e,t,{...t.loop,running:!1})},children:"Stop"},void 0,!1,void 0,this):i("button",{type:"button",class:"ax-node-action",style:ao,title:"Run this flow as a loop: each completed step opens the next one, and the last step starts the next run — until the run cap is reached or you press Stop.",onClick:(u)=>{u.stopPropagation(),c()},children:"Run loop"},void 0,!1,void 0,this),i("input",{class:"ax-flow-steer-input",value:n,placeholder:"Steer the agent…","aria-label":"Steer the agent",onInput:(u)=>o(u.target.value),onClick:(u)=>u.stopPropagation(),onKeyDown:(u)=>{if(u.key!=="Enter")return;u.stopPropagation(),l()},style:{flex:"1 1 120px",minWidth:"90px",fontSize:"10px",padding:"3px 6px",borderRadius:"4px",border:"1px solid var(--c-line)",background:"var(--c-panel-overlay)",color:"var(--c-text)"}},void 0,!1,void 0,this),i("button",{type:"button",class:"ax-node-action",style:ao,title:"Send a steering message to the agent working this flow.",onClick:(u)=>{u.stopPropagation(),l()},children:"Steer"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nc({node:e}){let t=hb(e.data);if(!t)return null;let n=gb(e.data),o=wb(e.data);return i("div",{class:"ax-step-dock",style:BE,children:[i("div",{class:"ax-step-controls",style:yb,children:[i("span",{class:"ax-step-position",style:xb,children:["Step ",t.index,"/",t.total]},void 0,!0,void 0,this),UE.map((r)=>i("button",{type:"button",class:"ax-node-action","aria-pressed":o===r.status,style:o===r.status?bb:ao,title:`Set this step's work item to "${r.status}".`,onClick:(s)=>{s.stopPropagation(),zn(e,"ax.work.update",{id:t.workItemId,status:r.status},r.toast)},children:r.label},r.status,!1,void 0,this))]},void 0,!0,void 0,this),n&&i(WE,{node:e,flow:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Sr=8,Eo=V(null),kr=[],Cr=[],kb=null;function _b(e){let t=e?.data.parentGroup;return typeof t==="string"&&t.length>0?t:null}function Sb(e){if(!e||!Array.isArray(e.data.children))return[];return e.data.children.filter((t)=>typeof t==="string")}function qE(e,t){let n=new Map(t.map((c)=>[c.id,c])),o=new Set([e]),r=n.get(e);if(!r)return o;let s=_b(r);while(s&&!o.has(s))o.add(s),s=_b(n.get(s));if(r.type!=="group")return o;let a=[...Sb(r)];while(a.length>0){let c=a.pop();if(!c||o.has(c))continue;o.add(c);let l=n.get(c);if(l?.type==="group")a.push(...Sb(l))}return o}function Cb(e,t){kr=[],Cr=[],kb=e;let n=Array.from(t),o=qE(e,n);for(let r of n){if(o.has(r.id))continue;let s=r.position.x,a=r.position.x+r.size.width,c=r.position.x+r.size.width/2,l=r.position.y,u=r.position.y+r.size.height,d=r.position.y+r.size.height/2;kr.push({val:s,minY:l,maxY:u}),kr.push({val:a,minY:l,maxY:u}),kr.push({val:c,minY:l,maxY:u}),Cr.push({val:l,minX:s,maxX:a}),Cr.push({val:u,minX:s,maxX:a}),Cr.push({val:d,minX:s,maxX:a})}}function Tb(){kr=[],Cr=[],kb=null}function Eb(e,t,n,o){let r=[e,e+n/2,e+n],s=[t,t+o/2,t+o],a=[0,n/2,n],c=[0,o/2,o],l=null,u=Sr+1,d=null;for(let y=0;y<3;y++){let x=r[y];for(let h of kr){let v=Math.abs(x-h.val);if(v<u)u=v,l=h.val-a[y],d={axis:"x",pos:h.val,from:Math.min(h.minY,t),to:Math.max(h.maxY,t+o)}}}let p=null,m=Sr+1,f=null;for(let y=0;y<3;y++){let x=s[y];for(let h of Cr){let v=Math.abs(x-h.val);if(v<m)m=v,p=h.val-c[y],f={axis:"y",pos:h.val,from:Math.min(h.minX,e),to:Math.max(h.maxX,e+n)}}}let g=[];if(d&&u<=Sr)g.push(d);if(f&&m<=Sr)g.push(f);return{x:l!==null&&u<=Sr?l:e,y:p!==null&&m<=Sr?p:t,guides:g}}function Ib({nodeId:e,viewport:t,onMove:n,onDragEnd:o}){let r=M(!1),s=M({x:0,y:0}),a=M({x:0,y:0});return O((l,u,d)=>{l.stopPropagation(),l.preventDefault(),r.current=!0,document.documentElement.classList.add("is-node-dragging"),window.getSelection()?.removeAllRanges(),s.current={x:l.clientX,y:l.clientY},a.current={x:u,y:d};let p=null,m=null,f=()=>{if(m=null,!r.current||!p)return;let x=p;p=null;let h=t.value.scale,v=(x.x-s.current.x)/h,b=(x.y-s.current.y)/h;n(e,a.current.x+v,a.current.y+b)},g=(x)=>{if(!r.current)return;if(p={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(f)},y=()=>{if(m!==null)window.cancelAnimationFrame(m),f();r.current=!1,document.documentElement.classList.remove("is-node-dragging"),document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",y),document.removeEventListener("pointercancel",y),o()};document.addEventListener("pointermove",g),document.addEventListener("pointerup",y),document.addEventListener("pointercancel",y)},[e,t,n,o])}var VE=200,GE=100;function Ab({nodeId:e,viewport:t,onResize:n,onResizeEnd:o}){let r=M(!1),s=M({x:0,y:0}),a=M({w:0,h:0});return O((l,u,d)=>{l.stopPropagation(),l.preventDefault(),r.current=!0,s.current={x:l.clientX,y:l.clientY},a.current={w:u,h:d},document.documentElement.classList.add("is-node-resizing");let p=null,m=null,f=()=>{if(m=null,!r.current||!p)return;let x=p;p=null;let h=t.value.scale,v=(x.x-s.current.x)/h,b=(x.y-s.current.y)/h;n(e,Math.max(VE,a.current.w+v),Math.max(GE,a.current.h+b))},g=(x)=>{if(!r.current)return;if(p={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(f)},y=()=>{if(m!==null)window.cancelAnimationFrame(m),f();r.current=!1,document.documentElement.classList.remove("is-node-resizing"),document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",y),document.removeEventListener("pointercancel",y),o()};document.addEventListener("pointermove",g),document.addEventListener("pointerup",y),document.addEventListener("pointercancel",y)},[e,t,n,o])}var XE={ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1}};function KE(e,t,n){let o=e.position.x+e.size.width/2,r=e.position.y+e.size.height/2,s=null,a=Number.POSITIVE_INFINITY;for(let c of n){if(c.id===e.id)continue;let l=c.position.x+c.size.width/2-o,u=c.position.y+c.size.height/2-r,d=l*t.dx+u*t.dy;if(d<=0)continue;let p=Math.abs(l*t.dy)+Math.abs(u*t.dx);if(p>d)continue;let m=d+p*2;if(m<a)a=m,s=c}return s}var JE=0.4,YE=0.55,QE=175;function eI(e,t,n=0){if(!Number.isFinite(e)||e>=1)return 1;let r=Math.min(2.2,1/Math.max(e,0.01));if(Number.isFinite(t)&&t>0)r=Math.min(r,t*JE/rr);if(Number.isFinite(n)&&n>0)r=Math.min(r,n*YE/QE);return Math.max(1,r)}function zb({node:e,children:t,onContextMenu:n}){let o=ke.value===e.id,r=ye.value.has(e.id),s=Ee.value.has(e.id),a=Lo.value.has(e.id),c=!a&&Do.value.has(e.id),l=Qi.value.has(e.id),u=!o&&vf.value.has(e.id),d=Nn.value,p=d!==null&&d.has(e.id),m=d!==null&&!d.has(e.id),[f,g]=L(!1),y=M(null),x=O((N,se,Me)=>{let de=Eb(se,Me,e.size.width,e.size.height),Zt=R.value.get(N);if(Zt?.position.x===de.x&&Zt.position.y===de.y){Eo.value=de.guides.length>0?de.guides:null;return}et(N,{position:{x:de.x,y:de.y}}),Eo.value=de.guides.length>0?de.guides:null,wf(N)},[e.size.width,e.size.height]),h=M(null),v=O(()=>{if(Tb(),Eo.value=null,Rl(null),h.current)document.removeEventListener("keydown",h.current),h.current=null;nt();let N=ln.value;if(bf(),!N||N.nodeId!==e.id)return;if(N.mode==="add")Hc(N.groupId,[e.id]);else{let se=R.value.get(N.groupId),Me=Array.isArray(se?.data.children)?se.data.children.filter((de)=>typeof de==="string"&&de!==e.id):[];ls(N.groupId,Me)}},[e.id]),b=Ib({nodeId:e.id,viewport:re,onMove:x,onDragEnd:v}),z=O((N,se,Me)=>{let de=R.value.get(N);if(de?.size.width===se&&de.size.height===Me)return;et(N,{size:{width:se,height:Me}})},[]),F=O(()=>{oe(e.id,{userResized:!0}),it(e.id,{data:{userResized:!0}}),nt()},[e.id]),_=Ab({nodeId:e.id,viewport:re,onResize:z,onResizeEnd:F}),k=O((N)=>{N.stopPropagation(),N.preventDefault(),je.value={fromId:e.id,fromX:e.position.x+e.size.width/2,fromY:e.position.y+e.size.height/2,cursorX:e.position.x+e.size.width/2,cursorY:e.position.y+e.size.height/2,targetId:null}},[e.id,e.position.x,e.position.y,e.size.width,e.size.height]),T=O((N)=>{if(N.button!==0)return;if(f)return;if(yt.value==="connect"){k(N);return}if(N.shiftKey){N.stopPropagation(),el(e.id);return}if(fn(e.id),Rl(e.id),Rm(e.id,typeof e.data.title==="string"&&e.data.title?e.data.title:e.type),Cb(e.id,R.value.values()),e.type!=="group"){let se=(Me)=>{if(Me.key==="Escape")xf()};h.current=se,document.addEventListener("keydown",se)}b(N,e.position.x,e.position.y)},[e.id,e.type,e.data.title,e.position.x,e.position.y,b,f,k]),P=O((N)=>{if(N.button!==0)return;if(N.stopPropagation(),yt.value==="connect"){k(N);return}if(N.shiftKey){el(e.id);return}fn(e.id)},[e.id,k]),Z=O((N)=>{if((N.target instanceof Element?N.target:null)?.closest('button, input, textarea, select, a, [contenteditable="true"]'))return;if(n)n(N,e.id)},[n,e.id]),j=O((N)=>{let se=N.target;if(se&&se!==N.currentTarget&&se.closest('input, textarea, [contenteditable="true"]'))return;let Me=XE[N.key];if(Me){N.preventDefault();let de=KE(e,Me,R.value.values());if(!de)return;fn(de.id),requestAnimationFrame(()=>{document.querySelector(`.canvas-node[data-node-id="${CSS.escape(de.id)}"]`)?.focus()})}else if(N.key==="Enter"&&N.target===N.currentTarget&&Fr.has(e.type))N.preventDefault(),en(e.id)},[e]),E=e.data.title||(e.type==="file"?(e.data.path||e.data.content||"").split(/[\\/]/).pop()??"":"")||st[e.type],B=O((N)=>{let se=N.trim();if(se&&se!==E)oe(e.id,{title:se}),it(e.id,{title:se});g(!1)},[e.id,E]),W=M(null),H=M(!1),U=M(null);D(()=>{if(H.current||!$l(e))return;let N=W.current;if(!N)return;let se=new ResizeObserver(()=>{if(H.current){se.disconnect();return}let Me=N.scrollHeight,de=Dm(e,Me);if(de===null)return;if(Math.abs(de-e.size.height)>8){if(ks(e.id,{width:e.size.width,height:de}),U.current!==null)window.clearTimeout(U.current);U.current=window.setTimeout(()=>{nt({recordHistory:!1}),U.current=null},0)}H.current=!0,se.disconnect()});return se.observe(N),()=>{if(se.disconnect(),U.current!==null)window.clearTimeout(U.current),U.current=null}},[e.id,e.type,e.data.mode,e.data.strictSize,e.collapsed,e.size.width,e.size.height]);let ee=e.pinned,xe=e.type==="trace",Fe=xe&&e.data.status==="running",We=e.type==="group",Te=e.data.strictSize===!0,eo=Math.max(re.value.scale,0.01),jt=eI(eo,e.collapsed?0:e.size.height,e.size.width),Kt=We&&e.data.color?e.data.color:void 0,I={left:`${e.position.x}px`,top:`${e.position.y}px`,width:`${e.size.width}px`,height:e.collapsed?"auto":`${e.size.height}px`,zIndex:e.zIndex,"--node-chrome-scale":jt.toFixed(3),...Kt?{"--group-color":Kt}:{}},K=ft.value&&Qx.value.has(e.id),le=["canvas-node",o?"active":"",u?"neighbor":"",p?"search-match":"",m?"search-dimmed":"",r?"selected":"",s?"context-pinned":"",a?"attention-focus-primary":"",c?"attention-focus-secondary":"",l?"attention-pulse":"",ee?"pinned":"",xe?"trace-node":"",Fe?"trace-running":"",We?"group-node":"",Te?"strict-size":"",K?"agent-mutating":""].filter(Boolean).join(" "),Y=We?(Array.isArray(e.data.children)?e.data.children:[]).filter((N)=>typeof N==="string"&&R.value.has(N)):[],[J,Q]=L(!1),te=ln.value,q=We&&te?.groupId===e.id&&te.mode==="add",ae=We&&te?.groupId===e.id&&te.mode==="remove",mt=je.value?.targetId===e.id,kt=We?[...new Set(Y.map((N)=>R.value.get(N)?.type).filter((N)=>!!N))].slice(0,4):[];if(We&&e.collapsed)return i("div",{class:`${le} group-chip`,"data-node-type":e.type,style:{...I,width:"auto",height:"auto"},onPointerDown:P,onDblClick:Z,title:"Expand group","data-testid":"group-chip",children:i("div",{class:"node-titlebar group-chip-inner",onPointerDown:T,children:[i("button",{type:"button",class:"group-chip-expand","aria-label":`Expand group ${E}`,onClick:(N)=>{N.stopPropagation(),Ko(e.id)},children:"▸"},void 0,!1,void 0,this),i("div",{class:"group-chip-text",children:[i("div",{class:"group-chip-name",children:E},void 0,!1,void 0,this),i("div",{class:"group-chip-meta",children:[kt.map((N)=>i("span",{class:"group-kind-dot",style:{background:ec[N]},"aria-hidden":"true"},N,!1,void 0,this)),i("span",{class:"group-chip-count",children:[Y.length," node",Y.length===1?"":"s"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this);return i("div",{class:`${le}${q?" is-drop-target":""}${ae?" is-drop-source":""}${mt?" is-edge-target":""}${We&&J?" group-menu-open":""}`,"data-node-type":e.type,"data-node-id":e.id,style:I,tabIndex:o?0:-1,onKeyDown:j,onPointerDown:P,onMouseDown:(N)=>{if(N.shiftKey)N.preventDefault()},onDblClick:Z,children:[We&&i("div",{class:"node-titlebar group-edge-row",onPointerDown:T,children:[i("span",{class:"group-name-pill",children:[f?i("input",{ref:y,class:"node-title-input group-title-input",value:E,onBlur:(N)=>B(N.target.value),onKeyDown:(N)=>{if(N.key==="Enter")B(N.target.value);if(N.key==="Escape")g(!1)},onClick:(N)=>N.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"group-name",title:E,children:E},void 0,!1,void 0,this),i("span",{class:"group-count",children:Y.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"group-edge-spacer"},void 0,!1,void 0,this),i("span",{class:"group-actions",role:"toolbar","aria-label":`${E} actions`,children:[i("button",{type:"button",class:"group-action",title:"Auto-arrange children","aria-label":"Auto-arrange children",disabled:Y.length===0,onClick:(N)=>{N.stopPropagation(),Hc(e.id,Y,"grid")},children:i("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[i("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"group-action",title:"Collapse group","aria-label":"Collapse group",onClick:(N)=>{N.stopPropagation(),Ko(e.id)},children:i("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:i("path",{d:"M3 10 L8 5 L13 10"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"group-action",title:"Rename · Ungroup · Pin all to context","aria-label":"Group menu","aria-expanded":J,onClick:(N)=>{N.stopPropagation(),Q((se)=>!se)},children:"⋯"},void 0,!1,void 0,this),J&&i("div",{class:"group-menu",role:"menu",onPointerDown:(N)=>N.stopPropagation(),children:[i("button",{type:"button",role:"menuitem",onClick:(N)=>{N.stopPropagation(),Q(!1),g(!0),requestAnimationFrame(()=>y.current?.focus())},children:"Rename"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",onClick:(N)=>{N.stopPropagation(),Q(!1),It(e.id),Zo(e.id)},children:"Ungroup"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",disabled:Y.length===0,onClick:(N)=>{N.stopPropagation(),Q(!1),bs(Y)},children:"Pin all to context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!We&&i("div",{class:"node-titlebar",onPointerDown:T,children:[i("span",{class:"node-type-icon","aria-hidden":"true",children:(()=>{let N=yn(e.type);return i(N,{size:Math.round(14*jt)},void 0,!1,void 0,this)})()},void 0,!1,void 0,this),typeof e.data.axWorkStatus==="string"&&i("span",{class:`node-ax-status node-ax-status-${e.data.axWorkStatus}`,children:e.data.axWorkStatus},void 0,!1,void 0,this),f?i("input",{ref:y,class:"node-title-input",value:E,onBlur:(N)=>B(N.target.value),onKeyDown:(N)=>{if(N.key==="Enter")B(N.target.value);if(N.key==="Escape")g(!1)},onClick:(N)=>N.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"node-title",title:E,children:E},void 0,!1,void 0,this),i("div",{class:"node-controls",children:[ee&&i("span",{class:"pin-indicator",title:"Pinned",children:"⊙"},void 0,!1,void 0,this),i("button",{type:"button",class:`ctx-pin-btn${s?" ctx-pin-active":""}`,onClick:(N)=>{N.stopPropagation(),Rn(e.id)},title:s?"Remove from context":"Add to context",children:"✦"},void 0,!1,void 0,this),Fs(e)&&i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),js(e)},title:"Open as site",children:"↗"},void 0,!1,void 0,this),Fr.has(e.type)&&i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),en(e.id)},title:"Expand (focus mode)",children:"⤢"},void 0,!1,void 0,this),i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),Ko(e.id)},title:e.collapsed?"Expand":"Collapse",children:e.collapsed?"▸":"▾"},void 0,!1,void 0,this),i("button",{type:"button",onClick:(N)=>{N.stopPropagation(),It(e.id),In(e.id)},title:"Close",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&i("div",{ref:W,class:"node-body",children:[t,i(nc,{node:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&i("div",{class:"node-resize-handle",onPointerDown:(N)=>_(N,e.size.width,e.size.height)},void 0,!1,void 0,this),r&&["tl","tr","bl","br"].map((N)=>i("span",{class:`node-selection-handle is-${N}`,"aria-hidden":"true"},N,!1,void 0,this)),fo.value.has(e.id)&&i("span",{class:"node-yield-pill","data-testid":"yield-pill",children:[i("span",{class:"node-yield-dot","aria-hidden":"true"},void 0,!1,void 0,this),fo.value.get(e.id)," took over — agent yielded"]},void 0,!0,void 0,this),!We&&["top","right","bottom","left"].map((N)=>i("div",{class:`node-port node-port-${N}`,onPointerDown:(se)=>{se.stopPropagation(),se.preventDefault();let Me=e.position.x+e.size.width/2,de=e.position.y+e.size.height/2,Zt=e.size.width/2,Pi=e.size.height/2,Ht,Sn;switch(N){case"top":Ht=Me,Sn=de-Pi;break;case"bottom":Ht=Me,Sn=de+Pi;break;case"left":Ht=Me-Zt,Sn=de;break;case"right":Ht=Me+Zt,Sn=de;break}je.value={fromId:e.id,fromX:Ht,fromY:Sn,cursorX:Ht,cursorY:Sn}}},N,!1,void 0,this))]},void 0,!0,void 0,this)}var tI={relation:"var(--c-muted)","depends-on":"var(--c-warn)",flow:"var(--c-accent)",references:"var(--c-muted)"},nI=new Set(["depends-on","flow"]);function oI(e){if(!Number.isFinite(e)||e<=0)return 1;return e<1?1/e:1}function rI(e,t){let n=`${8*t} ${4*t}`;if(e.style==="dashed")return n;if(e.style==="dotted")return`${3*t} ${3*t}`;if(e.type==="references"&&!e.style)return n;return}function oc(e,t){let n=e.position.x+e.size.width/2,o=e.position.y+e.size.height/2,r=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=r-n,c=s-o,l=e.size.width/2,u=e.size.height/2,d=Math.abs(c/(a||0.001)),p=u/(l||0.001);if(d>p){let f=c>0?1:-1;return{x:n+u/d*(a>0?1:-1),y:o+u*f,side:f>0?"bottom":"top"}}let m=a>0?1:-1;return{x:n+l*m,y:o+d*l*(c>0?1:-1),side:m>0?"right":"left"}}function rc(e,t){switch(e.side){case"top":return{x:e.x,y:e.y-t};case"bottom":return{x:e.x,y:e.y+t};case"left":return{x:e.x-t,y:e.y};case"right":return{x:e.x+t,y:e.y}}}function iI(e,t,n,o,r,s,a,c){return{x:0.125*e+0.375*n+0.375*r+0.125*a,y:0.125*t+0.375*o+0.375*s+0.125*c}}function sI({edge:e,fromNode:t,toNode:n,focused:o,dimmed:r,selected:s,scale:a,onContextMenu:c}){let l=oc(t,n),u=oc(n,t),d=u.x-l.x,p=u.y-l.y,m=Math.sqrt(d*d+p*p),f=Math.min(Math.max(m*0.35,32),160),g=rc(l,f),y=rc(u,f),x=`M ${l.x} ${l.y} C ${g.x} ${g.y}, ${y.x} ${y.y}, ${u.x} ${u.y}`,h=tI[e.type],v=nI.has(e.type),b=rI(e,a),z=Math.min(a,2.2),F=e.label&&a<=3.4?iI(l.x,l.y,g.x,g.y,y.x,y.y,u.x,u.y):null,_=`edge-path-${e.id}`;return i("g",{children:[i("path",{d:x,fill:"none",stroke:"transparent","stroke-width":12*a,style:{cursor:"pointer",pointerEvents:"stroke"},onClick:(k)=>{k.stopPropagation(),un.value=e.id},onDblClick:c?(k)=>c(k,e.id):void 0},void 0,!1,void 0,this),(o||s)&&i("path",{d:x,fill:"none",stroke:h,"stroke-width":6*a,"stroke-dasharray":b,opacity:s?0.3:0.15,style:{filter:"blur(3px)"}},void 0,!1,void 0,this),i("path",{id:_,d:x,class:s?"edge-selected":void 0,fill:"none",stroke:h,"stroke-width":(s?3:o?2.5:1.5)*a,"stroke-dasharray":b,"marker-end":v?"url(#edge-arrow)":void 0,opacity:s?1:r?0.2:o?1:0.85,style:{transition:"opacity 0.2s, stroke-width 0.2s"}},void 0,!1,void 0,this),e.animated&&i("circle",{r:3*a,fill:h,opacity:"0.9",children:i("animateMotion",{dur:"2s",repeatCount:"indefinite",children:i("mpath",{href:`#${_}`},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),F&&e.label&&i("g",{transform:`translate(${F.x}, ${F.y})`,children:[i("rect",{class:"edge-label-bg",x:-(e.label.length*3.5+8)*z,y:-10*z,width:(e.label.length*7+16)*z,height:20*z,rx:4*z},void 0,!1,void 0,this),i("text",{class:"edge-label","text-anchor":"middle","dominant-baseline":"central",fill:"var(--c-text)",children:e.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Pb({nodes:e,edges:t,onEdgeContextMenu:n}){let o=e.value,r=Array.from(t.value.values()),s=ke.value,a=s!==null,c=Nn.value,l=c!==null,u=oI(re.value.scale);if(r.length===0&&!je.value)return null;let d=96,p=Array.from(o.values());if(p.length===0)return null;let m=Math.min(...p.map((v)=>v.position.x))-d,f=Math.min(...p.map((v)=>v.position.y))-d,g=Math.max(...p.map((v)=>v.position.x+v.size.width))+d,y=Math.max(...p.map((v)=>v.position.y+v.size.height))+d,x=Math.max(1,g-m),h=Math.max(1,y-f);return i("svg",{"aria-label":"Canvas connections",role:"img",viewBox:`${m} ${f} ${x} ${h}`,width:x,height:h,style:{position:"absolute",top:`${f}px`,left:`${m}px`,pointerEvents:"none",overflow:"visible","--edge-chrome-scale":u.toFixed(3),"--edge-label-scale":Math.min(u,2.2).toFixed(3)},children:[i("title",{children:"Canvas connections"},void 0,!1,void 0,this),i("defs",{children:i("marker",{id:"edge-arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerUnits:"userSpaceOnUse",markerWidth:8*Math.min(u,2.2),markerHeight:8*Math.min(u,2.2),orient:"auto-start-reverse",children:i("path",{d:"M 0 1 L 10 5 L 0 9 z",fill:"currentColor",opacity:"0.75"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r.map((v)=>{let b=xs(v.from),z=xs(v.to);if(!b||!z||b.id===z.id)return null;let F=a&&(v.from===s||v.to===s),_=l&&!(c.has(v.from)||c.has(v.to));return i(sI,{edge:v,fromNode:b,toNode:z,focused:F,dimmed:a&&!F||_,selected:un.value===v.id,scale:u,onContextMenu:n},v.id,!1,void 0,this)}),je.value&&(()=>{let v=je.value,b=xs(v.fromId),z={position:{x:v.cursorX,y:v.cursorY},size:{width:1,height:1}},F;if(b){let _=oc(b,z),k=oc(z,b),T=k.x-_.x,P=k.y-_.y,Z=Math.sqrt(T*T+P*P),j=Math.min(Math.max(Z*0.35,32),160),E=rc(_,j),B=rc(k,j);F=`M ${_.x} ${_.y} C ${E.x} ${E.y}, ${B.x} ${B.y}, ${k.x} ${k.y}`}else{let _=v.cursorX-v.fromX,k=v.cursorY-v.fromY,T=Math.sqrt(_*_+k*k),P=Math.min(T*0.25,80),Z=_/(T||1),j=k/(T||1);F=`M ${v.fromX} ${v.fromY} C ${v.fromX+Z*P} ${v.fromY+j*P}, ${v.cursorX-Z*P} ${v.cursorY-j*P}, ${v.cursorX} ${v.cursorY}`}return i("g",{children:[i("path",{d:F,fill:"none",stroke:"var(--c-accent)","stroke-width":6*u,opacity:"0.1",style:{filter:"blur(3px)"}},void 0,!1,void 0,this),i("path",{d:F,fill:"none",stroke:"var(--c-accent)","stroke-width":2*u,"stroke-dasharray":`${6*u} ${4*u}`,opacity:"0.8"},void 0,!1,void 0,this),i("circle",{cx:v.cursorX,cy:v.cursorY,r:5*u,fill:"var(--c-accent)",opacity:"0.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})()]},void 0,!0,void 0,this)}function aI(e){let[t,...n]=e;if(!t)return"";return n.reduce((o,r)=>`${o} L ${r.x} ${r.y}`,`M ${t.x} ${t.y}`)}function Cd({annotations:e}){if(e.length===0)return null;return i("svg",{class:"annotation-layer","aria-hidden":"true",children:e.map((t)=>{let n=t.color==="currentColor"?"var(--c-annotation)":t.color;if(t.type==="text"){let o=t.points[0];if(!o||!t.text)return null;return i("text",{x:o.x,y:o.y,fill:n,"font-size":t.width,"font-family":"var(--font)","font-weight":"700",opacity:"0.95",children:t.text},t.id,!1,void 0,this)}return i("path",{d:aI(t.points),fill:"none",stroke:n,"stroke-width":t.width,"stroke-linecap":"round","stroke-linejoin":"round",opacity:"0.9"},t.id,!1,void 0,this)})},void 0,!1,void 0,this)}var cI=0.1,lI=4,Nb=1;function Rb(e){return Math.min(lI,Math.max(cI,e))}function $b({viewport:e,onViewportChange:t,onViewportCommit:n,disabled:o=!1}){let r=M(null),s=M(!1),a=M({x:0,y:0}),c=M(0),l=M(null),u=O((h)=>{if(l.current!==null)window.clearTimeout(l.current);l.current=window.setTimeout(()=>{l.current=null,n(h)},140)},[n]);function d(h){if(h.deltaMode!==0)return h.deltaX===0;return h.deltaX===0&&Number.isInteger(h.deltaY)&&Math.abs(h.deltaY)>=50}let p=O((h)=>{if(o)return;h.preventDefault();let v=e.value;if(h.ctrlKey||h.metaKey||d(h)){let b=r.current?.getBoundingClientRect();if(!b)return;let z=h.clientX-b.left,F=h.clientY-b.top,_=-h.deltaY*0.002,k=Rb(v.scale*(1+_)),T=k/v.scale,P={x:z-T*(z-v.x),y:F-T*(F-v.y),scale:k};t(P),u(P)}else{let b={x:v.x-h.deltaX*Nb,y:v.y-h.deltaY*Nb,scale:v.scale};t(b),u(b)}},[o,e,t,u]),m=O((h)=>{if(o)return;let v=r.current;if(!v)return;if(h.button===1||h.button===2)h.preventDefault();else if(Xo()){if(h.target!==v)return;h.preventDefault()}else return;s.current=!0,document.documentElement.classList.add("is-canvas-panning"),a.current={x:h.clientX,y:h.clientY},v.setPointerCapture(h.pointerId)},[o]),f=O((h)=>{if(!s.current)return;if(o)return;let v=h.clientX-a.current.x,b=h.clientY-a.current.y;a.current={x:h.clientX,y:h.clientY};let z=e.value;t({x:z.x+v,y:z.y+b,scale:z.scale})},[o,e,t]),g=O(()=>{if(s.current)n(e.value);s.current=!1,document.documentElement.classList.remove("is-canvas-panning")},[n,e]),y=O((h)=>{if(o)return;if(h.touches.length!==2){c.current=0;return}h.preventDefault();let v=h.touches[0],b=h.touches[1],z=Math.hypot(b.clientX-v.clientX,b.clientY-v.clientY),F=(v.clientX+b.clientX)/2,_=(v.clientY+b.clientY)/2;if(c.current>0){let k=e.value,T=r.current?.getBoundingClientRect();if(!T)return;let P=F-T.left,Z=_-T.top,j=z/c.current,E=Rb(k.scale*j),B=E/k.scale,W={x:P-B*(P-k.x),y:Z-B*(Z-k.y),scale:E};t(W),u(W)}c.current=z},[o,e,t,u]),x=O(()=>{if(l.current!==null)window.clearTimeout(l.current),l.current=null;n(e.value),c.current=0},[n,e]);return D(()=>{let h=r.current;if(!h)return;return h.addEventListener("wheel",p,{passive:!1}),h.addEventListener("pointerdown",m),h.addEventListener("pointermove",f),h.addEventListener("pointerup",g),h.addEventListener("pointercancel",g),h.addEventListener("lostpointercapture",g),h.addEventListener("touchmove",y,{passive:!1}),h.addEventListener("touchend",x),()=>{if(l.current!==null)window.clearTimeout(l.current);h.removeEventListener("wheel",p),h.removeEventListener("pointerdown",m),h.removeEventListener("pointermove",f),h.removeEventListener("pointerup",g),h.removeEventListener("pointercancel",g),h.removeEventListener("lostpointercapture",g),h.removeEventListener("touchmove",y),h.removeEventListener("touchend",x)}},[p,m,f,g,y,x]),D(()=>()=>{document.documentElement.classList.remove("is-canvas-panning")},[]),r}function uI(e){switch(e.type){case"markdown":return i(Ms,{node:e},void 0,!1,void 0,this);case"mcp-app":return i(Hn,{node:e},void 0,!1,void 0,this);case"webpage":return i(Da,{node:e},void 0,!1,void 0,this);case"json-render":return i(Hn,{node:e},void 0,!1,void 0,this);case"graph":return i(Hn,{node:e},void 0,!1,void 0,this);case"prompt":return i(Fa,{node:e},void 0,!1,void 0,this);case"response":return i(ja,{node:e},void 0,!1,void 0,this);case"status":return i(Oa,{node:e},void 0,!1,void 0,this);case"context":return i(gs,{node:e},void 0,!1,void 0,this);case"ledger":return i(As,{node:e},void 0,!1,void 0,this);case"trace":return i(Za,{node:e},void 0,!1,void 0,this);case"file":return i(Is,{node:e},void 0,!1,void 0,this);case"diff":return i(vs,{node:e},void 0,!1,void 0,this);case"mermaid":return i(Xs,{node:e},void 0,!1,void 0,this);case"image":return i(La,{node:e},void 0,!1,void 0,this);case"html":return i(wi,{node:e},void 0,!1,void 0,this);case"group":return i(xx,{node:e},void 0,!1,void 0,this);default:return i("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function dI(e,t,n){let o=n.x-t.x,r=n.y-t.y,s=o*o+r*r;if(s===0)return Math.hypot(e.x-t.x,e.y-t.y);let a=Math.max(0,Math.min(1,((e.x-t.x)*o+(e.y-t.y)*r)/s));return Math.hypot(e.x-(t.x+a*o),e.y-(t.y+a*r))}function pI(e,t,n){for(let o=e.length-1;o>=0;o--){let r=e[o];if(!r)continue;let s=n+r.width;if(t.x<r.bounds.x-s||t.x>r.bounds.x+r.bounds.width+s||t.y<r.bounds.y-s||t.y>r.bounds.y+r.bounds.height+s)continue;if(r.type==="text")return r;for(let a=1;a<r.points.length;a++){let c=r.points[a-1],l=r.points[a];if(c&&l&&dI(t,c,l)<=n+r.width/2)return r}}return null}var Td="currentColor",Mb=4,Ob=24,fI=14,Lb={width:520,height:420};function mI(e){let t=e.trim();if(!t||/\s/.test(t))return null;let n=/^[a-z][a-z0-9+.-]*:/i.test(t)?t:`https://${t}`;try{let o=new URL(n);if(o.protocol!=="http:"&&o.protocol!=="https:")return null;return o.toString()}catch{return null}}function Id(e){let t=e.trim();if(!t)return[];let n=t.includes(`
314
+ `)?t.split(/\r?\n/):t.split(/\s+/),o=new Set,r=[];for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let c=mI(a);if(!c||o.has(c))continue;o.add(c),r.push(c)}return r}function hI(e){let t=Id(e.getData("text/uri-list"));if(t.length>0)return t;return Id(e.getData("text/plain"))}function gI(e){if(!e)return!1;return e.types.includes("text/uri-list")||e.types.includes("text/plain")}function Ed(e){if(!(e instanceof HTMLElement))return!1;return Boolean(e.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}function vI(e,t,n=new Set){let o=[],r=0;for(let s of e){if(n.has(s.id))continue;if(t&&s.id===t)continue;if(s.type==="group")o.splice(r++,0,s);else o.push(s)}return o}function Db({onNodeContextMenu:e,onEdgeContextMenu:t,onCanvasContextMenu:n,annotationMode:o=!1,annotationTool:r=null}){let s=re.value,a=M(!1),c=M(null),l=M(!1),u=M([]),[d,p]=L(null),[m,f]=L(null),[g,y]=L(null),x=M(null),[h,v]=L(!1),b=M(0),z=M(null),F=M(null);D(()=>{let I=null,K=Mt(()=>{re.value;let le=F.current;if(!le)return;if(le.style.willChange="transform",I)clearTimeout(I);I=setTimeout(()=>{le.style.willChange="auto"},180)});return()=>{if(I)clearTimeout(I);K()}},[]);let _=$b({viewport:re,disabled:o,onViewportChange:(I)=>{if(a.current||o)return;Yo(),Af(I)},onViewportCommit:(I)=>{if(a.current||o)return;Yo(),Pf(I)}}),k=O((I)=>{x.current=I,y(I)},[]),T=O(async(I,K,le)=>{if(I.length===0)return;let{width:Y,height:J}=Lb,Q=24,te=Math.ceil(Math.sqrt(I.length)),q=Math.ceil(I.length/te),ae=te*Y+Math.max(0,te-1)*Q,mt=q*J+Math.max(0,q-1)*Q;for(let kt=0;kt<I.length;kt++){let N=kt%te,se=Math.floor(kt/te),Me=K-ae/2+N*(Y+Q),de=le-mt/2+se*(J+Q);await Ut({type:"webpage",content:I[kt],x:Me,y:de,width:Y,height:J})}},[]),P=O((I)=>{let K=_.current;if(!K)return;if(r==="eraser"){if((I.target instanceof Element?I.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;I.preventDefault(),I.stopPropagation();let q=K.getBoundingClientRect(),ae=re.value,mt={x:(I.clientX-q.left-ae.x)/ae.scale,y:(I.clientY-q.top-ae.y)/ae.scale},kt=pI(Array.from(Vo.value.values()),mt,fI/ae.scale);if(kt)If(kt.id);return}if(r==="text"){if((I.target instanceof Element?I.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;I.preventDefault(),I.stopPropagation(),ke.value=null,ht();let q=K.getBoundingClientRect(),ae=re.value;k({x:(I.clientX-q.left-ae.x)/ae.scale,y:(I.clientY-q.top-ae.y)/ae.scale,value:""});return}if(r==="pen"){if((I.target instanceof Element?I.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;I.preventDefault(),I.stopPropagation(),ke.value=null,ht(),l.current=!0;let q=K.getBoundingClientRect(),ae=re.value,mt={x:(I.clientX-q.left-ae.x)/ae.scale,y:(I.clientY-q.top-ae.y)/ae.scale};u.current=[mt],f({id:"draft-annotation",type:"freehand",points:[mt],bounds:{x:0,y:0,width:0,height:0},color:Td,width:Mb,createdAt:""}),K.setPointerCapture(I.pointerId);return}if(I.target!==K)return;if(Xo()||I.button===1||I.button===2){if(!I.shiftKey&&!z.current)ke.value=null,ht();return}I.preventDefault(),I.stopPropagation(),a.current=!0;let le=K.getBoundingClientRect(),Y=I.clientX-le.left,J=I.clientY-le.top,Q={startX:Y,startY:J,currentX:Y,currentY:J};z.current=Q,p(Q),K.setPointerCapture(I.pointerId)},[r,_]);D(()=>Mt(()=>{let I=re.value,K=c.current,le=_.current;if(!K||!le)return;let Y=le.getBoundingClientRect();qs({x:(K.x-Y.left-I.x)/I.scale,y:(K.y-Y.top-I.y)/I.scale})}),[]);let Z=O((I)=>{{let Y=_.current;if(Y){c.current={x:I.clientX,y:I.clientY};let J=Y.getBoundingClientRect(),Q=re.value;qs({x:(I.clientX-J.left-Q.x)/Q.scale,y:(I.clientY-J.top-Q.y)/Q.scale})}}if(l.current){let Y=_.current;if(!Y)return;let J=Y.getBoundingClientRect(),Q=re.value,te={x:(I.clientX-J.left-Q.x)/Q.scale,y:(I.clientY-J.top-Q.y)/Q.scale},q=u.current.at(-1);if(q&&Math.hypot(te.x-q.x,te.y-q.y)<2)return;u.current=[...u.current,te],f((ae)=>ae?{...ae,points:u.current}:null);return}if(!a.current||!z.current)return;let K=_.current?.getBoundingClientRect();if(!K)return;let le={...z.current,currentX:I.clientX-K.left,currentY:I.clientY-K.top};z.current=le,p(le)},[_]),j=O((I)=>{if(l.current){l.current=!1;let te=u.current;if(u.current=[],f(null),te.length>=2)il({points:te,color:Td,width:Mb});let q=_.current;if(q?.hasPointerCapture(I.pointerId))q.releasePointerCapture(I.pointerId);return}let K=z.current;if(!a.current||!K)return;a.current=!1,z.current=null;let le=Math.min(K.startX,K.currentX),Y=Math.max(K.startX,K.currentX),J=Math.min(K.startY,K.currentY),Q=Math.max(K.startY,K.currentY);if(Y-le<=5&&Q-J<=5)ke.value=null,ht();if(Y-le>5||Q-J>5){let te=re.value,q=(le-te.x)/te.scale,ae=(Y-te.x)/te.scale,mt=(J-te.y)/te.scale,kt=(Q-te.y)/te.scale,N=[];for(let se of R.value.values()){let Me=se.position.x,de=se.position.y;if(Me+se.size.width>q&&Me<ae&&de+se.size.height>mt&&de<kt)N.push(se.id)}if(N.length>0)yf(N)}p(null)},[]);D(()=>{if(o)return;if(!l.current&&!m&&!g)return;l.current=!1,u.current=[],f(null),k(null)},[o,m,k,g]);let E=O(()=>{let I=x.current;if(!I)return;let K=I.value.trim();if(k(null),!K)return;let le={x:I.x,y:I.y};il({type:"text",points:[le],color:Td,width:Ob,text:K})},[k]);D(()=>{if(r!=="text"&&g)k(null)},[r,k,g]),D(()=>{let I=(J,Q,te)=>{let q=null;for(let ae of R.value.values()){if(ae.id===te||ae.type==="group")continue;if(J>=ae.position.x&&J<=ae.position.x+ae.size.width&&Q>=ae.position.y&&Q<=ae.position.y+ae.size.height)q=ae.id}return q};function K(J){if(!je.value)return;let Q=_.current;if(!Q)return;let te=Q.getBoundingClientRect(),q=re.value,ae=(J.clientX-te.left-q.x)/q.scale,mt=(J.clientY-te.top-q.y)/q.scale;je.value={...je.value,cursorX:ae,cursorY:mt,targetId:I(ae,mt,je.value.fromId)}}function le(){let J=je.value;if(!J)return;je.value=null;let Q=J.targetId;if(!Q)return;if(J.withLabel){Yt("Edge label","label text").then((te)=>{so(J.fromId,Q,"relation",te??void 0)});return}so(J.fromId,Q,"relation",void 0)}function Y(J){let Q=je.value;if(!Q)return;if(J.key==="Escape")J.preventDefault(),je.value=null;else if(J.key==="l"||J.key==="L")J.preventDefault(),je.value={...Q,withLabel:!Q.withLabel}}return document.addEventListener("pointermove",K),document.addEventListener("pointerup",le),document.addEventListener("keydown",Y),()=>{document.removeEventListener("pointermove",K),document.removeEventListener("pointerup",le),document.removeEventListener("keydown",Y)}},[_]);let B=O((I)=>{if(o)return;let K=_.current;if(!K||I.target!==K||!n)return;let le=K.getBoundingClientRect(),Y=re.value,J=(I.clientX-le.left-Y.x)/Y.scale,Q=(I.clientY-le.top-Y.y)/Y.scale;n(I,J,Q)},[o,_,n]),W=O((I)=>{I.preventDefault()},[]),H=O((I)=>{if(Ed(I.target instanceof Element?I.target:null))return;I.preventDefault()},[]),U=O((I)=>{if(I.preventDefault(),b.current++,I.dataTransfer?.types.includes("Files")||gI(I.dataTransfer))v(!0)},[]),ee=O((I)=>{if(I.preventDefault(),I.dataTransfer)I.dataTransfer.dropEffect="copy"},[]),xe=O((I)=>{if(I.preventDefault(),b.current--,b.current<=0)b.current=0,v(!1)},[]),Fe=O(async(I)=>{I.preventDefault(),v(!1),b.current=0;let K=_.current;if(!K||!I.dataTransfer)return;let le=K.getBoundingClientRect(),Y=re.value,J=(I.clientX-le.left-Y.x)/Y.scale,Q=(I.clientY-le.top-Y.y)/Y.scale,te=Array.from(I.dataTransfer.files);if(te.length===0){let q=hI(I.dataTransfer);await T(q,J,Q);return}await Ha(te,J,Q)},[_,T]);D(()=>{let I=async(K)=>{if(K.defaultPrevented)return;if(Ed(K.target instanceof Element?K.target:null))return;if(Ed(document.activeElement))return;let le=K.clipboardData?.getData("text/plain")??"",Y=Id(le);if(Y.length===0)return;let J=_.current;if(!J)return;K.preventDefault();let Q=J.getBoundingClientRect(),te=re.value,q=(Q.width/2-te.x)/te.scale,ae=(Q.height/2-te.y)/te.scale;await T(Y,q,ae)};return document.addEventListener("paste",I),()=>{document.removeEventListener("paste",I)}},[_,T]);let We=vI(R.value.values(),Be.value,new Set(nl.value.keys())),Te=ln.value,eo=Te?R.value.get(Te.groupId):void 0,jt=Te?R.value.get(Te.nodeId):void 0,Kt=null;if(d){let I=Math.min(d.startX,d.currentX),K=Math.min(d.startY,d.currentY),le=Math.abs(d.currentX-d.startX),Y=Math.abs(d.currentY-d.startY);Kt={position:"absolute",left:`${I}px`,top:`${K}px`,width:`${le}px`,height:`${Y}px`,pointerEvents:"none"}}return i("div",{class:`canvas-viewport${Xo()?" pan-mode":""}`,ref:_,tabIndex:0,onPointerDown:P,onPointerMove:Z,onPointerLeave:()=>{c.current=null,qs(null)},onPointerUp:j,onContextMenu:W,onDblClick:B,onDragStart:H,onDragEnter:U,onDragOver:ee,onDragLeave:xe,onDrop:Fe,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden",cursor:r==="eraser"?"cell":r==="text"?"text":o||je.value||a.current||yt.value==="connect"?"crosshair":Xo()?"grab":"default"},children:[i("div",{ref:F,class:"canvas-world",style:{transform:`matrix(${s.scale}, 0, 0, ${s.scale}, ${s.x}, ${s.y})`,transformOrigin:"0 0",position:"absolute",top:0,left:0},children:[i(Ex,{},void 0,!1,void 0,this),i(mb,{},void 0,!1,void 0,this),i(Wx,{},void 0,!1,void 0,this),i(eb,{},void 0,!1,void 0,this),i(tb,{},void 0,!1,void 0,this),i(Pb,{nodes:R,edges:Re,onEdgeContextMenu:t},void 0,!1,void 0,this),je.value&&i("div",{class:"edge-hint-pill","data-testid":"edge-hint",style:{left:`${je.value.cursorX+14}px`,top:`${je.value.cursorY+14}px`},children:[i("span",{class:"edge-hint-main",children:je.value.targetId?"release to connect":"drag onto a node"},void 0,!1,void 0,this),i("span",{class:"edge-hint-keys",children:["esc cancels · L labels",je.value.withLabel?" · label on":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Te&&eo&&jt&&i("div",{class:"drop-pill","data-testid":"drop-pill",style:{left:`${jt.position.x}px`,top:`${jt.position.y+jt.size.height+10}px`},children:[i("span",{class:"drop-pill-text",children:Te.mode==="add"?`release to add to ${String(eo.data.title??"group")}`:`release to remove from ${String(eo.data.title??"group")}`},void 0,!1,void 0,this),i("span",{class:"drop-pill-hint",children:Te.mode==="add"?"esc keeps it out":"esc keeps it in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Cd,{annotations:Array.from(Vo.value.values())},void 0,!1,void 0,this),m&&m.points.length>=2&&i(Cd,{annotations:[m]},void 0,!1,void 0,this),We.map((I)=>i(zb,{node:I,onContextMenu:e,children:uI(I)},I.id,!1,void 0,this)),Eo.value&&i("svg",{class:"snap-guides-svg",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"visible"},children:Eo.value.map((I,K)=>I.axis==="x"?i("line",{x1:I.pos,y1:I.from-20,x2:I.pos,y2:I.to+20,class:"snap-guide-line"},K,!1,void 0,this):i("line",{x1:I.from-20,y1:I.pos,x2:I.to+20,y2:I.pos,class:"snap-guide-line"},K,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&i("div",{class:`annotation-capture-layer${r==="eraser"?" erasing":""}${r==="text"?" text":""}`,"aria-hidden":"true"},void 0,!1,void 0,this),g&&i("input",{class:"annotation-text-input",value:g.value,autoFocus:!0,style:{left:`${g.x*s.scale+s.x}px`,top:`${g.y*s.scale+s.y}px`,fontSize:`${Ob*s.scale}px`},onInput:(I)=>k({...g,value:I.target.value}),onBlur:E,onPointerDown:(I)=>I.stopPropagation(),onKeyDown:(I)=>{if(I.key==="Enter")I.preventDefault(),E();if(I.key==="Escape")I.preventDefault(),k(null)}},void 0,!1,void 0,this),Kt&&i("div",{class:"lasso-rect",style:Kt},void 0,!1,void 0,this),h&&i("div",{class:"drop-zone-overlay",children:i("div",{class:"drop-zone-indicator",children:[i("div",{class:"drop-zone-icon",children:"+"},void 0,!1,void 0,this),i("div",{class:"drop-zone-label",children:"Drop files or URLs to add to canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Fb(){let e=[...Ee.value],t=R.value,[n,o]=L(""),[r,s]=L(!1),a=Jx.value,[c,l]=L(null),u=a.length>=2,d=!u&&a.length===1&&a[0].steerable?a[0]:null,p=u?c?a.find((g)=>g.value===c&&g.steerable)??null:null:d,m=p?.value??null,f=async()=>{let g=n.trim();if(!g||r)return;s(!0);let y=await db(g,m);if(s(!1),y)o("")};return i("div",{class:"command-bar","data-testid":"command-bar",children:[e.length>0&&i("div",{class:"command-bar-chips","aria-label":"Pinned context",children:[e.map((g)=>{let y=t.get(g),x=typeof y?.data.title==="string"&&y.data.title.trim()?y.data.title:y?.type??g;return i("span",{class:"command-bar-chip","data-node-id":g,children:[i("span",{class:"command-bar-chip-glyph","aria-hidden":"true",children:"✦"},void 0,!1,void 0,this),i("span",{class:"command-bar-chip-label",title:x,children:x},void 0,!1,void 0,this),i("button",{type:"button",class:"command-bar-chip-unpin","aria-label":`Unpin ${x}`,title:"Remove from context",onClick:()=>Rn(g),children:"×"},void 0,!1,void 0,this)]},g,!0,void 0,this)}),i("span",{class:"command-bar-chips-note",children:"in agent context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"command-bar-composer",children:[i(br,{size:15,class:"command-bar-icon"},void 0,!1,void 0,this),u&&i("select",{class:"command-bar-target","aria-label":"Steer which agent",title:"Connected agents — steering reaches all of them unless you address one",value:m??"",onChange:(g)=>l(g.target.value||null),children:[i("option",{value:"",children:"All agents"},void 0,!1,void 0,this),a.map((g)=>{let y=g.pendingSteers&&g.pendingSteers>0?` · ${g.pendingSteers} queued`:"",x=g.polling?" · polling":"";return i("option",{value:g.value,disabled:!g.steerable,children:g.attached?`${g.label}${x}${y}`:g.steerable?`${g.label} · writer${x}${y}`:`${g.label} · no inbox`},g.value,!1,void 0,this)})]},void 0,!0,void 0,this),i("input",{class:"command-bar-input",type:"text",value:n,placeholder:`Steer ${p?.label??"the agent"}, or ${Ze("K")} to search the board…`,"aria-label":"Steer the agent",disabled:r,onInput:(g)=>o(g.target.value),onKeyDown:(g)=>{if(g.key==="Enter")g.preventDefault(),f()}},void 0,!1,void 0,this),i("button",{type:"button",class:"command-bar-send",disabled:r||!n.trim(),onClick:()=>void f(),children:r?"Sending…":"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Ad=Oe(()=>{if(Et.value==="disconnected")return"reconnecting";if(Et.value==="connected"&&!Gt.value&&co.value>1)return"resyncing";return null});function jb(){let e=Ad.value;if(!e)return null;if(e==="reconnecting"){let t=lo.value,n=uo.value;return i("div",{class:"connection-banner is-reconnecting",role:"status","data-testid":"connection-banner",children:[i("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"↻"},void 0,!1,void 0,this),i("span",{class:"connection-banner-text",children:[i("b",{children:"Reconnecting…"},void 0,!1,void 0,this)," live updates are paused; edits still save, the board may be stale until the stream returns."]},void 0,!0,void 0,this),i("span",{class:"connection-banner-meta",children:[t>0?`retry ${t}`:"retrying",n>0?` · ${Math.max(1,Math.round(n/1000))}s`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}return i("div",{class:"connection-banner is-resyncing",role:"status","data-testid":"connection-banner",children:[i("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"⟳"},void 0,!1,void 0,this),i("span",{class:"connection-banner-text",children:[i("b",{children:"Resyncing from snapshot"},void 0,!1,void 0,this)," — the event cursor went stale; the board reloads without losing local edits."]},void 0,!0,void 0,this),i("span",{class:"connection-banner-progress","aria-hidden":"true",children:i("span",{class:"connection-banner-progress-fill"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var yI={markdown:{width:520,height:360},group:{width:600,height:400},html:{width:720,height:640},image:{width:720,height:520},file:{width:720,height:600},webpage:{width:520,height:420}};async function Pt(e){if(e.x!==void 0&&e.y!==void 0)return Ut(e);let t=yI[e.type]??{width:360,height:200},n=e.width??t.width,o=e.height??t.height,r=Fo(),s=re.value,a=await Ut({...e,width:n,height:o,x:Math.round((r.x-s.x)/s.scale-n/2),y:Math.round((r.y-s.y)/s.scale-o/2)});if(a.ok&&a.id)tt(a.id);return a}var ic=!1,Zb=!1,Io=null,Tr=null;function zd(){return ic}function sc(){ic=!1,Zb=!0,Hb()}function Hb(){if(Io&&Tr)Io.removeEventListener("change",Tr);Io=null,Tr=null}function xI(){if(typeof window>"u"||!window.location)return null;let e=new URLSearchParams(window.location.search).get("theme");if(e==="auto")return"auto";return Yr(e)?e:null}function Bb(e){if(Zb)return;let t=xI();if(!t)return;if(Hb(),ic=!0,t!=="auto"){e(t);return}Io=window.matchMedia("(prefers-color-scheme: light)"),Tr=()=>{if(ic&&Io)e(Io.matches?"light":"dark")},Tr(),Io.addEventListener("change",Tr)}var bI='a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';function Er(e,t,n={}){D(()=>{if(!t)return;let o=e.current;if(!o)return;let r=document.activeElement,s=n.restoreTo,a=()=>Array.from(o.querySelectorAll(bI)),c=n.initial?.current??a()[0];if(c&&!o.contains(document.activeElement))c.focus();let l=(u)=>{if(u.key!=="Tab")return;let d=a();if(d.length===0)return;let p=d[0],m=d[d.length-1],f=document.activeElement;if(u.shiftKey&&(f===p||!o.contains(f)))u.preventDefault(),m.focus();else if(!u.shiftKey&&f===m)u.preventDefault(),p.focus()};return o.addEventListener("keydown",l),()=>{if(o.removeEventListener("keydown",l),s)requestAnimationFrame(()=>s()?.focus());else if(r&&document.contains(r)&&r!==document.body)r.focus()}},[e,t,n.initial,n.restoreTo])}function wI(e,t){let n=e.toLowerCase(),o=t.toLowerCase(),r=[],s=0,a=0,c=-1;for(let l=0;l<o.length&&s<n.length;l++)if(o[l]===n[s]){if(r.push(l),a+=c===l-1?10:1,l===0||o[l-1]===" "||o[l-1]==="-"||o[l-1]==="_")a+=5;c=l,s++}return{match:s===n.length,score:a,indices:r}}function _I(e,t){if(t.length===0)return e;let n=[],o=0;for(let r of t){if(r>o)n.push(e.slice(o,r));n.push(i("mark",{children:e[r]},r,!1,void 0,this)),o=r+1}if(o<e.length)n.push(e.slice(o));return n}var Pd={md:"markdown",app:"mcp-app",web:"webpage",ui:"json-render",chart:"graph",ctx:"context",log:"ledger"};function SI(e){let t=e.toLowerCase().trim();if(t.startsWith("type:")){let n=t.slice(5).trim(),r=Object.keys(st).find((a)=>a.startsWith(n));if(r)return{typeFilter:r,remaining:""};let s=Pd[n];if(s)return{typeFilter:s,remaining:""}}if(Pd[t])return{typeFilter:Pd[t],remaining:""};return{typeFilter:null,remaining:e}}function Ub({onClose:e,onToggleMinimap:t}){let[n,o]=L(""),[r,s]=L(0),a=M(null),c=M(null),l=M(null);Er(l,!0,{initial:a}),D(()=>{setTimeout(()=>a.current?.focus(),30)},[]);let u=O(()=>{let h=[];for(let b of R.value.values()){let z=b.data.title||st[b.type],F=b.data.content||b.data.path||"",_=b.type==="group"&&Array.isArray(b.data.children)?b.data.children.length:0;h.push({id:`node:${b.id}`,kind:"node",label:z,description:b.type==="group"?`group · ${_} node${_===1?"":"s"}`:F.length>60?`${st[b.type].toLowerCase()} · ${F.slice(0,60)}…`:F?`${st[b.type].toLowerCase()} · ${F}`:st[b.type].toLowerCase(),icon:yn(b.type),nodeType:b.type,action:()=>{tt(b.id),e()}})}let v=[{label:"New markdown note",shortcut:"M",icon:Bn,iconTone:"accent",action:()=>{Pt({type:"markdown",title:"New note",width:520,height:360}),e()}},...ft.value?[]:[{label:"Start agent session",icon:br,iconTone:"purple",action:()=>{Xn(),e()}}],{label:"Fit view",shortcut:"F",icon:Ua,iconTone:"muted",action:()=>{Qo(wt().width,wt().height),e()}},{label:"Auto-arrange (grid)",icon:So,iconTone:"muted",action:()=>{Cs(),e()}},{label:"Auto-arrange (graph-aware)",icon:So,iconTone:"muted",action:()=>{Ts(),e()}},{label:"Toggle minimap",icon:Wa,iconTone:"muted",action:()=>{t(),e()}},{label:"Toggle theme (dark/light)",icon:qa,iconTone:"muted",action:()=>{let b=Xe.value==="dark"?"light":"dark";sc(),document.documentElement.setAttribute("data-theme",b),vr(),Xe.value=b,is(b),e()}}];for(let b of v)h.push({id:`action:${b.label}`,kind:"action",label:b.label,...b.shortcut?{shortcut:b.shortcut}:{},icon:b.icon,...b.iconTone?{iconTone:b.iconTone}:{},action:b.action});return h},[e,t]),{typeFilter:d,remaining:p}=SI(n),m=u(),f;if(!n.trim())f=m.map((h)=>({...h,score:0,indices:[]}));else{f=[];for(let h of m){if(d){if(h.kind!=="node"||h.nodeType!==d)continue;if(!p){f.push({...h,score:0,indices:[]});continue}}let v=wI(p||n,h.label);if(v.match)f.push({...h,score:v.score,indices:v.indices})}f.sort((h,v)=>v.score-h.score)}f=[...f.filter((h)=>h.kind==="action"),...f.filter((h)=>h.kind==="node")];let g=f.findIndex((h)=>h.kind==="node");D(()=>{if(!n.trim()){Nn.value=null;return}let h=new Set;for(let v of f)if(v.kind==="node")h.add(v.id.slice(5));Nn.value=h.size>0?h:null},[n,f]),D(()=>()=>{Nn.value=null},[]);let y=Math.min(r,Math.max(0,f.length-1)),x=O((h)=>{if(h.key==="ArrowDown")h.preventDefault(),s((v)=>Math.min(v+1,f.length-1));else if(h.key==="ArrowUp")h.preventDefault(),s((v)=>Math.max(v-1,0));else if(h.key==="Enter"){if(h.preventDefault(),f[y])f[y].action()}else if(h.key==="Escape")h.preventDefault(),h.stopPropagation(),e()},[f,y,e]);return D(()=>{let h=c.current;if(!h)return;h.children[y]?.scrollIntoView({block:"nearest"})},[y]),D(()=>{s(0)},[n]),i("div",{class:"command-palette-backdrop",onMouseDown:e,children:i("div",{ref:l,class:"command-palette",role:"dialog","aria-modal":"true","aria-label":"Search and commands",onMouseDown:(h)=>h.stopPropagation(),children:[i("div",{class:"command-palette-search",children:[i("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),i("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("input",{ref:a,type:"text",class:"command-palette-input",value:n,onInput:(h)=>o(h.target.value),onKeyDown:x,placeholder:"Search nodes, run actions, jump to…","aria-label":"Search nodes, run actions, jump to"},void 0,!1,void 0,this),i("kbd",{class:"command-palette-esc",children:"esc"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"command-palette-results",ref:c,children:[f.length===0&&i("div",{class:"command-palette-empty",children:"No matching nodes or actions"},void 0,!1,void 0,this),f.map((h,v)=>{let b=h.icon,z=v===0&&h.kind==="action"?"Actions":v===g?"Jump to":null;return i("div",{class:"command-palette-row",children:[z&&i("div",{class:"command-palette-group",children:z},void 0,!1,void 0,this),i("button",{type:"button",class:`command-palette-item${v===y?" selected":""}`,onMouseEnter:()=>s(v),onClick:()=>h.action(),children:[i("span",{class:`command-palette-icon tone-${h.iconTone??"kind"}`,"aria-hidden":"true",children:i(b,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"command-palette-label",children:[h.indices.length>0?_I(h.label,h.indices):h.label,h.description&&i("span",{class:"command-palette-desc",children:[" — ",h.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h.shortcut&&i("kbd",{class:"command-palette-kbd",children:h.shortcut},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},h.id,!0,void 0,this)})]},void 0,!0,void 0,this),i("div",{class:"command-palette-hint",children:[i("span",{children:"↑↓ navigate"},void 0,!1,void 0,this),i("span",{children:"↵ open"},void 0,!1,void 0,this),i("span",{children:"esc close"},void 0,!1,void 0,this),i("span",{children:"type: filter"},void 0,!1,void 0,this),i("span",{class:"command-palette-hint-spacer"},void 0,!1,void 0,this),i("span",{children:Ze("K")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Wb(){let[e,t]=L(null),n=O((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"node",x:a.clientX,y:a.clientY,nodeId:c})},[]),o=O((a,c,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"canvas",x:a.clientX,y:a.clientY,canvasX:c,canvasY:l})},[]),r=O((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"edge",x:a.clientX,y:a.clientY,edgeId:c})},[]),s=O(()=>t(null),[]);return D(()=>{if(!e)return;let a=()=>t(null),c=(l)=>{if(l.key==="Escape")t(null)};return document.addEventListener("click",a),document.addEventListener("keydown",c),()=>{document.removeEventListener("click",a),document.removeEventListener("keydown",c)}},[e]),{menu:e,openNodeMenu:n,openCanvasMenu:o,openEdgeMenu:r,closeMenu:s}}var kI="#4bbcFF",CI=[{label:"Blue",value:"#3b82f6"},{label:"Green",value:"#22c55e"},{label:"Yellow",value:"#eab308"},{label:"Red",value:"#ef4444"},{label:"Gray",value:"#6b7280"},{label:"Purple",value:"#a855f7"}];function qb({menu:e,onClose:t}){let n;if(e.kind==="node"){let c=R.value.get(e.nodeId);if(!c)return null;n=PI(c)}else if(e.kind==="edge"){let c=e.edgeId,l=Re.value.get(c);n=[{label:l?.label?`Edit label “${l.label.slice(0,18)}${l.label.length>18?"…":""}”`:"Add label…",action:()=>{Yt("Edge label (empty clears it)","label text",{initial:l?.label??"",allowEmpty:!0,confirm:"Save"}).then((u)=>{if(u===null)return;us(c,{label:u})})}},{separator:!0},...["flow","depends-on","relation","references"].map((u)=>({label:`${l?.type===u?"✓":" "} ${u}`,action:()=>void us(c,{type:u})})),{separator:!0},...["solid","dashed","dotted"].map((u)=>({label:`${(l?.style??"solid")===u?"✓":" "} ${u}`,action:()=>void us(c,{style:u})})),{separator:!0},{label:"Delete edge",danger:!0,action:()=>void ds(c)}]}else n=zI(e.canvasX,e.canvasY);let o=new Map,r=n.some((c)=>c.render)?n.length*32+168:n.length*32+8,s=Math.min(e.x,Math.max(12,window.innerWidth-240)),a=Math.min(e.y,Math.max(12,window.innerHeight-r));return i("div",{class:"context-menu",style:{position:"fixed",left:`${s}px`,top:`${a}px`,zIndex:1e4},onPointerDown:(c)=>c.stopPropagation(),onClick:(c)=>c.stopPropagation(),children:n.map((c)=>{let l=c.separator?"separator":c.render?"custom":`${c.label??"item"}:${c.shortcut??""}`,u=(o.get(l)??0)+1;o.set(l,u);let d=`${l}:${u}`;if(c.separator)return i("div",{class:"context-menu-separator"},d,!1,void 0,this);if(c.render)return i("div",{class:"context-menu-custom",children:c.render(t)},d,!1,void 0,this);return i("button",{type:"button",class:`context-menu-item${c.danger?" is-danger":""}`,onClick:()=>{c.action?.(),t()},children:[i("span",{class:"context-menu-label",children:c.label},void 0,!1,void 0,this),c.shortcut&&i("span",{class:"context-menu-shortcut",children:c.shortcut},void 0,!1,void 0,this)]},d,!0,void 0,this)})},void 0,!1,void 0,this)}function TI(e){return(typeof e.data.path==="string"?e.data.path.trim():"")||null}function ac(e){let t=e.trim().toLowerCase(),n=t.match(/^#([0-9a-f]{3})$/);if(n){let[o,r,s]=n[1].split("");return`#${o}${o}${r}${r}${s}${s}`}return t}function Vb(e){if(typeof e.data.color!=="string"||!e.data.color.trim())return null;return ac(e.data.color)}function EI(e){let t=Vb(e);return t&&/^#[0-9a-f]{6}$/.test(t)?t:ac(kI)}function Nd(e,t){let n=t?ac(t):null;et(e.id,{data:{...e.data,color:n}}),it(e.id,{data:{color:n}})}function II(e,t){let n=Vb(e);return i("div",{class:"context-menu-section",children:[i("div",{class:"context-menu-section-header",children:[i("span",{class:"context-menu-section-label",children:"Group color"},void 0,!1,void 0,this),i("button",{type:"button",class:"context-menu-reset",onClick:()=>{Nd(e,null),t()},children:"Theme default"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"context-menu-color-grid",children:CI.map((o)=>{let r=ac(o.value);return i("button",{type:"button",class:`context-menu-color-swatch${n===r?" active":""}`,"aria-label":`Set group color to ${o.label}`,title:o.label,style:{"--swatch-color":o.value},onClick:()=>{Nd(e,o.value),t()},children:[i("span",{class:"context-menu-color-dot",style:{"--swatch-color":o.value}},void 0,!1,void 0,this),i("span",{children:o.label},void 0,!1,void 0,this)]},o.value,!0,void 0,this)})},void 0,!1,void 0,this),i("label",{class:"context-menu-color-custom",children:[i("span",{children:"Custom"},void 0,!1,void 0,this),i("input",{type:"color",class:"context-menu-color-input","aria-label":"Custom group color",value:EI(e),onClick:(o)=>o.stopPropagation(),onInput:(o)=>{Nd(e,o.currentTarget.value),t()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function $d(e,t,n,o){return{x:e-n/2,y:t-o/2}}function AI(e,t){return e.trim().replace(/[?#].*$/,"").split("/").filter(Boolean).at(-1)||t}async function Rd(e){let t=await Yt(e.promptLabel,e.placeholder??"");if(!t)return;let n=t.trim();if(!n)return;let o=$d(e.canvasX,e.canvasY,e.width,e.height);if(!(await Ut({type:e.type,...e.type!=="webpage"?{title:AI(n,e.titleFallback)}:{},content:n,x:o.x,y:o.y,width:e.width,height:e.height})).ok)console.error(`[canvas-menu] ${e.errorMessage}`)}function zI(e,t){return[{label:"New note",action:()=>{let r=$d(e,t,520,360);Ut({type:"markdown",title:"New note",x:r.x,y:r.y,width:520,height:360})}},{label:"Open webpage...",action:()=>{Rd({promptLabel:"Webpage URL:",type:"webpage",canvasX:e,canvasY:t,width:520,height:420,placeholder:"https://example.com",titleFallback:"Webpage",errorMessage:"Could not create webpage node. Enter a valid http(s) URL."})}},{label:"Open file...",action:()=>{Rd({promptLabel:"Workspace path or absolute file path:",type:"file",canvasX:e,canvasY:t,width:720,height:500,placeholder:"src/server/server.ts",titleFallback:"File",errorMessage:"Could not create file node. Check the path and try again."})}},{label:"Open image...",action:()=>{Rd({promptLabel:"Image path, URL, or data URI:",type:"image",canvasX:e,canvasY:t,width:480,height:360,placeholder:"artifacts/architecture.png",titleFallback:"Image",errorMessage:"Could not create image node. Check the image source and try again."})}},{separator:!0},{label:"New group",action:()=>{let r=$d(e,t,600,400);jo({title:"Group",x:r.x,y:r.y,width:600,height:400})}}]}function PI(e){let t=[],n=TI(e);if(t.push({label:"Focus",action:()=>tt(e.id)}),t.push({label:"Rename…",action:()=>{Yt("Rename node","Node title",{initial:typeof e.data.title==="string"?e.data.title:"",confirm:"Save"}).then((l)=>{if(!l?.trim())return;it(e.id,{title:l.trim()})})}}),Fr.has(e.type))t.push({label:"Expand",shortcut:"⤢",action:()=>en(e.id)});t.push({label:e.collapsed?"Expand":"Collapse",action:()=>Ko(e.id)});let o=Ee.value.has(e.id);t.push({label:o?"Unpin from context":"Pin as context",action:()=>Rn(e.id)}),t.push({label:e.pinned?"Unlock position":"Lock position (no auto-arrange)",action:()=>{let l=!e.pinned;et(e.id,{pinned:l}),it(e.id,{pinned:l}),nt()}});let r=ys.value;if(r&&r.from!==e.id){let l=R.value.get(r.from),u=l?(l.data.title||l.id).slice(0,20):r.from;t.push({label:`Connect from "${u}"`,action:()=>{so(r.from,e.id,"relation"),ys.value=null}})}t.push({label:r?"Connect from here (replace)":"Connect from here",action:()=>{ys.value={from:e.id}}});let s=Array.from(Re.value.values()).filter((l)=>l.from===e.id||l.to===e.id).length;if(s>0)t.push({label:`${s} edge${s!==1?"s":""} connected`});if(t.push({separator:!0}),(e.type==="markdown"||e.type==="file"||e.type==="image")&&n)t.push({label:"Open in browser",action:()=>{window.open(`/artifact?path=${encodeURIComponent(n)}`,"_blank","noopener")}}),t.push({label:"Copy path",action:()=>{navigator.clipboard.writeText(n)}});if(e.type==="mcp-app"||e.type==="json-render"||e.type==="graph")if(e.data.chartConfig){let l=e.data.chartConfig.title||"chart";t.push({label:"Copy chart data",action:()=>{navigator.clipboard.writeText(JSON.stringify(e.data.chartConfig,null,2))}})}else{let l=e.data.url;if(t.push({label:"Open in browser",action:()=>{if(l)window.open(l,"_blank")}}),t.push({label:"Focus in TUI",action:()=>Dp("mcp-app-focus",{url:l})}),e.type==="json-render"||e.type==="graph")t.push({label:"Copy spec",action:()=>{navigator.clipboard.writeText(JSON.stringify(e.data.spec??e.data.graphConfig??{},null,2))}})}if(e.type==="webpage"){let l=typeof e.data.url==="string"?e.data.url:"";t.push({label:"Refresh webpage",action:()=>{as(e.id)}}),t.push({label:"Open in browser",action:()=>{if(l)window.open(l,"_blank","noopener")}}),t.push({label:"Copy URL",action:()=>{if(l)navigator.clipboard.writeText(l)}})}if(e.type==="group"){let l=e.data.children??[];if(t.push({separator:!0}),t.push({render:(u)=>II(e,u)}),l.length>0)t.push({label:`Ungroup (${l.length} node${l.length!==1?"s":""})`,action:()=>{It(e.id),Zo(e.id)}})}let a=typeof e.data.parentGroup==="string"?e.data.parentGroup:null,c=a?R.value.get(a):void 0;if(c&&c.type==="group"){let l=typeof c.data.title==="string"&&c.data.title?c.data.title:"frame",u=Array.isArray(c.data.children)?c.data.children.filter((d)=>d!==e.id):[];t.push({label:`Remove from “${l}”`,action:()=>{ls(c.id,u)}})}return t.push({separator:!0}),t.push({label:e.type==="group"?"Delete frame (children stay)":"Delete",danger:!0,action:()=>{It(e.id),In(e.id)}}),t}function Gb(){let e=Ee.value.size;if(e===0||Jt.value)return null;return i("div",{class:"context-pin-bar",children:[i("span",{class:"context-pin-bar-count",children:["✦"," ",e," node",e!==1?"s":""," in context"]},void 0,!0,void 0,this),i("button",{type:"button",class:"context-pin-bar-btn context-pin-bar-clear",onClick:Cf,title:"Clear all context pins",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ci(e,t){console.error(`[tool-rail] ${e} failed`,t)}function wn(e){let t={image:{message:"Image URL (https://… or data:image/…)",placeholder:"https://example.com/diagram.png"},file:{message:"Workspace file path",placeholder:"src/server/server.ts"},webpage:{message:"Page URL",placeholder:"https://example.com"}};Yt(t[e].message,t[e].placeholder).then((n)=>{if(!n)return;Pt({type:e,content:n}).catch((o)=>Ci(`create ${e}`,o))})}function rt({label:e,shortcut:t,detail:n,ariaLabel:o,active:r,menuOpen:s,onClick:a,btnRef:c,children:l}){let[u,d]=L(null),p=(g)=>{let y=g.currentTarget.getBoundingClientRect();d({left:y.right+10,top:y.top+y.height/2})},m=()=>d(null),f=o??(t?`${e} (${t})`:n?`${e} (${n})`:e);return i(ve,{children:[i("button",{ref:c,type:"button",class:`rail-btn${r?" active":""}`,"aria-label":f,"aria-pressed":r===void 0?void 0:r,onClick:(g)=>{m(),a(g)},onPointerEnter:p,onPointerLeave:m,onFocus:p,onBlur:m,children:l},void 0,!1,void 0,this),u&&!s&&i("span",{class:"toolbar-tooltip rail-tooltip",role:"tooltip","data-testid":"rail-tooltip",style:{left:`${u.left}px`,top:`${u.top}px`},children:[i("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),(t||n)&&i("span",{class:"toolbar-tooltip-meta",children:[t&&i("kbd",{class:"toolbar-tooltip-shortcut",children:t},void 0,!1,void 0,this),n&&i("span",{children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Xb({minimapVisible:e,onToggleMinimap:t,snapshotOpen:n,onToggleSnapshot:o,snapshotBtnRef:r,onOpenPalette:s,onOpenShortcuts:a,annotationTool:c,onSetAnnotationTool:l}){let u=yt.value,d=Go.value,p=Array.from(R.value.values()).filter((k)=>k.type==="trace").length,m=Re.value.size,[f,g]=L(null),[y,x]=L(null),h=M(null),v=(k)=>(T)=>{if(f===k){g(null);return}let P=T.currentTarget.getBoundingClientRect();x({top:P.top,bottom:P.bottom,right:P.right}),g(k)},b=(k)=>y?k?{position:"fixed",left:`${y.right+8}px`,bottom:`${window.innerHeight-y.bottom}px`,top:"auto",right:"auto"}:{position:"fixed",left:`${y.right+8}px`,top:`${y.top}px`,right:"auto"}:void 0;D(()=>{if(!f)return;let k=(P)=>{if(h.current&&P.target instanceof Node&&!h.current.contains(P.target))g(null)},T=(P)=>{if(P.key==="Escape")g(null)};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",T),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",T)}},[f]);let z=(k)=>{sc(),document.documentElement.setAttribute("data-theme",k),vr(),Xe.value=k,is(k),g(null)},F=Ll(Xe.value),_=(k,T={})=>{fetch(`/api/workbench/intent?_ts=${Date.now()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:k,payload:T})}).catch((P)=>Ci("sendIntent",P))};return i("div",{class:"tool-rail",ref:h,role:"toolbar","aria-label":"Canvas tools","aria-orientation":"vertical",children:[i("span",{class:"rail-brand",title:"PMX Canvas","aria-label":"PMX Canvas",children:i(Lx,{size:22},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"rail-divider"},void 0,!1,void 0,this),i(rt,{label:"Select",shortcut:"V",active:u==="select",onClick:()=>yt.value="select",children:i(Dx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Pan",shortcut:"Space",active:u==="pan",onClick:()=>yt.value="pan",children:i(Fx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Connect",shortcut:"C",active:u==="connect",onClick:()=>yt.value="connect",children:i("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("circle",{cx:"4",cy:"4",r:"2"},void 0,!1,void 0,this),i("circle",{cx:"12",cy:"12",r:"2"},void 0,!1,void 0,this),i("path",{d:"M5.5 5.5 C 8 8, 8 8, 10.5 10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("div",{class:"rail-divider"},void 0,!1,void 0,this),i(rt,{label:"Markdown note",shortcut:"M",onClick:()=>void Pt({type:"markdown",title:"New note",width:520,height:360}).catch((k)=>Ci("create markdown",k)),children:i(Bn,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Image",shortcut:"I",onClick:()=>wn("image"),children:i(ud,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"File",shortcut:"Shift+F",onClick:()=>wn("file"),children:i(Ba,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Webpage",shortcut:"W",onClick:()=>wn("webpage"),children:i(xr,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"HTML surface",shortcut:"H",onClick:()=>void Pt({type:"html",title:"HTML surface"}).catch((k)=>Ci("create html",k)),children:i(jx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Group",shortcut:"G",onClick:()=>void Pt({type:"group",title:"Group"}).catch((k)=>Ci("create group",k)),children:i(dd,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"toolbar-menu-anchor",children:[i(rt,{label:"Annotate",shortcut:"A",detail:"Draw · Text note · Eraser",active:c!==null,menuOpen:f==="annotate",onClick:v("annotate"),children:c==="eraser"?i(cd,{},void 0,!1,void 0,this):c==="text"?i(ld,{},void 0,!1,void 0,this):i(ad,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),f==="annotate"&&i("div",{class:"toolbar-menu",style:b(!1),role:"menu","aria-label":"Annotate",children:[i("button",{type:"button",class:`toolbar-menu-item${c==="pen"?" active":""}`,onClick:()=>{l(c==="pen"?null:"pen"),g(null)},children:[i(ad,{},void 0,!1,void 0,this),i("span",{children:c==="pen"?"Stop annotating":"Draw (A)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:`toolbar-menu-item${c==="text"?" active":""}`,onClick:()=>{l(c==="text"?null:"text"),g(null)},children:[i(ld,{},void 0,!1,void 0,this),i("span",{children:c==="text"?"Stop text notes":"Text note"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:`toolbar-menu-item${c==="eraser"?" active":""}`,onClick:()=>{l(c==="eraser"?null:"eraser"),g(null)},children:[i(cd,{},void 0,!1,void 0,this),i("span",{children:c==="eraser"?"Stop erasing":"Eraser"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"rail-spacer"},void 0,!1,void 0,this),i(rt,{label:"Search & commands",shortcut:Ze("K"),onClick:s,children:i(Mx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Arrange",detail:m>0?"graph-aware":"grid",onClick:()=>m>0?Ts():Cs(),children:i(So,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:d?"Disable trace":"Enable trace",active:d,onClick:()=>_("trace-toggle",{enabled:!d}),children:i(Rx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),(d||p>0)&&i(rt,{label:"Clear trace",onClick:()=>_("trace-clear"),children:i($x,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:e?"Hide minimap":"Show minimap",active:e,onClick:t,children:i(Wa,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(rt,{label:"Snapshots",active:n,onClick:o,btnRef:r,children:i(Nx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"toolbar-menu-anchor",children:[i(rt,{label:"Theme",detail:ar[F].label,menuOpen:f==="theme",ariaLabel:"Choose theme",active:f==="theme",onClick:v("theme"),children:cr(F)==="dark"?i(Px,{},void 0,!1,void 0,this):i(qa,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),f==="theme"&&i("div",{class:"toolbar-menu",style:b(!0),role:"menu","aria-label":"Theme",children:Ol.map((k)=>i("button",{type:"button",role:"menuitemradio","aria-checked":F===k,class:`toolbar-menu-item${F===k?" active":""}`,onClick:()=>z(k),children:[i("span",{class:"theme-swatch",style:{background:ar[k].swatchBg},children:i("span",{class:"theme-swatch-dot",style:{background:ar[k].swatchAccent}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{children:ar[k].label},void 0,!1,void 0,this),F===k&&i("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},k,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(rt,{label:"Shortcuts",shortcut:"?",onClick:a,children:i(Ox,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Kb({onOpenPalette:e}){let t=M(null),n=()=>{Pt({type:"markdown",title:"New note",width:520,height:360}).catch(()=>{})},o=async(r)=>{if(!r||r.length===0)return;let s=Fo(),a=re.value;await Ha(Array.from(r),(s.x-a.x)/a.scale,(s.y-a.y)/a.scale)};return i("div",{class:"empty-state","data-testid":"empty-state",children:[i("svg",{class:"empty-state-mark",width:"52",height:"52",viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",children:[i("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7"},void 0,!1,void 0,this),i("rect",{x:"20",y:"20",width:"24",height:"24",rx:"4","stroke-dasharray":"4 4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{children:[i("div",{class:"empty-state-title",children:"Nothing on this board yet"},void 0,!1,void 0,this),i("div",{class:"empty-state-sub",children:"Drop files anywhere, paste a link, or start from a note."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"empty-state-grid",children:[i("button",{type:"button",class:"empty-state-action",onClick:n,children:[i(Bn,{size:16,class:"tone-accent"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-label",children:"New markdown note"},void 0,!1,void 0,this),i("kbd",{children:"M"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-action",onClick:()=>t.current?.click(),children:[i("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round",class:"tone-warn","aria-hidden":"true",children:[i("path",{d:"M8 10 V2 M8 2 L5 5 M8 2 L11 5"},void 0,!1,void 0,this),i("path",{d:"M2 10 V13 H14 V10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"empty-state-action-label",children:"Drop files"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-hint",children:"or pick"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-action",onClick:()=>wn("webpage"),children:[i(xr,{size:16,class:"tone-ok"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-label",children:"Paste a link"},void 0,!1,void 0,this),i("kbd",{children:Ze("V")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-action is-agent",onClick:()=>void Xn(),children:[i(br,{size:16,class:"tone-purple"},void 0,!1,void 0,this),i("span",{class:"empty-state-action-label",children:"Start agent session"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"empty-state-hint",onClick:e,children:["? shortcuts · ",Ze("K")," palette"]},void 0,!0,void 0,this),i("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:(r)=>{let s=r.currentTarget;o(s.files).finally(()=>{s.value=""})}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Md({presence:e,size:t=18}){return i("span",{class:"writer-avatar",style:{background:Ga(e.sessionId),width:`${t}px`,height:`${t}px`},"aria-hidden":"true",children:Kx(e.label)},void 0,!1,void 0,this)}function Jb(){let e=yd.value;if(ft.value||e.length===0)return null;let t=e.reduce((r,s)=>r+s.opCount,0),n=e.length===1?e[0].label:`${e.length} writers`,o=ko.value;return i("button",{type:"button",class:"external-indicator","data-testid":"external-indicator","aria-expanded":o,title:`${e.length} external writer${e.length===1?"":"s"} on this board — click for activity`,onClick:()=>{ko.value=!o},children:[i("span",{class:"external-indicator-avatars",children:e.slice(0,3).map((r)=>i(Md,{presence:r},r.sessionId,!1,void 0,this))},void 0,!1,void 0,this),i("span",{class:"external-indicator-label",children:n},void 0,!1,void 0,this),i("span",{class:"external-indicator-ops hud-collapsible-text",children:[t," op",t===1?"":"s"]},void 0,!0,void 0,this),i("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function NI(e){if(e==="node.add"||e==="jsonrender.add"||e==="graph.add"||e==="group.create")return{glyph:"+",tone:"ok"};if(e==="node.remove"||e==="edge.remove"||e==="canvas.clear")return{glyph:"×",tone:"danger"};if(e==="edge.add")return{glyph:"⟶",tone:"accent"};if(e.startsWith("ax."))return{glyph:"◆",tone:"purple"};return{glyph:"✎",tone:"accent"}}function RI(e){return e.reduce((t,n)=>n.lastSeenAt>t?n.lastSeenAt:t,"")}function $I(){return[...Ve.value.values()].filter((e)=>!e.auto&&e.phase==="forming")}function Yb(){let e=ko.value,t=yd.value,n=bn(e?1e4:0);if(D(()=>{if(!e)return;let c=(l)=>{if(l.key!=="Escape")return;if(wr.value)wr.value=!1;else ko.value=!1};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]),!e||ft.value||t.length===0)return null;let o=vd.value,r=$I().filter((c)=>!o||(c.source??"")===o),s=qn.value.filter((c)=>!o||c.sessionId===o),a=(c,l)=>i("button",{type:"button",class:`activity-filter${o===c?" is-active":""}`,style:c?{"--writer":Ga(c)}:void 0,"aria-pressed":o===c,onClick:()=>{vd.value=c},children:l},void 0,!1,void 0,this);return i("div",{class:"activity-feed","data-testid":"activity-feed",role:"dialog","aria-label":"External activity",children:[i("div",{class:"activity-feed-head",children:[i("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"activity-feed-titles",children:[i("div",{class:"activity-feed-title",children:["External activity — ",t.length," writer",t.length===1?"":"s"]},void 0,!0,void 0,this),i("div",{class:"activity-feed-sub",children:[t.reduce((c,l)=>c+l.opCount,0)," writes · last"," ",Xa(RI(t),n)," · no session attached"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"activity-feed-close","aria-label":"Close activity feed",onClick:()=>{ko.value=!1},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"activity-filters",children:[a(null,"All"),t.map((c)=>a(c.sessionId,c.label))]},void 0,!0,void 0,this),i("div",{class:"activity-rows",children:[r.map((c)=>i("div",{class:"activity-row is-pending","data-testid":"activity-proposal",children:[i("span",{class:"activity-glyph tone-purple","aria-hidden":"true",children:"▢"},void 0,!1,void 0,this),i("div",{class:"activity-main",children:[i("div",{class:"activity-text",children:["Proposing: ",i("b",{children:c.label?.trim()||`${c.kind} intent`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"activity-meta",children:[c.reason?.trim()||"Intent signalled — a real veto window before the mutation",c.source?` · ${c.source}`:""]},void 0,!0,void 0,this),i("div",{class:"activity-actions",children:[i("button",{type:"button",class:"activity-veto",onClick:()=>{io(c).then((l)=>{if(l)Xr(c.id)})},children:"Veto"},void 0,!1,void 0,this),i("span",{class:"activity-hint",children:"or hover ghost + Esc"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"activity-age",children:"now"},void 0,!1,void 0,this)]},c.id,!0,void 0,this)),s.length===0&&r.length===0&&i("div",{class:"activity-empty",children:"No writes yet."},void 0,!1,void 0,this),s.map((c)=>{let{glyph:l,tone:u}=NI(c.op);return i("div",{class:"activity-row","data-testid":"activity-row","data-op":c.op,children:[i("span",{class:`activity-glyph tone-${u}`,"aria-hidden":"true",children:l},void 0,!1,void 0,this),i("div",{class:"activity-main",children:[i("div",{class:"activity-text",children:c.summary},void 0,!1,void 0,this),i("div",{class:"activity-writer",style:{color:Ga(c.sessionId)},children:c.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"activity-age",children:Xa(c.at,n)},void 0,!1,void 0,this)]},c.id,!0,void 0,this)})]},void 0,!0,void 0,this),i("div",{class:"activity-feed-foot",children:[i("span",{class:"activity-feed-note",children:"All writes ghost first · Esc vetoes"},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-link",onClick:()=>{wr.value=!0},children:"Writers"},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-link is-accent",onClick:()=>{ko.value=!1,Xn()},children:"Start session ↗"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function MI(){let e=[];if(Vn.value)e.push("scoped");if(Co.value.length>0)e.push("gated");return e.length>0?e.join(" + "):"open"}function Qb(){let e=wr.value,t=bn(e?1e4:0),n=M(null);if(Er(n,e),!e)return null;let o=pt.value.filter((a)=>a.attached),r=pt.value.filter((a)=>!a.attached),s=()=>{wr.value=!1};return i(ve,{children:[i("div",{class:"writers-scrim",onClick:s,"aria-hidden":"true"},void 0,!1,void 0,this),i("div",{ref:n,class:"writers-sheet","data-testid":"writers-sheet",role:"dialog","aria-modal":"true","aria-label":"Connected writers",children:[i("div",{class:"writers-head",children:[i("span",{class:"writers-title",children:"Connected writers"},void 0,!1,void 0,this),i("span",{class:"writers-board",children:dn.value.slice(0,12)},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-close","aria-label":"Close writers",onClick:s,children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"writers-body",children:[i("div",{class:"writers-section",children:"Agent sessions"},void 0,!1,void 0,this),o.length===0&&i("div",{class:"writers-empty",children:"None attached — start one from the top bar."},void 0,!1,void 0,this),o.map((a)=>i("div",{class:"writers-row",children:[i(Md,{presence:a,size:20},void 0,!1,void 0,this),i("span",{class:"writers-name",children:a.label},void 0,!1,void 0,this),i("span",{class:"writers-config",children:MI()},void 0,!1,void 0,this)]},a.sessionId,!0,void 0,this)),i("div",{class:"writers-section",children:"External writers · MCP"},void 0,!1,void 0,this),r.length===0&&i("div",{class:"writers-empty",children:"No external writers right now."},void 0,!1,void 0,this),r.map((a)=>i("div",{class:"writers-row",children:[i(Md,{presence:a,size:20},void 0,!1,void 0,this),i("span",{class:"writers-name is-mono",children:a.label},void 0,!1,void 0,this),i("span",{class:"writers-meta",children:[a.source!==a.label?`${a.source} · `:"","wrote"," ",Xa(a.lastSeenAt,t)," ago"]},void 0,!0,void 0,this)]},a.sessionId,!0,void 0,this))]},void 0,!0,void 0,this),i("div",{class:"writers-foot",children:[i("span",{class:"writers-note",children:"Local-first: any process on this machine can connect and write. Every write ghosts first — veto is the control, not permissions."},void 0,!1,void 0,this),i("button",{type:"button",class:"writers-done",onClick:s,children:"Done"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ew(e,t){switch(e.type){case"markdown":return i(Ms,{node:e,expanded:t},void 0,!1,void 0,this);case"mcp-app":return i(Hn,{node:e,expanded:t},void 0,!1,void 0,this);case"webpage":return i(Da,{node:e,expanded:t},void 0,!1,void 0,this);case"json-render":return i(Hn,{node:e,expanded:t},void 0,!1,void 0,this);case"graph":return i(Hn,{node:e,expanded:t},void 0,!1,void 0,this);case"prompt":return i(Fa,{node:e},void 0,!1,void 0,this);case"response":return i(ja,{node:e,expanded:t},void 0,!1,void 0,this);case"status":return i(Oa,{node:e},void 0,!1,void 0,this);case"context":return i(gs,{node:e,expanded:t},void 0,!1,void 0,this);case"ledger":return i(As,{node:e},void 0,!1,void 0,this);case"trace":return i(Za,{node:e},void 0,!1,void 0,this);case"file":return i(Is,{node:e,expanded:t},void 0,!1,void 0,this);case"diff":return i(vs,{node:e},void 0,!1,void 0,this);case"mermaid":return i(Xs,{node:e,expanded:t},void 0,!1,void 0,this);case"image":return i(La,{node:e,expanded:t},void 0,!1,void 0,this);case"html":return i(wi,{node:e,expanded:t},void 0,!1,void 0,this);default:return i("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function tw(e){switch(e.type){case"markdown":return e.data.content||"";case"diff":return e.data.content||"";case"mermaid":return e.data.content||"";case"file":return e.data.fileContent||"";case"webpage":return e.data.content||"";case"html":return e.data.html||e.data.content||"";case"json-render":case"graph":return JSON.stringify(e.data.spec??e.data.graphConfig??{},null,2);default:return""}}function OI(e){if(!e)return 0;return e.split(/\s+/).filter(Boolean).length}function LI(e,t){return e!==null&&typeof e==="object"&&e.source===Ot&&e.type==="presentation-exit"&&e.token===t}function DI(e){return e==="ArrowRight"||e==="PageDown"||e===" "||e==="ArrowLeft"||e==="PageUp"||e==="Home"||e==="End"}function nw(e){return e instanceof HTMLElement&&Boolean(e.closest(".html-presentation-exit"))}function ow(){let e=Be.value,t=e?R.value.get(e):void 0,[n,o]=L(!1),[r,s]=L(!1),[a,c]=L(""),l=M(null),u=M(null),d=O(()=>{s(!1),po()},[]),p=O(()=>{c(`presentation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`),s(!0)},[]),m=O((H)=>{document.querySelector(".html-presentation-overlay iframe.html-node-frame-presentation")?.contentWindow?.postMessage({source:Ot,token:a,...H},"*")},[a]),f=O(()=>{s(!1)},[]),g=O((H)=>{if(H.key==="Escape"){H.preventDefault(),H.stopPropagation(),s(!1);return}if(H.key==="Tab"&&!nw(H.target)){H.preventDefault(),H.stopPropagation(),u.current?.focus();return}if((H.key===" "||H.key==="Enter")&&nw(H.target))return;if(!DI(H.key))return;H.preventDefault(),H.stopPropagation(),m({type:"presentation-key",key:H.key})},[m]),y=O((H)=>{if(H.target.classList.contains("expanded-overlay-backdrop"))po()},[]),x=O(()=>{if(!t)return;let H=tw(t);if(!H)return;navigator.clipboard.writeText(H).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},[t]),h=O(()=>{if(!e)return;Rn(e)},[e]);D(()=>{s(!1)},[e]),Ui(()=>{if(!r)return;let H=()=>{let xe=l.current;if(!xe||xe.contains(document.activeElement))return;xe.focus()},U=[0,50,150].map((xe)=>window.setTimeout(H,xe)),ee=(xe)=>{if(!LI(xe.data,a))return;s(!1)};return document.addEventListener("keydown",g,!0),window.addEventListener("message",ee),()=>{U.forEach((xe)=>{window.clearTimeout(xe)}),document.removeEventListener("keydown",g,!0),window.removeEventListener("message",ee)}},[g,a,r]);let v=M(null),b=O(()=>e?document.querySelector(`.canvas-node[data-node-id="${CSS.escape(e)}"]`):null,[e]);if(Er(v,t!==void 0,{restoreTo:b}),!t)return null;let z=t.data.title||t.data.path?.split("/").pop()||st[t.type],F=tw(t),_=OI(F),k=e?Ee.value.has(e):!1,T=F.length>0,P=Qt.value===e,Z=t.type==="mcp-app"||t.type==="webpage"||t.type==="json-render"||t.type==="graph",j=bx(t),E=yn(t.type),B=t.data.provenance&&typeof t.data.provenance==="object"?t.data.provenance:null,W=B?[B.sourceKind,B.sourceUri,B.syncedAt?`synced ${B.syncedAt.slice(11,16)}`:null].filter((H)=>typeof H==="string"&&H.length>0).join(" · "):null;return i("div",{class:"expanded-overlay-backdrop",onPointerDown:y,style:{pointerEvents:P?"none":"auto"},children:i("div",{ref:v,class:`expanded-overlay-panel${k?" is-pinned":""}`,role:"dialog","aria-modal":"true","aria-label":z,"data-testid":"expanded-node",children:[i("div",{class:"expanded-header",children:[i("span",{class:"expanded-kind-icon","aria-hidden":"true",children:i(E,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"expanded-title",children:z},void 0,!1,void 0,this),i("span",{class:"expanded-kind-pill",children:st[t.type]},void 0,!1,void 0,this),i("button",{type:"button",class:`expanded-pin${k?" is-on":""}`,onClick:h,title:k?"In agent context — click to unpin":"Pin as agent context","aria-pressed":k,children:"✦"},void 0,!1,void 0,this),i("span",{class:"expanded-spacer"},void 0,!1,void 0,this),i("div",{class:"expanded-actions",children:[T&&i("button",{type:"button",class:"expanded-action-btn",onClick:x,title:"Copy content to clipboard",children:n?"Copied!":"Copy"},void 0,!1,void 0,this),Fs(t)&&i("button",{type:"button",class:"expanded-action-btn",onClick:()=>void js(t),title:"Open as a full-page site in the system browser",children:"Open in tab ↗"},void 0,!1,void 0,this),j&&i("button",{type:"button",class:"expanded-action-btn expanded-action-primary",onClick:p,title:"Present this HTML node fullscreen",children:"Present"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("button",{type:"button",class:"expanded-close",onClick:d,title:"Close (Esc)","aria-label":"Close",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:`expanded-body${Z?" is-embedded":""}`,children:Z?i("div",{style:{flex:1,minHeight:0,display:"flex"},children:ew(t,!0)},void 0,!1,void 0,this):ew(t,!0)},void 0,!1,void 0,this),i("div",{style:{"--ax-dock-bleed":"0px","--ax-dock-pad":"16px"},children:i(nc,{node:t},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"expanded-footer",children:[i("span",{class:"expanded-footer-meta",children:[W,_>0?`${_.toLocaleString()} word${_!==1?"s":""}`:null].filter(Boolean).join(" · ")||st[t.type].toLowerCase()},void 0,!1,void 0,this),i("span",{class:"expanded-spacer"},void 0,!1,void 0,this),i("span",{class:`expanded-footer-hint${P?" is-saving":""}`,children:P?"Saving edits…":"esc or click outside to close"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j&&r&&i("div",{ref:l,class:"html-presentation-overlay",role:"dialog","aria-modal":"true","aria-label":`Present ${z}`,tabIndex:-1,onKeyDownCapture:g,children:[i("button",{ref:u,type:"button",class:"html-presentation-exit",onClick:f,title:"Exit presentation (Esc)","aria-label":"Exit presentation",children:"Exit presentation"},void 0,!1,void 0,this),i("div",{class:"html-presentation-stage",children:i(wi,{node:t,expanded:!0,presentation:!0,presentationExitToken:a},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var iw=168,sw=112,cc=20;function rw(e,t,n,o){let r=Array.from(e.values()),s=0,a=0,c=1000,l=800;if(r.length>0){s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let x of r)s=Math.min(s,x.position.x),a=Math.min(a,x.position.y),c=Math.max(c,x.position.x+x.size.width),l=Math.max(l,x.position.y+x.size.height)}let u=-t.x/t.scale,d=-t.y/t.scale,p=u+n/t.scale,m=d+o/t.scale,f={minX:Math.min(s,u)-cc,minY:Math.min(a,d)-cc,maxX:Math.max(c,p)+cc,maxY:Math.max(l,m)+cc},g=f.maxX-f.minX||1,y=f.maxY-f.minY||1;return{bounds:f,scale:Math.min(iw/g,sw/y)}}function aw({viewport:e,nodes:t,onNavigate:n,containerWidth:o,containerHeight:r}){let s=M(null),a=M(!1),c=t.value,l=e.value,u=rw(c,l,o,r),{bounds:d,scale:p}=u,m=(_)=>(_-d.minX)*p,f=(_)=>(_-d.minY)*p,g=O((_)=>{let k=s.current;if(!k)return;let T=k.getBoundingClientRect(),P=(_.clientX-T.left)/T.width*iw,Z=(_.clientY-T.top)/T.height*sw,j=rw(t.value,e.value,o,r),E=e.value,B=o/E.scale,W=r/E.scale,H=P/j.scale+j.bounds.minX,U=Z/j.scale+j.bounds.minY;n(-(H-B/2)*E.scale,-(U-W/2)*E.scale)},[t,e,o,r,n]),y=O((_)=>{_.stopPropagation(),_.preventDefault(),a.current=!0,g(_);let k=(P)=>{if(a.current)g(P)},T=()=>{a.current=!1,document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",T)};document.addEventListener("pointermove",k),document.addEventListener("pointerup",T)},[g]),x=ye.value,h=Vn.value,v=h?Ja(h.nodeIds.map((_)=>c.get(_)).filter((_)=>_!==void 0),h.padding):null,b=pt.value.map((_)=>({id:_.sessionId,phase:_.phase,worker:_.parentAgentId!=null,external:!_.attached,at:Ka(_,(k)=>c.get(k))})).filter((_)=>_.at!==null),z=-l.x/l.scale,F=-l.y/l.scale;return i("div",{ref:s,class:"minimap","data-testid":"minimap",title:"Click to jump · drag the frame to pan",onPointerDown:y,children:[Array.from(c.values()).map((_)=>{let k=_.type==="group";return i("span",{class:`minimap-node${k?" is-group":""}${x.has(_.id)?" is-selected":""}`,"data-kind":_.type,style:{left:`${m(_.position.x)}px`,top:`${f(_.position.y)}px`,width:`${Math.max(k?6:4,_.size.width*p)}px`,height:`${Math.max(k?5:3,_.size.height*p)}px`,"--kind":ec[_.type]}},_.id,!1,void 0,this)}),v&&i("span",{class:"minimap-fence",style:{left:`${m(v.x)}px`,top:`${f(v.y)}px`,width:`${v.width*p}px`,height:`${v.height*p}px`}},void 0,!1,void 0,this),b.map((_)=>i("span",{class:`minimap-presence phase-${_.phase}${_.worker?" is-worker":""}${_.external?" is-external":""}`,style:{left:`${m(_.at.x)-4}px`,top:`${f(_.at.y)-4}px`,"--identity-color":`hsl(${Wn(_.id)} 65% 62%)`}},_.id,!1,void 0,this)),i("span",{class:"minimap-frame",style:{left:`${m(z)}px`,top:`${f(F)}px`,width:`${o/l.scale*p}px`,height:`${r/l.scale*p}px`}},void 0,!1,void 0,this),i("span",{class:"minimap-zoom",children:[Math.round(l.scale*100),"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Je({label:e,shortcut:t,body:n,align:o="center",side:r="down",tapToOpen:s=!1,children:a}){return i("span",{class:`toolbar-tooltip-anchor toolbar-tooltip-anchor-${o}${r==="up"?" toolbar-tooltip-anchor-up":""}${s?" toolbar-tooltip-anchor-tap":""}`,tabIndex:s?-1:void 0,children:[a,i("span",{class:"toolbar-tooltip",role:"tooltip",children:[i("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),n&&i("span",{class:"toolbar-tooltip-body",children:n},void 0,!1,void 0,this),t&&i("span",{class:"toolbar-tooltip-meta",children:i("kbd",{class:"toolbar-tooltip-shortcut",children:t},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function cw(){let e=ye.value.size,t=O(()=>{let c=Array.from(ye.value);if(c.length===0)return;bs(c),ht()},[]),n=O(()=>{let c=Array.from(ye.value);if(c.length===0)return;jo({title:"Group",childIds:c}),ht()},[]),o=O(()=>{let c=Array.from(ye.value);for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++)so(c[l],c[u],"relation");ht()},[]),r=O(()=>{let c=Array.from(ye.value);for(let l of c)It(l),In(l);ht()},[]);if(e===0)return null;let s=e>=2,a=!ft.value&&Ee.value.size>0&&!Jt.value;return i("div",{class:`selection-bar${a?" is-above-pin-bar":""}`,role:"toolbar","aria-label":"Selection",children:[i("span",{class:"selection-bar-count",children:[e," node",e!==1?"s":""," selected"]},void 0,!0,void 0,this),s&&i(ve,{children:[i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Align left",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align left",onClick:()=>ol("left"),children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("line",{x1:"2.5",y1:"2",x2:"2.5",y2:"14"},void 0,!1,void 0,this),i("rect",{x:"5",y:"3.5",width:"8",height:"3.5",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"5",y:"9",width:"5",height:"3.5",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Align top",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align top",onClick:()=>ol("top"),children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("line",{x1:"2",y1:"2.5",x2:"14",y2:"2.5"},void 0,!1,void 0,this),i("rect",{x:"3.5",y:"5",width:"3.5",height:"8",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"9",y:"5",width:"3.5",height:"5",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Distribute horizontally",body:"Evens the gaps. A selection that cannot fit flows into a clean row instead of overlapping.",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Distribute",disabled:e<3,onClick:()=>Sf(),children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[i("rect",{x:"1.5",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"6.25",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),i("rect",{x:"11",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Auto-arrange selection",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Auto-arrange",onClick:()=>kf(),children:i(So,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Group the selection",shortcut:"G",side:"up",children:i("button",{type:"button",class:"selection-bar-action",onClick:n,children:[i("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-dasharray":"3 2.5","aria-hidden":"true",children:i("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"2"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"Group"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Connect every pair",side:"up",children:i("button",{type:"button",class:"selection-bar-action",onClick:o,children:"Connect"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Je,{label:"Pin to agent context",side:"up",children:i("button",{type:"button",class:"selection-bar-action is-pin",onClick:t,children:[i("span",{"aria-hidden":"true",children:"✦"},void 0,!1,void 0,this),"Pin as context"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Delete selection",side:"up",children:i("button",{type:"button",class:"selection-bar-icon is-danger","aria-label":"Delete selection",onClick:r,children:i("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","aria-hidden":"true",children:[i("path",{d:"M2.5 4 H13.5"},void 0,!1,void 0,this),i("path",{d:"M5.5 4 V2.5 H10.5 V4"},void 0,!1,void 0,this),i("path",{d:"M4 4 L4.8 13.5 H11.2 L12 4"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Clear selection",shortcut:"Esc",side:"up",children:i("button",{type:"button",class:"selection-bar-icon",onClick:ht,"aria-label":"Clear selection",children:"×"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function lc(e,t=Date.now()){if(!e.expiresAt)return null;let n=Date.parse(e.expiresAt);if(!Number.isFinite(n))return null;return Math.max(0,n-t)}function uc(e){let t=Math.max(0,Math.ceil(e/1000)),n=Math.floor(t/60),o=t%60;return`${n}:${String(o).padStart(2,"0")}`}var FI={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"vetoed"},jI={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"cancelled"},lw=[{id:"all",label:"All",hint:"Everything below in one feed, newest first"},{id:"update",label:"Updates",hint:"Board edits agents made — nodes, edges, pins, work items"},{id:"steer",label:"Steer",hint:"Instructions sent to agents — by you from the composer, or agent-to-agent"},{id:"assistant",label:"Assistant",hint:"Messages agents posted for you to read"},{id:"event",label:"Events",hint:"Run telemetry — tool runs, approvals, failures, policy notes"},{id:"evidence",label:"Evidence",hint:"Proof agents recorded — test results, artifacts, links"}],uw=Object.fromEntries(lw.map((e)=>[e.id,e.hint])),ZI={policy:"warn",prompt:"accent","assistant-message":"muted","tool-start":"accent","tool-result":"ok",failure:"danger",approval:"warn",steering:"purple",command:"accent",note:"muted",evidence:"ok",steer:"purple",update:"purple",yield:"warn"};function Od(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function HI({item:e}){let t=FI[e.status]??"queued",n=e.nodeIds[0];return i("li",{class:`session-item status-${t}`,"data-work-item-id":e.id,children:[i("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-item-main",children:[i("button",{type:"button",class:"session-item-title",title:n?"Focus the linked node":void 0,disabled:!n,onClick:()=>n&&tt(n),children:e.title},void 0,!1,void 0,this),e.detail&&i("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"session-item-status",children:jI[e.status]??t},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:Od(e.updatedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function BI({gate:e,now:t}){let[n,o]=L(null),r=async(c)=>{o(c),await lb(e,c),o(null)},s=e.nodeIds[0],a=lc(e,t);return i("li",{class:"session-item status-awaiting session-gate","data-gate-id":e.id,children:[i("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-item-main",children:[i("button",{type:"button",class:"session-item-title",title:s?"Focus the linked node":void 0,disabled:!s,onClick:()=>s&&tt(s),children:e.title},void 0,!1,void 0,this),e.detail&&i("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this),a!==null&&i("div",{class:"session-gate-ttl","data-testid":"gate-countdown",children:["auto-holds in ",uc(a)," if unanswered"]},void 0,!0,void 0,this),i("div",{class:"session-gate-actions",children:[i("button",{type:"button",class:"session-gate-approve",disabled:n!==null,onClick:()=>void r("approved"),children:n==="approved"?"Approving…":"Approve"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-gate-reject",disabled:n!==null,onClick:()=>void r("rejected"),children:n==="rejected"?"Rejecting…":"Reject"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"session-item-time",children:Od(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function UI({gate:e}){let[t,n]=L(!1);return i("li",{class:"session-item status-vetoed session-gate-held","data-gate-id":e.id,children:[i("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-item-main",children:[i("span",{class:"session-item-title",children:e.title},void 0,!1,void 0,this),i("div",{class:"session-item-detail",children:"Auto-held — no answer in time, the action did not proceed."},void 0,!1,void 0,this),i("div",{class:"session-gate-actions",children:i("button",{type:"button",class:"session-gate-reject",disabled:t,onClick:()=>{n(!0),ub(e).finally(()=>n(!1))},children:t?"Reopening…":"Reopen"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"session-item-status",children:"held"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function WI(){let e=Vn.value,t=ye.value.size,[n,o]=L(!1),r=(s)=>{o(!0),rb(s).finally(()=>o(!1))};return i("div",{class:`session-scope${e?" is-fenced":""}`,"data-testid":"session-scope",children:[i("span",{class:"session-scope-dot","aria-hidden":"true"},void 0,!1,void 0,this),e?i(ve,{children:[i("span",{class:"session-scope-text",children:["Scoped to ",i("strong",{children:e.nodeIds.length},void 0,!1,void 0,this)," node",e.nodeIds.length===1?"":"s"," · writes outside are blocked"]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-scope-action",disabled:n,onClick:()=>r(null),children:"Clear"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(ve,{children:[i("span",{class:"session-scope-text",children:"Unscoped — the agent may write anywhere"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-scope-action",disabled:n||t===0,title:t===0?"Select nodes on the canvas first":"Fence the agent to the selected nodes",onClick:()=>r([...ye.value]),children:["Fence to selection",t>0?` (${t})`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function qI(e){if(e==="browser")return"you";return pt.value.find((n)=>n.sessionId===e||n.source===e)?.label??e}function VI({entry:e}){let t=Si.value.has(e.id);return i("li",{class:`session-timeline-row tone-${ZI[e.kind]??"muted"}`,children:[i("span",{class:"session-timeline-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("div",{class:"session-timeline-main",children:[i("div",{class:"session-timeline-head",children:[i("span",{class:"session-timeline-label",title:uw[_d(e.kind)],children:e.label},void 0,!1,void 0,this),e.who&&i("span",{class:"session-timeline-who",style:{"--identity-color":`hsl(${Wn(e.who)} 65% 62%)`},children:qI(e.who)},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:Od(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-timeline-body",children:e.body},void 0,!1,void 0,this),e.undoable&&!t&&i("button",{type:"button",class:"session-timeline-undo","data-testid":"timeline-undo",onClick:()=>void Sd(e),children:"↩ undo this edit"},void 0,!1,void 0,this),t&&i("div",{class:"session-timeline-undone",children:"undone · steering sent"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function dw(){let[e,t]=L(!1),n=_r.value,o=nb.value,r=Co.value,s=ib.value,a=cb.value,[c,l]=L(!1),[u,d]=L(null),p=bn();if(D(()=>{Gn()},[]),!(e||r.length>0))return i("aside",{class:"session-panel is-collapsed","aria-label":"Session (collapsed)",children:[i("button",{type:"button",class:"session-collapse",onClick:()=>t(!0),title:"Expand session panel",children:"‹"},void 0,!1,void 0,this),n&&i("span",{class:`session-collapsed-live phase-${n.phase}`,title:Un(n),"aria-label":`Session live: ${Un(n)}`,children:[i("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this),i("span",{class:"session-collapsed-label",children:"Session"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("aside",{class:"session-panel","aria-label":"Session",children:[i("header",{class:"session-panel-header",children:[i("span",{class:"session-panel-title",children:"Session"},void 0,!1,void 0,this),n&&i("span",{class:`session-live phase-${n.phase}`,title:Un(n),children:[i("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this),i("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),n&&i("button",{type:"button",class:"session-end",title:"End this session — a receipt and a snapshot of the board follow",onClick:()=>void Ya(n),children:"End"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-collapse",onClick:()=>t(!1),title:"Collapse session panel",children:"›"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(WI,{},void 0,!1,void 0,this),(()=>{let f=a.find((g)=>g.undoable&&!Si.value.has(g.id));if(!f)return null;return i("div",{class:"session-undo-row","data-testid":"session-undo-row",children:[i("span",{class:"session-undo-text",title:f.body,children:["Agent edit on top: ",f.body]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-undo-btn",onClick:()=>void Sd(f),children:"↩ Undo"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)})(),i("div",{class:"session-panel-body",children:[i("section",{class:"session-section",children:(()=>{let f=o.filter((z)=>z.status==="in-progress"||z.status==="todo").length,g=o.filter((z)=>z.status!=="cancelled"),y=g.filter((z)=>z.status==="done").length,x=o.length-g.length,h=r.length>0,v=c||h,b=f>0?`${f} running`:g.length>0?`${y}/${g.length} done${x>0?` · ${x} cancelled`:""}`:o.length>0?`${o.length} cancelled`:"none yet";return i(ve,{children:[i("button",{type:"button",class:"session-section-toggle","aria-expanded":v,"data-testid":"work-items-toggle",onClick:()=>l((z)=>!z),children:[i("span",{class:"session-section-title",children:"Work items"},void 0,!1,void 0,this),i("span",{class:"session-work-summary",children:[f>0&&i("span",{class:"session-work-dot","aria-hidden":"true"},void 0,!1,void 0,this),b]},void 0,!0,void 0,this),i("span",{class:`session-section-chevron${v?" is-open":""}`,"aria-hidden":"true",children:"›"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v&&(r.length===0&&s.length===0&&o.length===0?i("div",{class:"session-empty",children:"No work items yet — the agent's tasks and gates appear here."},void 0,!1,void 0,this):i("ul",{class:"session-list","aria-live":"polite","aria-label":"Work items and gates",children:[r.map((z)=>i(BI,{gate:z,now:p},z.id,!1,void 0,this)),s.map((z)=>i(UI,{gate:z},z.id,!1,void 0,this)),o.map((z)=>i(HI,{item:z},z.id,!1,void 0,this))]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)})()},void 0,!1,void 0,this),i("section",{class:"session-section",children:[i("h3",{class:"session-section-title",children:"Timeline"},void 0,!1,void 0,this),i("div",{class:"session-timeline-filters",role:"group","aria-label":"Filter timeline",children:lw.map((f)=>i("button",{type:"button",class:`activity-filter${To.value===f.id?" is-active":""}`,"aria-pressed":To.value===f.id,title:f.hint,onMouseEnter:()=>d(f.id),onMouseLeave:()=>d((g)=>g===f.id?null:g),onFocus:()=>d(f.id),onBlur:()=>d((g)=>g===f.id?null:g),onClick:()=>{To.value=f.id},children:f.label},f.id,!1,void 0,this))},void 0,!1,void 0,this),i("div",{class:"session-timeline-hint","data-testid":"timeline-filter-hint",children:uw[u??To.value]},void 0,!1,void 0,this),a.length===0?i("div",{class:"session-empty",children:To.value==="all"?"Nothing recorded yet.":"Nothing of this kind yet."},void 0,!1,void 0,this):i("ul",{class:"session-list session-timeline","aria-live":"polite","aria-label":"Timeline",children:a.map((f)=>i(VI,{entry:f},f.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Ld(e){if(!e||typeof e!=="object")return null;let t=e,n=(o)=>Array.isArray(o)?o.length:0;return{added:n(t.addedNodes)+n(t.addedEdges),removed:n(t.removedNodes)+n(t.removedEdges),modified:n(t.modifiedNodes)}}function pw({onOpenSnapshots:e}){let t=Qa.value,[n,o]=L(null),[r,s]=L(!1);if(!t)return null;let a=async()=>{if(!t.snapshot)return;s(!0);try{let u=await fetch(`/api/canvas/snapshots/${encodeURIComponent(t.snapshot.id)}/diff`,{headers:{"x-pmx-workbench":"1"}});if(u.ok){let d=await u.json();o(Ld(d.diff)??{added:0,removed:0,modified:0})}}finally{s(!1)}},c=new Date(t.endedAt),l=Number.isNaN(c.getTime())?"":`${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}`;return i("div",{class:"session-receipt","data-testid":"session-receipt",role:"status",children:[i("div",{class:"session-receipt-head",children:[i("span",{class:"session-receipt-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"session-receipt-title",children:[t.endedBy==="human"?"Session ended by you":t.endedBy==="idle-timeout"?"Session ended — idle timeout":t.endedBy==="agent"?"Session ended by the agent":"Session ended",l?` · ${l}`:""]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-receipt-close",onClick:fb,"aria-label":"Dismiss receipt",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-tiles",children:[i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Items"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value",children:t.counts.items},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Done"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-ok",children:t.counts.done},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.counts.cancelled>0&&i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Cancelled"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-muted",children:t.counts.cancelled},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.counts.rejected>0&&i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Rejected"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-danger",children:t.counts.rejected},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.counts.held>0&&i("div",{class:"session-receipt-tile",children:[i("span",{class:"session-receipt-tile-label",children:"Held"},void 0,!1,void 0,this),i("span",{class:"session-receipt-tile-value tone-warn",children:t.counts.held},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-note",children:t.snapshot?"A snapshot of the board from before this session is saved — restore it to undo the session.":t.unchanged?"This session changed nothing on the board — no snapshot kept.":"The board was empty when the session started — nothing to restore."},void 0,!1,void 0,this),n&&i("div",{class:"session-receipt-diff","data-testid":"session-receipt-diff",children:["This session: ",n.added," added · ",n.removed," removed · ",n.modified," modified"]},void 0,!0,void 0,this),i("div",{class:"session-receipt-actions",children:[t.snapshot&&i("button",{type:"button",class:"session-receipt-primary",disabled:r,onClick:()=>void a(),children:r?"Comparing…":"View diff"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-receipt-secondary",title:"Open the History drawer — saved boards and past sessions",onClick:e,children:"History"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var GI=[{title:"Tools",shortcuts:[{keys:"V",desc:"Select tool — drag empty space to lasso"},{keys:"Space (hold)",desc:"Pan — drag anywhere moves the board"},{keys:"A",desc:"Annotate — draw on the canvas"}]},{title:"Navigation",shortcuts:[{keys:Ze("K"),desc:"Command palette — search nodes & actions"},{keys:"Tab / Shift+Tab",desc:"Cycle through nodes"},{keys:"← ↑ → ↓",desc:"Walk graph along edges (when node focused)"},{keys:"F",desc:"Fit all nodes on screen"},{keys:Ze("0"),desc:"Reset viewport to origin"},{keys:`${Ze("+")} / ${Ze("−")}`,desc:"Zoom in / out"}]},{title:"Creation",shortcuts:[{keys:"M",desc:"New markdown note"},{keys:"I / W / H",desc:"New image / webpage / HTML surface"},{keys:"Shift+F",desc:"New file node (workspace path)"},{keys:"G / Shift+G",desc:"Group the selection (new frame when empty) / ungroup"},{keys:"Double-click",desc:"Open actions on a node or create menu on canvas"},{keys:"Drag port → node",desc:"Connect two nodes (hover to reveal ports)"}]},{title:"Selection",shortcuts:[{keys:"Click",desc:"Focus node (highlights neighbors & edges)"},{keys:"Shift+Click",desc:"Toggle node in multi-selection"},{keys:"Drag empty space",desc:"Lasso select multiple nodes"},{keys:Ur?"Delete / ⌫":"Delete / Backspace",desc:"Delete the selection (or the focused node)"},{keys:Ur?"⌘Z / ⇧⌘Z":"Ctrl+Z / Ctrl+Y",desc:"Undo / redo — agent edits included"},{keys:"Esc",desc:"Clear selection / close overlay"}]},{title:"View",shortcuts:[{keys:"?",desc:"Toggle this shortcut overlay"},{keys:"Minimap",desc:"Click/drag to navigate (toggle in the rail)"},{keys:"Right-drag",desc:"Pan the board from anywhere"}]}];function fw({onClose:e}){return i("div",{class:"shortcut-overlay-backdrop",onMouseDown:e,children:i("div",{class:"shortcut-overlay",onMouseDown:(t)=>t.stopPropagation(),children:[i("div",{class:"shortcut-overlay-header",children:[i("span",{class:"shortcut-overlay-title",children:"Keyboard Shortcuts"},void 0,!1,void 0,this),i("span",{class:"shortcut-overlay-hint",children:["Press ",i("kbd",{children:"?"},void 0,!1,void 0,this)," or ",i("kbd",{children:"Esc"},void 0,!1,void 0,this)," to close"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"shortcut-overlay-body",children:GI.map((t)=>i("div",{class:"shortcut-group",children:[i("div",{class:"shortcut-group-title",children:t.title},void 0,!1,void 0,this),t.shortcuts.map((n)=>i("div",{class:"shortcut-row",children:[i("kbd",{class:"shortcut-keys",children:n.keys},void 0,!1,void 0,this),i("span",{class:"shortcut-desc",children:n.desc},void 0,!1,void 0,this)]},n.keys,!0,void 0,this))]},t.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var mw="Before session · ";function hw(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return"";return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function XI(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let o=Math.floor(n/60);if(o<24)return`${o}h ago`;return`${Math.floor(o/24)}d ago`}function dc(e){if(!e.startsWith(mw))return null;let t=e.slice(mw.length),n=t.lastIndexOf(" · ");return n>0?t.slice(0,n):t}function gw({open:e,onClose:t,anchorRef:n}){let[o,r]=L([]),[s,a]=L(!1),[c,l]=L(!1),[u,d]=L(null),[p,m]=L(""),[f,g]=L(null),[y,x]=L({}),h=M(null),v=M(null);D(()=>{if(!e)return;a(!0),qp().then((T)=>{r(T),a(!1)})},[e]),D(()=>{if(e)setTimeout(()=>v.current?.focus(),50)},[e]),D(()=>{if(!e)return;let T=(P)=>{let Z=h.current,j=n.current;if(Z&&!Z.contains(P.target)&&j&&!j.contains(P.target))t()};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[e,t]),D(()=>{if(!e)return;let T=(P)=>{if(P.key==="Escape")t()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[e,t]);let b=O(async()=>{let T=p.trim();if(!T)return;l(!0);let P=await Vp(T);if(l(!1),P.ok&&P.snapshot)r((Z)=>[P.snapshot,...Z]),m("")},[p]),z=O(async(T)=>{g(null),d(T);let P=await Gp(T);if(d(null),P.ok)t()},[t]),F=O(async(T)=>{if((await Xp(T)).ok)r((Z)=>Z.filter((j)=>j.id!==T));g(null)},[]),_=O(async(T)=>{x((Z)=>({...Z,[T]:"loading"}));let P=await ge("snapshotDiff",`/api/canvas/snapshots/${encodeURIComponent(T)}/diff`,{});x((Z)=>({...Z,[T]:Ld(P.diff)??{added:0,removed:0,modified:0}}))},[]);if(!e)return null;let k=(T,P)=>f?.id===T.id?i(ve,{children:[i("button",{type:"button",class:`snapshot-action-btn ${f.action==="delete"?"snapshot-action-confirm":"snapshot-action-restore"}`,onClick:()=>f.action==="delete"?F(T.id):z(T.id),title:f.action==="delete"?"Confirm delete":"Confirm restore",disabled:u!==null,children:f.action==="delete"?"Delete":u===T.id?"Restoring…":"Confirm"},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn",onClick:()=>g(null),title:"Cancel",disabled:u!==null,children:"Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(ve,{children:[i("button",{type:"button",class:"snapshot-action-btn snapshot-action-restore",onClick:()=>g({id:T.id,action:"restore"}),title:"Restore this snapshot — replaces the current canvas (undoable)",disabled:u!==null,children:u===T.id?"Restoring…":P},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn snapshot-action-delete",onClick:()=>g({id:T.id,action:"delete"}),title:"Delete this snapshot","aria-label":"Delete snapshot",disabled:u!==null,children:"✕"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{ref:h,class:"snapshot-panel","data-testid":"history-drawer",role:"dialog","aria-label":"History",children:[i("div",{class:"snapshot-panel-header",children:[i("span",{class:"snapshot-panel-title",children:"History"},void 0,!1,void 0,this),i("span",{class:"snapshot-panel-sub",children:"snapshots + sessions"},void 0,!1,void 0,this),i("span",{class:"snapshot-panel-spacer"},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-panel-close",onClick:t,title:"Close","aria-label":"Close history",children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-save-form",children:[i("input",{ref:v,type:"text",class:"snapshot-name-input",value:p,onInput:(T)=>m(T.target.value),onKeyDown:(T)=>{if(T.key==="Enter")b()},placeholder:"Save a snapshot as…","aria-label":"Snapshot name",maxLength:80,disabled:c},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-save-btn",onClick:b,disabled:!p.trim()||c,children:c?"…":"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-restore-note",children:"Restoring replaces the current canvas. You can undo it if needed."},void 0,!1,void 0,this),i("div",{class:"snapshot-list",children:[s&&i("div",{class:"snapshot-empty",children:"Loading…"},void 0,!1,void 0,this),!s&&o.length===0&&i("div",{class:"snapshot-empty",children:"No history yet. Save a snapshot, or start an agent session — it snapshots for you."},void 0,!1,void 0,this),!s&&[...o.filter((T)=>dc(T.name)===null),...o.some((T)=>dc(T.name)!==null)?[{id:"__sessions-header__"}]:[],...o.filter((T)=>dc(T.name)!==null)].map((T)=>{if(T.id==="__sessions-header__")return i("div",{class:"snapshot-section-header","data-testid":"history-sessions-header",children:"Sessions"},T.id,!1,void 0,this);let P=dc(T.name),Z=y[T.id];if(P!==null)return i("div",{class:"snapshot-item is-session","data-testid":"history-session",children:[i("div",{class:"snapshot-item-head",children:[i("span",{class:"snapshot-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"snapshot-item-name",children:["Agent session — ",P]},void 0,!0,void 0,this),i("span",{class:"snapshot-item-time",children:hw(T.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:["snapshot at session start · ",T.nodeCount," node",T.nodeCount!==1?"s":"",Z&&Z!=="loading"&&i("span",{class:"snapshot-item-diff",children:[" ","· since: ",Z.added," added · ",Z.removed," removed · ",Z.modified," modified"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-actions is-session",children:[i("button",{type:"button",class:"snapshot-action-btn snapshot-action-diff",disabled:Z==="loading",onClick:()=>void _(T.id),children:Z==="loading"?"Comparing…":"View diff"},void 0,!1,void 0,this),k(T,"Restore pre-state")]},void 0,!0,void 0,this)]},T.id,!0,void 0,this);return i("div",{class:"snapshot-item","data-testid":"history-snapshot",children:[i("div",{class:"snapshot-item-head",children:[i("span",{class:"snapshot-item-glyph","aria-hidden":"true",children:"◫"},void 0,!1,void 0,this),i("span",{class:"snapshot-item-name",children:T.name},void 0,!1,void 0,this),i("span",{class:"snapshot-item-time",children:hw(T.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:[T.nodeCount," node",T.nodeCount!==1?"s":"",T.edgeCount>0?` · ${T.edgeCount} edge${T.edgeCount!==1?"s":""}`:""," · ",XI(T.createdAt)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-actions",children:k(T,"Restore")},void 0,!1,void 0,this)]},T.id,!0,void 0,this)})]},void 0,!0,void 0,this),i("div",{class:"snapshot-panel-foot",children:"Every agent session start writes a snapshot automatically."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var vw=3,yw={"waiting-approval":0,thinking:1,tooling:2,idle:3};function KI(){let e=Yx.value;if(e.length===0)return null;let t=[...e].sort((a,c)=>(yw[a.phase]??4)-(yw[c.phase]??4)),n=t.slice(0,vw),o=t.slice(vw),r=e.reduce((a,c)=>(a[c.phase]=(a[c.phase]??0)+1,a),{}),s=[r["waiting-approval"]&&`${r["waiting-approval"]} waiting on approval`,r.thinking&&`${r.thinking} thinking`,r.tooling&&`${r.tooling} running tools`,r.idle&&`${r.idle} idle`].filter(Boolean).join(", ");return i(ve,{children:[i("span",{class:"agent-chips",children:n.map((a)=>{let c=pt.value.filter((l)=>l.parentAgentId!=null&&(l.parentAgentId===a.sessionId||l.parentAgentId===a.source)).length;return i(Je,{label:`Agent session — ${a.label}`,tapToOpen:!0,body:"What this attached agent is doing right now: idle, thinking, running a tool, or waiting on your approval. Steer it from the composer below.",children:i("span",{class:`agent-chip phase-${a.phase}`,"data-phase":a.phase,style:{"--identity-color":`hsl(${Wn(a.sessionId)} 65% 62%)`},children:[i("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"agent-chip-label",children:Un(a)},void 0,!1,void 0,this),i("span",{class:"agent-chip-who hud-collapsible-text",children:a.label},void 0,!1,void 0,this),c>0&&i("span",{class:"agent-chip-workers",children:["+",c," worker",c===1?"":"s"]},void 0,!0,void 0,this),i("button",{type:"button",class:"agent-chip-end","aria-label":`End ${a.label} session`,title:`End ${a.label}'s session`,onClick:(l)=>{l.stopPropagation(),Ya({source:a.source,agentId:a.agentId})},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},a.sessionId,!1,void 0,this)})},void 0,!1,void 0,this),o.length>0&&i(Je,{label:`${e.length} agent sessions attached`,tapToOpen:!0,body:`${e.length} agents on this board — ${s}. The most active wear their own chips; the rest are here, and idle agents' cursors leave the board until they work again.`,children:i("span",{class:"agent-chip agent-chip-more","data-testid":"agent-chip-more",children:["+",o.length," · ",e.length," agents"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function JI(){let e=Co.value.length,t=_r.value!==null&&e>0,n=bn(t?1000:0);if(!t)return null;let o=Co.value.map((r)=>lc(r,n)).filter((r)=>r!==null).sort((r,s)=>r-s)[0];return i(Je,{label:"Approval gates waiting on you",tapToOpen:!0,body:"The agent is blocked until you approve or reject in the session panel; unanswered gates auto-hold when the countdown runs out.",children:i("span",{class:"gate-badge",children:[e," gate",e===1?"":"s",o!==void 0&&` · ${uc(o)}`]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function YI(e){if(e>0.9)return"danger";if(e>=0.7)return"warn";return"ok"}function Ti(e){return e>=1000?`${(e/1000).toFixed(e>=1e4?0:1)}k`:String(e)}function QI(){let e=_r.value;if(!e)return null;let t=gd.value,n=e.contextUsage,o=n?n.used:t.used,r=n?n.total:t.total,s=r>0?Math.min(1,o/r):0,a=Math.round(s*100),c=n?{label:`Context window — reported by ${e.label}`,body:`${Ti(n.used)} of ${Ti(n.total)} tokens of the agent's actual context window are used. Your ✦-pinned nodes account for ≈ ${Ti(t.used)} tokens of it.`}:{label:"Pins — pinned-context size (estimate)",body:`The nodes you pinned (✦) are what the agent is asked to carry as context: ≈ ${Ti(t.used)} of a ${Ti(t.total)}-token budget. When the agent's host reports its real context window, this meter switches to showing that instead.`};return i(Je,{label:c.label,body:c.body,tapToOpen:!0,children:i("span",{class:`context-budget tone-${YI(s)}`,"data-mode":n?"window":"pins",children:[i("span",{class:"context-budget-caption hud-collapsible-text",children:n?"Context":"Pins"},void 0,!1,void 0,this),i("span",{class:"context-budget-track","aria-hidden":"true",children:i("span",{class:"context-budget-fill",style:{width:`${a}%`}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"context-budget-label","data-testid":"budget-label",children:[o>0&&a===0?"<1":a,"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function eA(){let[e,t]=L(!1);if(_r.value)return null;return i(Je,{label:"Start an agent session",body:"Attaches a session to this board: the next agent that writes here is adopted into it, and you get the panel, composer, and receipt.",children:i("button",{type:"button",class:"start-session-btn",disabled:e,onClick:()=>{t(!0),Xn().finally(()=>t(!1))},children:[i("span",{class:"start-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),"Start agent session",i("span",{class:"beta-tag",children:"beta"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function xw(){let e=Et.value,t=Gt.value,n=re.value,o=R.value.size,r=Re.value.size,s=Go.value,a=Array.from(R.value.values()).filter((f)=>f.type==="trace").length,[c,l]=L("");D(()=>{let f=!1;return fetch("/health").then((g)=>g.ok?g.json():null).then((g)=>{if(f||typeof g?.workspace!=="string"||!g.workspace)return;let y=g.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop();if(y)l(y)}).catch(()=>{}),()=>{f=!0}},[]);let u=Ad.value,d=u??(e==="connected"&&!t?"syncing":e),p=t?[`${o} node${o!==1?"s":""}`,...r>0?[`${r} edge${r!==1?"s":""}`]:[],...a>0?[`${a} trace${a!==1?"s":""}`]:s?["trace armed"]:[]].join(" · "):"Syncing canvas…",m=()=>{let f=wt();Qo(f.width,f.height)};return i("div",{class:"top-bar",children:[i(Je,{label:`Canvas status: ${d}`,tapToOpen:!0,body:"Live updates stream in over SSE; amber means reconnecting.",align:"start",children:i("span",{class:`connection-dot ${u??e}`,"aria-label":`Canvas status: ${d}`},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"top-bar-title",title:c||"PMX Canvas",children:c||"PMX Canvas"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:dn.value?dn.value.slice(0,12):"…"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:p},void 0,!1,void 0,this),i("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),i(KI,{},void 0,!1,void 0,this),i(JI,{},void 0,!1,void 0,this),i(QI,{},void 0,!1,void 0,this),i(Jb,{},void 0,!1,void 0,this),i(eA,{},void 0,!1,void 0,this),i("div",{class:"top-bar-sep"},void 0,!1,void 0,this),i(Je,{label:"Zoom out",shortcut:Ze("−"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>Jo(0.8),"aria-label":"Zoom out",children:i(zx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Reset zoom",shortcut:Ze("0"),children:i("button",{type:"button",class:"top-bar-zoom-label",onClick:()=>$n({x:0,y:0,scale:1},250),"aria-label":"Reset view",children:[Math.round(n.scale*100),"%"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Zoom in",shortcut:Ze("+"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>Jo(1.25),"aria-label":"Zoom in",children:i(Ax,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Je,{label:"Fit all",shortcut:"F",align:"end",children:i("button",{type:"button",class:"top-bar-btn",onClick:m,"aria-label":"Fit canvas",children:i(Ua,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Kn={status:{x:40,y:80,w:300,h:120},markdown:{x:380,y:80,w:720,h:600},context:{x:1130,y:80,w:320,h:400},"mcp-app":{x:380,y:720,w:960,h:600},webpage:{x:380,y:80,w:520,h:420},"json-render":{x:380,y:720,w:840,h:620},graph:{x:380,y:720,w:760,h:520},ledger:{x:1130,y:520,w:320,h:280},trace:{x:40,y:900,w:200,h:56},file:{x:380,y:80,w:720,h:600},diff:{x:380,y:80,w:640,h:420},mermaid:{x:380,y:80,w:640,h:460},image:{x:380,y:80,w:720,h:520},html:{x:380,y:80,w:720,h:640},group:{x:220,y:60,w:840,h:560},prompt:{x:380,y:1260,w:520,h:400},response:{x:380,y:1480,w:720,h:400}};function Ei(e,t,n,o={}){let r=Kn[t];return{id:e,type:t,position:o.position??{x:r.x,y:r.y},size:o.size??{width:r.w,height:r.h},zIndex:t==="status"?0:1,collapsed:!1,pinned:!1,data:n}}var Ao=null,mc=null,pc=0,Jn=null,tA=3000,nA=2000,bw=5000,Ii=!1,_n=null,Ir=null,Qn=0,Yn=null;function oA(){if(typeof location>"u"||typeof window>"u")return null;let e=new URLSearchParams(location.search).get("transport");if(e==="poll"||e==="sse")return e;if(window.__PMX_AMP_ORB===!0)return"poll";return null}var Ar=new Map;function Ai(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function hc(e){if(!mc)return e;let t=mc.get(e.id);if(!t)return e;return{...e,position:t.position??e.position,size:t.size??e.size,collapsed:t.collapsed??e.collapsed,pinned:t.pinned??e.pinned}}function zi(e,t,n){return hc(Ei(e,t,n))}function rA(){return Gs([...R.value.values()],Kn.markdown.w,Kn.markdown.h)}function zr(){if(!R.value.has("status-main"))pn(zi("status-main","status",{phase:"idle",message:"",elapsed:0}))}function iA(e,t){let n=`md-${Ai(e)}`;if(R.value.get(n))oe(n,{path:e,title:t}),ke.value=n;else{let r=rA(),s=zi(n,"markdown",{path:e,title:t,content:"",rendered:""});s.position=r,pn(s),tt(n)}}function sA(e){if(R.value.get("context-main"))oe("context-main",{cards:e});else if(e.length>0){let o=zi("context-main","context",{cards:e});pn(o)}}function aA(e){let t=e.url,n=`mcp-${Ai(t)}`;if(R.value.get(n))oe(n,e);else pn(zi(n,"mcp-app",e)),tt(n)}function cA(e){let t=e.toolCallId,o=(typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null)??(t.startsWith("ext-app-")?t:`ext-app-${t}`);if(R.value.get(o)){oe(o,e);return}let{serverName:s,toolName:a}=e;if(s&&a){for(let[x,h]of R.value.entries())if(h.type==="mcp-app"&&h.data.mode==="ext-app"&&h.data.serverName===s&&h.data.toolName===a&&!h.data.toolResult){oe(x,{...e});return}}let{_x:c,_y:l,_width:u,_height:d}=e,p=Kn["mcp-app"],m=u??p.w,f=d??p.h,g=c===void 0||l===void 0?Gs([...R.value.values()],m,f):null,y=hc(Ei(o,"mcp-app",{mode:"ext-app",...e},{position:{x:c??g?.x??p.x,y:l??g?.y??p.y},size:{width:m,height:f}}));pn(y),tt(o,{recordHistory:!1})}function lA(e){let t=e.startsWith("ext-app-")?e:`ext-app-${e}`;if(R.value.has(t))return t;let n=`ext-app-${e}`;if(n!==t&&R.value.has(n))return n;for(let[o,r]of R.value.entries())if(r.type==="mcp-app"&&r.data.mode==="ext-app"&&r.data.toolCallId===e)return o;return null}function Cw(e){let t=typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null;if(t&&R.value.has(t))return t;if(typeof e.toolCallId!=="string"||!e.toolCallId)return null;return lA(e.toolCallId)}function Tw(e,t){if(typeof e!=="string"||!e)return null;if(typeof t!=="string"||!t)return null;let n=null;for(let[o,r]of R.value.entries())if(r.type==="mcp-app"&&r.data.mode==="ext-app"&&r.data.serverName===e&&r.data.toolName===t&&!r.data.toolResult){if(n)return null;n=o}return n}function Ew(e){if(R.value.get("ledger-main"))oe("ledger-main",e);else{let o=zi("ledger-main","ledger",e);o.collapsed=!0,pn(o)}}function Dd(e){if(!Yr(e))return;if(document.documentElement.setAttribute("data-theme",e),vr(),Xe.value!==e)Xe.value=e}function uA(e){return e==="markdown"||e==="mcp-app"||e==="webpage"||e==="json-render"||e==="graph"||e==="prompt"||e==="response"||e==="status"||e==="context"||e==="ledger"||e==="trace"||e==="file"||e==="diff"||e==="mermaid"||e==="image"||e==="html"||e==="group"}function dA(e){return e==="relation"||e==="depends-on"||e==="flow"||e==="references"}function Fd(e){if(!e||typeof e!=="object")return null;let t=e;if(typeof t.x!=="number"||typeof t.y!=="number")return null;return{x:t.x,y:t.y}}function Iw(e){if(!e||typeof e!=="object")return null;let t=e;if(typeof t.width!=="number"||typeof t.height!=="number")return null;return{width:t.width,height:t.height}}function pA(e){let t=Fd(e),n=Iw(e);return t&&n?{...t,...n}:null}function fA(e){if(typeof e.id!=="string"||!e.id)return null;if(!uA(e.type))return null;let t=Fd(e.position),n=Iw(e.size);if(!t||!n)return null;let o=e.data&&typeof e.data==="object"?Object.fromEntries(Object.entries(e.data)):{};return{id:e.id,type:e.type,position:t,size:n,zIndex:typeof e.zIndex==="number"?e.zIndex:1,collapsed:e.collapsed===!0,pinned:e.pinned===!0,data:o}}function mA(e){if(typeof e.id!=="string"||!e.id)return null;if(typeof e.from!=="string"||!e.from)return null;if(typeof e.to!=="string"||!e.to)return null;if(!dA(e.type))return null;return{id:e.id,from:e.from,to:e.to,type:e.type,...typeof e.label==="string"?{label:e.label}:{},...e.style==="solid"||e.style==="dashed"||e.style==="dotted"?{style:e.style}:{},...e.animated===!0?{animated:!0}:{}}}function hA(e){if(typeof e.id!=="string"||!e.id)return null;if(e.type!=="freehand"&&e.type!=="text")return null;if(!Array.isArray(e.points))return null;let t=e.points.map((o)=>Fd(o)).filter((o)=>o!==null),n=pA(e.bounds);if(t.length<(e.type==="text"?1:2)||!n)return null;return{id:e.id,type:e.type,points:t,bounds:n,color:typeof e.color==="string"?e.color:"#f97316",width:typeof e.width==="number"?e.width:4,...typeof e.text==="string"?{text:e.text}:{},...typeof e.label==="string"?{label:e.label}:{},createdAt:typeof e.createdAt==="string"?e.createdAt:""}}var ww="pmx-canvas-version-reload";function gA(e,t){if(typeof window>"u")return;let n=window,o=(s,a)=>typeof s==="string"&&s!==""&&s!=="unknown"&&typeof a==="string"&&a!==""&&a!=="unknown"&&s!==a;if(!o(e,n.__PMX_BOOT_SERVER_VERSION)&&!o(t,n.__PMX_BOOT_BUNDLE_STAMP))return;let r=`${String(e)}::${String(t)}`;try{if(window.sessionStorage.getItem(ww)===r)return;window.sessionStorage.setItem(ww,r)}catch{return}window.location.reload()}function vA(e){let t=qn.value[0]?.id;if(xd(e),ft.value&&qn.value[0]?.id!==t)Gn()}function yA(e){pb(e)}var _w=null;function xA(e){Nl(e)}function bA(e){if(dn.value=e.sessionId||"",Et.value="connected",co.value+=1,gA(e.version,e.bundleStamp),Dr(),Hp().then(xd),_w?.(),!os)_w=$m();if(ge("fetchHumanPresence","/api/canvas/human-presence",null).then(Nl),Zc().then((t)=>{if(Xt.value=t,ft.value)Gn()}),typeof e.theme==="string"&&!zd())Dd(e.theme);if(e.ledgerSummary)Ew(e.ledgerSummary)}function wA(e){if(typeof e.path!=="string"||!e.path)return;let t=e.path,n=(typeof e.title==="string"?e.title:"")||t.split("/").pop()||"Untitled";if(iA(t,n),e.ledgerSummary)Ew(e.ledgerSummary)}function _A(e){zr(),oe("status-main",{message:typeof e.message==="string"?e.message:String(e.message??""),level:e.level??"ok",source:e.source})}function SA(e){zr(),oe("status-main",{phase:e.phase,detail:e.detail})}function kA(e){let t=e.cards??[];sA(t)}function CA(e){if(typeof e.url==="string"&&e.url)aA({url:e.url,sourceServer:e.sourceServer,sourceTool:e.sourceTool,inferredType:e.inferredType,trustedDomain:e.trustedDomain,hostMode:e.hostMode??"hosted"})}function TA(e){let t=e.sessions??[];for(let n of t){let o=n.url;if(!o)continue;let r=`mcp-${Ai(o)}`;if(R.value.has(r))oe(r,{sessionState:n.state,lastSeenAt:n.lastSeenAt})}}function EA(e){if(typeof e.url==="string"&&e.url){let t=`mcp-${Ai(e.url)}`;if(R.value.has(t))oe(t,{hostMode:"fallback",fallbackReason:e.reasonCode})}}function IA(e){let n=R.value.get("context-main");if(!n)return;let o=(n.data.auxTabs??[]).concat(e);oe("context-main",{auxTabs:o})}function AA(e){if(R.value.has("context-main"))if(e.mode==="all")oe("context-main",{auxTabs:[]});else{let o=R.value.get("context-main");if(!o)return;let r=(o.data.auxTabs??[]).filter((s)=>s.id!==e.id);oe("context-main",{auxTabs:r})}}function zA(e){zr(),oe("status-main",{phase:"idle",lastCompletion:{tokenCount:e.tokenCount,artifactCount:e.artifactCount}})}function PA(e){zr(),oe("status-main",{phase:"tooling",detail:`${e.name}`,activeTool:e.name})}function NA(e){zr(),oe("status-main",{activeTool:null})}function RA(e){if(e.state==="active"&&e.path){let n=`md-${Ai(e.path)}`;if(R.value.has(n))oe(n,{reviewActive:!0})}}function $A(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;cA({toolCallId:e.toolCallId,...typeof e.nodeId==="string"&&e.nodeId.length>0?{nodeId:e.nodeId}:{},title:e.title,html:e.html,toolInput:e.toolInput,serverName:e.serverName,toolName:e.toolName,appSessionId:e.appSessionId,resourceUri:e.resourceUri,toolDefinition:e.toolDefinition,resourceMeta:e.resourceMeta,hostMode:"hosted",trustedDomain:!0,...e.chartConfig?{chartConfig:e.chartConfig}:{},...typeof e.x==="number"&&{_x:e.x},...typeof e.y==="number"&&{_y:e.y},...typeof e.width==="number"&&{_width:e.width},...typeof e.height==="number"&&{_height:e.height}})}function MA(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=Cw(e)??Tw(e.serverName,e.toolName);if(!t)return;if(R.value.has(t))oe(t,{html:e.html})}function OA(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=Cw(e)??Tw(e.serverName,e.toolName);if(!t)return;if(R.value.has(t)){if(e.success===!1){It(t);return}oe(t,{toolResult:td({result:e.result,success:typeof e.success==="boolean"?e.success:void 0,error:typeof e.error==="string"?e.error:void 0,content:typeof e.content==="string"?e.content:void 0,detailedContent:typeof e.detailedContent==="string"?e.detailedContent:void 0})})}}function LA(e){zr(),oe("status-main",{subagent:{state:e.state,name:e.agentDisplayName??e.agentName}})}function DA(e){let t=e.nodeId;if(!t)return;let n=e.text||"",{position:o,parentNodeId:r,contextNodeIds:s}=e;if(e.threadNodeId&&R.value.has(e.threadNodeId)){let a=e.threadNodeId,c=R.value.get(a);if(!c)return;let l=Array.isArray(c.data.turns)?[...c.data.turns]:[],u=l[l.length-1];if(!u||u.role!=="user"||u.text!==n)l.push({role:"user",text:n,status:"pending"});oe(a,{turns:l,threadStatus:"pending"});return}if(!R.value.has(t)){let a=o??Kn.prompt;pn(hc(Ei(t,"prompt",{text:n,turns:n?[{role:"user",text:n,status:"pending"}]:[],threadStatus:n?"pending":"draft",status:n?"pending":"draft",parentNodeId:r,contextNodeIds:s},{position:{x:a.x,y:a.y}}))),tt(t)}if(r&&R.value.has(r))Ss({id:`edge-${r}-${t}`,from:r,to:t,type:"flow",style:"dashed"})}function FA(e){let{nodeId:t,status:n}=e;if(t&&R.value.has(t))oe(t,{status:n})}function jA(e){let{responseNodeId:t,promptNodeId:n}=e;if(!t)return;let o=n?R.value.get(n):void 0;if(o&&Array.isArray(o.data.turns)){Ar.set(t,n);let s=[...o.data.turns];s.push({role:"assistant",text:"",status:"streaming"}),oe(n,{turns:s,threadStatus:"streaming",_activeResponseId:t}),tt(n);return}let r=o?{x:o.position.x,y:o.position.y+o.size.height+24}:{x:Kn.response.x,y:Kn.response.y};if(!R.value.has(t))pn(hc(Ei(t,"response",{content:"",status:"streaming",promptNodeId:n},{position:r})));if(n)Ss({id:`edge-${n}-${t}`,from:n,to:t,type:"flow",animated:!0});tt(t)}function ZA(e){let t=e.responseNodeId;if(!t)return;let n=Ar.get(t);if(n){let o=R.value.get(n);if(o&&Array.isArray(o.data.turns)){let r=[...o.data.turns],s=r[r.length-1];if(s&&s.role==="assistant")s.text=e.content,s.status="streaming";oe(n,{turns:r,threadStatus:"streaming"})}return}if(!R.value.has(t))return;oe(t,{content:e.content,status:"streaming"})}function HA(e){let t=e.responseNodeId;if(!t)return;let n=Ar.get(t);if(n){let s=R.value.get(n);if(s&&Array.isArray(s.data.turns)){let a=[...s.data.turns],c=a[a.length-1];if(c&&c.role==="assistant")c.text=e.content,c.status="complete";oe(n,{turns:a,threadStatus:"answered",_activeResponseId:void 0})}Ar.delete(t);return}if(!R.value.has(t))return;oe(t,{content:e.content,status:"complete"});let r=R.value.get(t)?.data.promptNodeId;if(r){let s=`edge-${r}-${t}`,a=Re.value.get(s);if(a)Ef(s),Ss({...a,animated:!1})}}function BA(e){let t=e.layout;if(!t?.nodes)return;let n=!Gt.value;Gt.value=!0;let o=t.nodes.map(fA).filter((c)=>c!==null),r=Array.isArray(t.edges)?t.edges.map(mA).filter((c)=>c!==null):Array.from(Re.value.values()),s=Array.isArray(t.annotations)?t.annotations.map(hA).filter((c)=>c!==null):void 0,a=t.viewport?{x:typeof t.viewport.x==="number"?t.viewport.x:0,y:typeof t.viewport.y==="number"?t.viewport.y:0,scale:typeof t.viewport.scale==="number"?t.viewport.scale:1}:void 0;if(n)Yo();Rf({...a?{viewport:a}:{},nodes:o,edges:r,...s?{annotations:s}:{}},{applyViewport:n}),Kc({event:"canvas-layout-update",data:e})}function UA(e){if(e<=1)return 500;if(e===2)return 1000;return Math.min(2500,1500+(e-3)*500)}function WA(e){let t=e.nodeId;if(t&&R.value.has(t)){if(e.noPan===!0){fn(t);return}tt(t)}}function qA(e){let t=e.viewport;if(!t)return;let n=typeof t.x==="number"?t.x:0,o=typeof t.y==="number"?t.y:0,r=typeof t.scale==="number"?t.scale:1;Yo(),zf({x:n,y:o,scale:r})}function VA(e){if(R.value.get("context-main"))oe("context-main",{currentTokens:e.currentTokens,tokenLimit:e.tokenLimit,messagesLength:e.messagesLength,utilization:e.utilization,nearLimit:e.nearLimit})}function GA(e){Go.value=e.enabled===!0}function XA(e){if(typeof e.theme==="string"&&!zd())Dd(e.theme)}function KA(e){let t=Array.isArray(e.nodeIds)?e.nodeIds.filter((n)=>typeof n==="string"):[];Tf(t),Kc({event:"context-pins-changed",data:e})}var fc=null;function Sw(){if(fc)clearTimeout(fc);fc=setTimeout(()=>{if(fc=null,Zc().then((e)=>{Xt.value=e}),ft.value)Gn()},150)}function JA(e){let t=e.intent;if(!t||typeof t.id!=="string"||typeof t.kind!=="string"||typeof t.expiresAt!=="number")return;Tm(t)}function YA(e){let t=typeof e.id==="string"?e.id:"";if(!t)return;if(e.settled===!0)Im(t,typeof e.nodeId==="string"?e.nodeId:void 0);else zl(t)}var Aw={connected:bA,"workbench-open":wA,"canvas-status":_A,"execution-phase":SA,"context-cards":kA,"mcp-app-candidate":CA,"mcp-app-host-snapshot":TA,"mcp-app-host-fallback":EA,"aux-open":IA,"aux-close":AA,"assistant-complete":zA,"tool-start":PA,"tool-complete":NA,"review-state":RA,"subagent-status":LA,"ext-app-open":$A,"ext-app-update":MA,"ext-app-result":OA,"context-pins-changed":KA,"canvas-layout-update":BA,"canvas-focus-node":WA,"canvas-viewport-update":qA,"context-usage":VA,"trace-state":GA,"theme-changed":XA,"canvas-prompt-created":DA,"canvas-prompt-status":FA,"canvas-response-start":jA,"canvas-response-delta":ZA,"canvas-response-complete":HA,"ax-state-changed":Sw,"ax-event-created":Sw,"ax-intent":JA,"ax-intent-clear":YA,"agent-presence":vA,"human-presence":xA,"agent-session-ended":yA};function zw(e,t){let n=Aw[e];if(!n)return;let o=n;try{o(t)}catch(r){console.warn(`[sse-bridge] Handler for "${e}" failed:`,r)}}function kw(){Ii=!0,Qn+=1;let e=Qn;Et.value="connecting";let t=null,n=!1,o=async()=>{if(e!==Qn)return;try{let r=new URLSearchParams;if(Ir!==null)r.set("since",String(Ir));let s=dn.value;if(s)r.set("session",s);let a=r.toString(),c=await fetch(`/api/workbench/poll${a?`?${a}`:""}`);if(e!==Qn)return;if(!c.ok)throw Error(`poll failed with HTTP ${c.status}`);let l=await c.json();if(e!==Qn)return;if(!l.ok)throw Error("poll returned ok: false");let u=t;if(t=l.sessionId??null,u!==null&&l.sessionId&&u!==l.sessionId&&!l.snapshot){Ir=null,_n=setTimeout(()=>void o(),0);return}if(l.snapshot&&n)mc=sl(),Gt.value=!1,Xc(),Pl(),Ar.clear();for(let d of l.events)zw(d.event,d.payload);n=!0,Ir=l.seq,lo.value=0,uo.value=0,Et.value="connected",_n=setTimeout(()=>void o(),nA)}catch(r){if(e!==Qn)return;console.warn("[sse-bridge] poll transport error:",r),Et.value="disconnected",lo.value+=1,uo.value=bw,_n=setTimeout(()=>void o(),bw)}};return o(),()=>{if(Qn+=1,Ii=!1,Ir=null,_n)clearTimeout(_n),_n=null}}function jd(){if(Bb(Dd),mc=sl(),Gt.value=!1,Xc(),Pl(),Ar.clear(),Jn)clearTimeout(Jn),Jn=null;let e=oA();if(e==="poll"||Ii)return kw();let t=dn.value,n=t?`/api/workbench/events?session=${t}`:"/api/workbench/events";Et.value="connecting";let o=new EventSource(n);Ao=o;let r=!1;if(Yn)clearTimeout(Yn);if(Yn=null,e!=="sse")Yn=setTimeout(()=>{if(Yn=null,r||Ao!==o)return;console.warn("[sse-bridge] No SSE event within watchdog window — switching to polling transport."),window.dispatchEvent(new Event("pmx-canvas-boot-extend")),o.close(),Ao=null,kw()},tA);for(let[s]of Object.entries(Aw))o.addEventListener(s,(a)=>{r=!0;try{zw(s,JSON.parse(a.data))}catch(c){console.warn(`[sse-bridge] Failed to parse "${s}" event:`,c)}});return o.onopen=()=>{if(Ao!==o)return;pc=0,lo.value=0,uo.value=0,Et.value="connected"},o.onerror=()=>{if(Ao!==o)return;Et.value="disconnected",o.close(),Ao=null,pc+=1;let s=UA(pc);lo.value=pc,uo.value=s,Jn=setTimeout(()=>{Jn=null,jd()},s)},()=>{if(Jn)clearTimeout(Jn),Jn=null;if(Yn)clearTimeout(Yn),Yn=null;if(Ii){if(Qn+=1,Ii=!1,Ir=null,_n)clearTimeout(_n),_n=null}o.close(),Ao=null}}function zo(e,t){console.error(`[app] ${e} failed`,t)}function Pw(){let[e,t]=L(!0),[n,o]=L(!1),[r,s]=L(!1),[a,c]=L(!1),[l,u]=L(null),d=M(null),{menu:p,openNodeMenu:m,openCanvasMenu:f,openEdgeMenu:g,closeMenu:y}=Wb(),x=Gt.value,h=ft.value,v=O(()=>t((P)=>!P),[]),b=O(()=>o((P)=>!P),[]),z=O(()=>o(!1),[]),F=O((P)=>u(P),[]),_=O((P,Z)=>{$n({x:P,y:Z,scale:re.value.scale},200)},[]);D(()=>jd(),[]),D(()=>{let P=null,Z=()=>{if(P!==null)window.clearTimeout(P);P=window.setTimeout(()=>{P=null,Dr()},400)};return window.addEventListener("resize",Z),()=>{if(P!==null)window.clearTimeout(P);window.removeEventListener("resize",Z)}},[]),D(()=>{let P=(E)=>{let B=(E.metaKey||E.ctrlKey)&&!E.altKey;if(B&&E.key==="k"){E.preventDefault(),s((U)=>!U);return}if(E.key==="Escape"&&l){E.preventDefault(),u(null);return}if(E.key==="Escape"&&Be.value&&!Qt.value){E.preventDefault(),po();return}if(E.key==="Escape"&&r){E.preventDefault(),s(!1);return}if(E.key==="Escape"&&a){E.preventDefault(),c(!1);return}let W=E.target,H=W?.tagName;if(H==="INPUT"||H==="TEXTAREA"||W?.isContentEditable)return;if(E.key===" "&&!E.repeat&&!B){E.preventDefault(),Br.value=!0;return}if(E.key==="?"||E.key==="/"&&E.shiftKey){E.preventDefault(),c((U)=>!U);return}if(B&&(E.key==="z"||E.key==="Z"))E.preventDefault(),kd(E.shiftKey);else if(B&&(E.key==="y"||E.key==="Y"))E.preventDefault(),kd(!0);else if(B&&E.key==="0")E.preventDefault(),$n({x:0,y:0,scale:1},250);else if(B&&(E.key==="="||E.key==="+"))E.preventDefault(),Jo(1.25);else if(B&&E.key==="-")E.preventDefault(),Jo(0.8);else if(E.key==="Escape"){if(ye.value.size>0||un.value!==null){ht();return}ke.value=null,y()}else if(E.key==="Tab")E.preventDefault(),Mf(E.shiftKey?-1:1);else if(E.key==="Delete"||E.key==="Backspace"){if(un.value!==null){let ee=un.value;E.preventDefault(),un.value=null,ds(ee).catch((xe)=>zo("delete-edge",xe));return}let U=ye.value.size>0?[...ye.value]:ke.value?[ke.value]:[];if(U.length===0)return;E.preventDefault();for(let ee of U)It(ee),In(ee).catch((xe)=>zo("delete",xe));ht(),ke.value=null}else if(ke.value&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(E.key)){E.preventDefault();let U=E.key.replace("Arrow","").toLowerCase();Of(U)}else if(!B&&!E.altKey){let U=E.key.toLowerCase();if(U==="v"&&!E.shiftKey)yt.value="select";else if(U==="c"&&!E.shiftKey&&!B)E.preventDefault(),yt.value=yt.value==="connect"?"select":"connect";else if(U==="m"&&!E.shiftKey)E.preventDefault(),Pt({type:"markdown",title:"New note",width:520,height:360}).catch((ee)=>zo("create markdown",ee));else if(U==="a"&&!E.shiftKey)E.preventDefault(),u((ee)=>ee==="pen"?null:"pen");else if(U==="g"&&!E.shiftKey){E.preventDefault();let ee=Array.from(ye.value);if(ee.length>=2)jo({title:"Group",childIds:ee}).catch((xe)=>zo("group selection",xe)),ht();else Pt({type:"group",title:"Group"}).catch((xe)=>zo("create group",xe))}else if(U==="g"&&E.shiftKey){E.preventDefault();for(let ee of _f())It(ee),Zo(ee).catch((xe)=>zo("ungroup",xe));ht()}else if(U==="i"&&!E.shiftKey)E.preventDefault(),wn("image");else if(U==="w"&&!E.shiftKey)E.preventDefault(),wn("webpage");else if(U==="h"&&!E.shiftKey)E.preventDefault(),Pt({type:"html",title:"HTML surface"}).catch((ee)=>zo("create html",ee));else if(U==="f"&&E.shiftKey)E.preventDefault(),wn("file");else if(U==="f"&&!E.shiftKey){E.preventDefault();let ee=wt();Qo(ee.width,ee.height)}}},Z=(E)=>{if(E.key===" ")Br.value=!1},j=()=>{Br.value=!1};return document.addEventListener("keydown",P),document.addEventListener("keyup",Z),window.addEventListener("blur",j),()=>{document.removeEventListener("keydown",P),document.removeEventListener("keyup",Z),window.removeEventListener("blur",j)}},[l,y,r,a]),D(()=>{let P=window.setTimeout(()=>void Dr(),250);return()=>window.clearTimeout(P)},[h]),D(()=>{if(!x)return;let P=window.__pmxCanvasBootstrapReady;if(typeof P==="function")P()},[x]);let k=Array.from(R.value.values()),T=wt();return i("div",{class:"app-shell","data-session-active":h?"true":"false",children:[i(Xb,{minimapVisible:e,onToggleMinimap:v,snapshotOpen:n,onToggleSnapshot:b,snapshotBtnRef:d,onOpenPalette:()=>s(!0),onOpenShortcuts:()=>c((P)=>!P),annotationTool:l,onSetAnnotationTool:F},void 0,!1,void 0,this),i("div",{class:"app-main",children:[i(xw,{},void 0,!1,void 0,this),i(jb,{},void 0,!1,void 0,this),i("div",{class:"canvas-region",ref:(P)=>Mp(P),children:[i(Db,{onNodeContextMenu:m,onCanvasContextMenu:f,onEdgeContextMenu:g,annotationMode:l!==null,annotationTool:l},void 0,!1,void 0,this),i($p,{},void 0,!1,void 0,this),i(Rp,{},void 0,!1,void 0,this),i(Yb,{},void 0,!1,void 0,this),i(Qb,{},void 0,!1,void 0,this),x&&k.length===0&&Ve.value.size===0&&i(Kb,{onOpenPalette:()=>s(!0)},void 0,!1,void 0,this),ye.value.size>0&&i(cw,{},void 0,!1,void 0,this),h?i(Fb,{},void 0,!1,void 0,this):Ee.value.size>0&&i(Gb,{},void 0,!1,void 0,this),i(pw,{onOpenSnapshots:()=>o(!0)},void 0,!1,void 0,this),i(Lp,{},void 0,!1,void 0,this),Be.value&&i(ow,{},void 0,!1,void 0,this),i(gw,{open:n,onClose:z,anchorRef:d},void 0,!1,void 0,this),e&&i(aw,{viewport:re,nodes:R,edges:Re,onNavigate:_,containerWidth:T.width,containerHeight:T.height},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h&&i(dw,{},void 0,!1,void 0,this),p&&i(qb,{menu:p,onClose:y},void 0,!1,void 0,this),r&&i(Ub,{onClose:()=>s(!1),onToggleMinimap:v},void 0,!1,void 0,this),a&&i(fw,{onClose:()=>c(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}Ff();var Nw=document.getElementById("app");if(Nw)cp(i(Pw,{},void 0,!1,void 0,this),Nw);