pmx-canvas 0.8.0 → 0.8.2

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.
@@ -19,7 +19,7 @@ var g0=Object.create;var{getPrototypeOf:v0,defineProperty:af,getOwnPropertyNames
19
19
 
20
20
  ${l}${u}
21
21
 
22
- `}}};Zo.tableCaption={filter:["caption"],replacement:()=>""};Zo.tableColgroup={filter:["colgroup","col"],replacement:()=>""};Zo.tableSection={filter:["thead","tbody","tfoot"],replacement:function(e){return e}};function LE(e){var t=e.parentNode;return t.nodeName==="THEAD"||t.firstChild===e&&(t.nodeName==="TABLE"||DE(t))&&ME.call(e.childNodes,function(n){return n.nodeName==="TH"})}function DE(e){var t=e.previousSibling;return e.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function Zx(e,t=null,n=null){if(n===null)n=RE.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=HE(r,t," ");return o+r+" |"}function Wx(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(Wx(n))return!0}return!1}var Qd=(e,t)=>{if(!e.childNodes)return!1;for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(t==="code"&&Yd&&Yd(o))return!0;if(t.includes(o.nodeName))return!0;if(Qd(o,t))return!0}return!1},qx=(e,t)=>{let n=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];if(t.preserveNestedTables)n.push("TABLE");return Qd(e,"code")||Qd(e,n)};function ep(e){let t=Dx.get(e);if(t!==void 0)return t;let n=FE(e);return Dx.set(e,n),n}function FE(e){if(!e)return!0;if(!e.rows)return!0;if(e.rows.length===1&&e.rows[0].childNodes.length<=1)return!0;if(Wx(e))return!0;return!1}function BE(e){let t=e.parentNode;while(t.nodeName!=="DIV")if(t=t.parentNode,!t)return null;return t}function Gx(e){let t=e.parentNode;while(t.nodeName!=="TABLE")if(t=t.parentNode,!t)return null;return t}function HE(e,t,n){let o=t.getAttribute("colspan")||1;for(let r=1;r<o;r++)e+=" | "+n.repeat(3);return e}function Vx(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 Xx(e){Yd=e.isCodeBlock,Hx=e.options,e.keep(function(n){if(n.nodeName==="TABLE"&&qx(n,e.options))return!0;return!1});for(var t in Zo)e.addRule(t,Zo[t])}function Kx(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 jE(e){e.use([Fx,Bx,Xx,Kx])}Jx.gfm=jE;Jx.highlightedCodeBlock=Fx;Jx.strikethrough=Bx;Jx.tables=Xx;Jx.taskListItems=Kx});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 wa,$e,mf,hu,Ao,lf,ff,hf,gf,gu,pu,mu,k0,ya={},ba=[],T0=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_a=Array.isArray;function ro(e,t){for(var n in t)e[n]=t[n];return e}function vu(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function C0(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?wa.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 va(e,a,o,r,null)}function va(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?++mf:r,__i:-1,__u:0};return r==null&&$e.vnode!=null&&$e.vnode(s),s}function _e(e){return e.children}function qr(e,t){this.props=e,this.context=t}function Gr(e,t){if(t==null)return e.__?Gr(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"?Gr(e):null}function E0(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,o=[],r=[],s=ro({},t);s.__v=t.__v+1,$e.vnode&&$e.vnode(s),yu(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,o,n==null?Gr(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,xf(o,s,r),t.__e=t.__=null,s.__e!=n&&vf(s)}}function vf(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}),vf(e)}function uf(e){(!e.__d&&(e.__d=!0)&&Ao.push(e)&&!xa.__r++||lf!=$e.debounceRendering)&&((lf=$e.debounceRendering)||ff)(xa)}function xa(){try{for(var e,t=1;Ao.length;)Ao.length>t&&Ao.sort(hf),e=Ao.shift(),t=Ao.length,E0(e)}finally{Ao.length=xa.__r=0}}function yf(e,t,n,o,r,s,a,c,l,u,p){var d,m,f,h,v,x,g,b=o&&o.__k||ba,I=t.length;for(l=A0(n,t,b,l,I),d=0;d<I;d++)(f=n.__k[d])!=null&&(m=f.__i!=-1&&b[f.__i]||ya,f.__i=d,x=yu(e,f,m,r,s,a,c,l,u,p),h=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&bu(m.ref,null,f),p.push(f.ref,f.__c||h,f)),v==null&&h!=null&&(v=h),(g=!!(4&f.__u))||m.__k===f.__k?l=bf(f,l,e,g):typeof f.type=="function"&&x!==void 0?l=x:h&&(l=h.nextSibling),f.__u&=-7);return n.__e=v,l}function A0(e,t,n,o,r){var s,a,c,l,u,p=n.length,d=p,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]=va(null,a,null,null,null):_a(a)?a=e.__k[s]=va(_e,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=e.__k[s]=va(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=I0(a,n,l,d))!=-1&&(d--,(c=n[u])&&(c.__u|=2)),c==null||c.__v==null?(u==-1&&(r>p?m--:r<p&&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(d)for(s=0;s<p;s++)(c=n[s])!=null&&(2&c.__u)==0&&(c.__e==o&&(o=Gr(c)),_f(c,c));return o}function bf(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=bf(r[s],t,n,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=Gr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function I0(e,t,n,o){var r,s,a,{key:c,type:l}=e,u=t[n],p=u!=null&&(2&u.__u)==0;if(u===null&&c==null||p&&c==u.key&&l==u.type)return n;if(o>(p?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 df(e,t,n){t[0]=="-"?e.setProperty(t,n==null?"":n):e[t]=n==null?"":typeof n!="number"||T0.test(t)?n:n+"px"}function ga(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||df(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||df(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(gf,"$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=gu,e.addEventListener(t,s?mu:pu,s)):e.removeEventListener(t,s?mu:pu,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 pf(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=gu++;else if(t.t<n.u)return;return n($e.event?$e.event(t):t)}}}function yu(e,t,n,o,r,s,a,c,l,u){var p,d,m,f,h,v,x,g,b,I,R,M,_,N,w,k=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),s=[c=t.__e=n.__e]),(p=$e.__b)&&p(t);e:if(typeof k=="function")try{if(g=t.props,b=k.prototype&&k.prototype.render,I=(p=k.contextType)&&o[p.__c],R=p?I?I.props.value:p.__:o,n.__c?x=(d=t.__c=n.__c).__=d.__E:(b?t.__c=d=new k(g,R):(t.__c=d=new qr(g,R),d.constructor=k,d.render=N0),I&&I.sub(d),d.state||(d.state={}),d.__n=o,m=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&k.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ro({},d.__s)),ro(d.__s,k.getDerivedStateFromProps(g,d.__s))),f=d.props,h=d.state,d.__v=t,m)b&&k.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&k.getDerivedStateFromProps==null&&g!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(g,R),t.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(g,d.__s,R)===!1){t.__v!=n.__v&&(d.props=g,d.state=d.__s,d.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(z){z&&(z.__=t)}),ba.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(g,d.__s,R),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,h,v)})}if(d.context=R,d.props=g,d.__P=e,d.__e=!1,M=$e.__r,_=0,b)d.state=d.__s,d.__d=!1,M&&M(t),p=d.render(d.props,d.state,d.context),ba.push.apply(d.__h,d._sb),d._sb=[];else do d.__d=!1,M&&M(t),p=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++_<25);d.state=d.__s,d.getChildContext!=null&&(o=ro(ro({},o),d.getChildContext())),b&&!m&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(f,h)),N=p!=null&&p.type===_e&&p.key==null?wf(p.props.children):p,c=yf(e,_a(N)?N:[N],t,n,o,r,s,a,c,l,u),d.base=t.__e,t.__u&=-161,d.__h.length&&a.push(d),x&&(d.__E=d.__=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(w=s.length;w--;)vu(s[w]);fu(t)}else t.__e=n.__e,t.__k=n.__k,z.then||fu(t);$e.__e(z,t,n)}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=P0(n.__e,t,n,o,r,s,a,l,u);return(p=$e.diffed)&&p(t),128&t.__u?void 0:c}function fu(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(fu))}function xf(e,t,n){for(var o=0;o<n.length;o++)bu(n[o],n[++o],n[++o]);$e.__c&&$e.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(s){s.call(r)})}catch(s){$e.__e(s,r.__v)}})}function wf(e){return typeof e!="object"||e==null||e.__b>0?e:_a(e)?e.map(wf):ro({},e)}function P0(e,t,n,o,r,s,a,c,l){var u,p,d,m,f,h,v,x=n.props||ya,{props:g,type:b}=t;if(b=="svg"?r="http://www.w3.org/2000/svg":b=="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==!!b&&(b?f.localName==b:f.nodeType==3)){e=f,s[u]=null;break}}if(e==null){if(b==null)return document.createTextNode(g);e=document.createElementNS(r,b,g.is&&g),c&&($e.__m&&$e.__m(t,s),c=!1),s=null}if(b==null)x===g||c&&e.data==g||(e.data=g);else{if(s=s&&wa.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"?d=f:u=="children"||(u in g)||u=="value"&&("defaultValue"in g)||u=="checked"&&("defaultChecked"in g)||ga(e,u,null,f,r);for(u in g)f=g[u],u=="children"?m=f:u=="dangerouslySetInnerHTML"?p=f:u=="value"?h=f:u=="checked"?v=f:c&&typeof f!="function"||x[u]===f||ga(e,u,f,x[u],r);if(p)c||d&&(p.__html==d.__html||p.__html==e.innerHTML)||(e.innerHTML=p.__html),t.__k=[];else if(d&&(e.innerHTML=""),yf(t.type=="template"?e.content:e,_a(m)?m:[m],t,n,o,b=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&Gr(n,0),c,l),s!=null)for(u=s.length;u--;)vu(s[u]);c||(u="value",b=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[u]||b=="progress"&&!h||b=="option"&&h!=x[u])&&ga(e,u,h,x[u],r),u="checked",v!=null&&v!=e[u]&&ga(e,u,v,x[u],r))}return e}function bu(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){$e.__e(r,n)}}function _f(e,t,n){var o,r;if($e.unmount&&$e.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||bu(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){$e.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(r=0;r<o.length;r++)o[r]&&_f(o[r],t,n||typeof e.type!="function");n||vu(e.__e),e.__c=e.__=e.__e=void 0}function N0(e,t,n){return this.constructor(e,n)}function Qi(e,t,n){var o,r,s,a;t==document&&(t=document.documentElement),$e.__&&$e.__(e,t),r=(o=typeof n=="function")?null:n&&n.__k||t.__k,s=[],a=[],yu(t,e=(!o&&n||t).__k=C0(_e,null,[e]),r||ya,ya,t.namespaceURI,!o&&n?[n]:r?null:t.firstChild?wa.call(t.childNodes):null,s,!o&&n?n:r?r.__e:t.firstChild,o,a),xf(s,e,a)}wa=ba.slice,$e={__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}},mf=0,hu=function(e){return e!=null&&e.constructor===void 0},qr.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ro({},this.state),typeof e=="function"&&(e=e(ro({},n),this.props)),e&&ro(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),uf(this))},qr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),uf(this))},qr.prototype.render=_e,Ao=[],ff=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,hf=function(e,t){return e.__v.__b-t.__v.__b},xa.__r=0,gf=/(PointerCapture)$|Capture$/i,gu=0,pu=pf(!1),mu=pf(!0),k0=0;var Vr,dt,xu,Sf,es=0,Nf=[],mt=$e,{__b:kf,__r:Tf,diffed:Cf,__c:Ef,unmount:Af,__:If}=mt;function ka(e,t){mt.__h&&mt.__h(dt,e,es||t),es=0;var n=dt.__H||(dt.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function A(e){return es=1,z0(zf,e)}function z0(e,t,n){var o=ka(Vr++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):zf(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=dt,!dt.__f)){var r=function(c,l,u){if(!o.__c.__H)return!0;var p=o.__c.__H.__.filter(function(m){return m.__c});if(p.every(function(m){return!m.__N}))return!s||s.call(this,c,l,u);var d=o.__c.props!==c;return p.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(d=!0)}}),s&&s.call(this,c,l,u)||d};dt.__f=!0;var s=dt.shouldComponentUpdate,a=dt.componentWillUpdate;dt.componentWillUpdate=function(c,l,u){if(this.__e){var p=s;s=void 0,r(c,l,u),s=p}a&&a.call(this,c,l,u)},dt.shouldComponentUpdate=r}return o.__N||o.__}function H(e,t){var n=ka(Vr++,3);!mt.__s&&_u(n.__H,t)&&(n.__=e,n.u=t,dt.__H.__h.push(n))}function _n(e,t){var n=ka(Vr++,4);!mt.__s&&_u(n.__H,t)&&(n.__=e,n.u=t,dt.__h.push(n))}function L(e){return es=5,Be(function(){return{current:e}},[])}function Be(e,t){var n=ka(Vr++,7);return _u(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function j(e,t){return es=8,Be(function(){return e},t)}function R0(){for(var e;e=Nf.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Sa),t.__h.some(wu),t.__h=[]}catch(n){t.__h=[],mt.__e(n,e.__v)}}}mt.__b=function(e){dt=null,kf&&kf(e)},mt.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),If&&If(e,t)},mt.__r=function(e){Tf&&Tf(e),Vr=0;var t=(dt=e.__c).__H;t&&(xu===dt?(t.__h=[],dt.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Sa),t.__h.some(wu),t.__h=[],Vr=0)),xu=dt},mt.diffed=function(e){Cf&&Cf(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Nf.push(t)!==1&&Sf===mt.requestAnimationFrame||((Sf=mt.requestAnimationFrame)||M0)(R0)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),xu=dt=null},mt.__c=function(e,t){t.some(function(n){try{n.__h.some(Sa),n.__h=n.__h.filter(function(o){return!o.__||wu(o)})}catch(o){t.some(function(r){r.__h&&(r.__h=[])}),t=[],mt.__e(o,n.__v)}}),Ef&&Ef(e,t)},mt.unmount=function(e){Af&&Af(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(o){try{Sa(o)}catch(r){t=r}}),n.__H=void 0,t&&mt.__e(t,n.__v))};var Pf=typeof requestAnimationFrame=="function";function M0(e){var t,n=function(){clearTimeout(o),Pf&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);Pf&&(t=requestAnimationFrame(n))}function Sa(e){var t=dt,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),dt=t}function wu(e){var t=dt;e.__c=e.__(),dt=t}function _u(e,t){return!e||e.length!==t.length||t.some(function(n,o){return n!==e[o]})}function zf(e,t){return typeof t=="function"?t(e):t}var xR=Object.freeze({status:"aborted"});function B(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,p=Object.keys(u);for(let d=0;d<p.length;d++){let m=p[d];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 p of u._zod.deferred)p();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 wR=Symbol("zod_brand");class io extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ts extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}var Ta={};function Sn(e){if(e)Object.assign(Ta,e);return Ta}function Ea(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 ku(e,t="|"){return e.map((n)=>Au(n)).join(t)}function ns(e,t){if(typeof t==="bigint")return t.toString();return t}function os(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Aa(e){return e===null||e===void 0}function Ia(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Mf(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 Rf=Symbol("evaluating");function De(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===Rf)return;if(o===void 0)o=Rf,o=n();return o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ur(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Io(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Tu(e){return JSON.stringify(e)}function $f(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Cu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Xr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Of=os(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function dr(e){if(Xr(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(Xr(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Eu(e){if(dr(e))return{...e};if(Array.isArray(e))return[...e];return e}var Lf=new Set(["string","number","symbol"]);function Po(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wn(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function ee(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 Au(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Df(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ff={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 $0(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=Io(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 ur(this,"shape",a),a},checks:[]});return Wn(e,s)}function O0(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=Io(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 ur(this,"shape",a),a},checks:[]});return Wn(e,s)}function L0(e,t){if(!dr(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=Io(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return ur(this,"shape",s),s}});return Wn(e,r)}function D0(e,t){if(!dr(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Io(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return ur(this,"shape",o),o}});return Wn(e,n)}function F0(e,t){let n=Io(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return ur(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return Wn(e,n)}function B0(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=Io(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 ur(this,"shape",l),l},checks:[]});return Wn(t,a)}function H0(e,t,n){let o=Io(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 ur(this,"shape",s),s}});return Wn(t,o)}function pr(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 No(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Ca(e){return typeof e==="string"?e:e?.message}function qn(e,t,n){let o={...e,path:e.path??[]};if(!e.message){let r=Ca(e.inst?._zod.def?.error?.(e))??Ca(t?.error?.(e))??Ca(n.customError?.(e))??Ca(n.localeError?.(e))??"Invalid input";o.message=r}if(delete o.inst,delete o.continue,!t?.reportInput)delete o.input;return o}function Pa(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Bf(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 mr(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}var Hf=(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,ns,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Na=B("$ZodError",Hf),Iu=B("$ZodError",Hf,{Parent:Error});function jf(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 Uf(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 za=(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 io;if(a.issues.length){let c=new(r?.Err??e)(a.issues.map((l)=>qn(l,s,Sn())));throw Cu(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)=>qn(l,s,Sn())));throw Cu(c,r?.callee),c}return a.value};var rs=(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 io;return s.issues.length?{success:!1,error:new(e??Na)(s.issues.map((a)=>qn(a,r,Sn())))}:{success:!0,data:s.value}},is=rs(Iu),ss=(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)=>qn(a,r,Sn())))}:{success:!0,data:s.value}},Ma=ss(Iu),Zf=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return za(e)(t,n,r)};var Wf=(e)=>(t,n,o)=>za(e)(t,n,o);var qf=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Ra(e)(t,n,r)};var Gf=(e)=>async(t,n,o)=>Ra(e)(t,n,o);var Vf=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return rs(e)(t,n,r)};var Xf=(e)=>(t,n,o)=>rs(e)(t,n,o);var Kf=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ss(e)(t,n,r)};var Jf=(e)=>async(t,n,o)=>ss(e)(t,n,o);var Yf=/^[cC][^\s-]{8,}$/,Qf=/^[0-9a-z]+$/,eh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,th=/^[0-9a-vA-V]{20}$/,nh=/^[A-Za-z0-9]{27}$/,oh=/^[a-zA-Z0-9_-]{21}$/,rh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ih=/^([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})$/,Pu=(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 sh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var U0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ah(){return new RegExp(U0,"u")}var ch=/^(?:(?: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])$/,lh=/^(([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 uh=/^((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])$/,dh=/^(([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])$/,ph=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nu=/^[A-Za-z0-9_-]*$/;var mh=/^\+[1-9]\d{6,14}$/,fh="(?:(?:\\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])))",hh=new RegExp(`^${fh}$`);function gh(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 vh(e){return new RegExp(`^${gh(e)}$`)}function yh(e){let t=gh({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(`^${fh}T(?:${o})$`)}var bh=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var xh=/^-?\d+$/,zu=/^-?\d+(?:\.\d+)?$/,wh=/^(?:true|false)$/i,_h=/^null$/i;var Sh=/^undefined$/i;var kh=/^[^A-Z]*$/,Th=/^[^a-z]*$/;var Pt=B("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ch={number:"number",bigint:"bigint",object:"date"},Ru=B("$ZodCheckLessThan",(e,t)=>{Pt.init(e,t);let n=Ch[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})}}),Mu=B("$ZodCheckGreaterThan",(e,t)=>{Pt.init(e,t);let n=Ch[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})}}),Eh=B("$ZodCheckMultipleOf",(e,t)=>{Pt.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):Mf(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})}}),Ah=B("$ZodCheckNumberFormat",(e,t)=>{Pt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[r,s]=Ff[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=xh}),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 Ih=B("$ZodCheckMaxLength",(e,t)=>{var n;Pt.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Aa(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=Pa(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ph=B("$ZodCheckMinLength",(e,t)=>{var n;Pt.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Aa(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=Pa(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Nh=B("$ZodCheckLengthEquals",(e,t)=>{var n;Pt.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Aa(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=Pa(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})}}),as=B("$ZodCheckStringFormat",(e,t)=>{var n,o;if(Pt.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=()=>{})}),zh=B("$ZodCheckRegex",(e,t)=>{as.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})}}),Rh=B("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kh),as.init(e,t)}),Mh=B("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Th),as.init(e,t)}),$h=B("$ZodCheckIncludes",(e,t)=>{Pt.init(e,t);let n=Po(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})}}),Oh=B("$ZodCheckStartsWith",(e,t)=>{Pt.init(e,t);let n=new RegExp(`^${Po(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})}}),Lh=B("$ZodCheckEndsWith",(e,t)=>{Pt.init(e,t);let n=new RegExp(`.*${Po(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 Dh=B("$ZodCheckOverwrite",(e,t)=>{Pt.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class $u{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(`
22
+ `}}};Zo.tableCaption={filter:["caption"],replacement:()=>""};Zo.tableColgroup={filter:["colgroup","col"],replacement:()=>""};Zo.tableSection={filter:["thead","tbody","tfoot"],replacement:function(e){return e}};function LE(e){var t=e.parentNode;return t.nodeName==="THEAD"||t.firstChild===e&&(t.nodeName==="TABLE"||DE(t))&&ME.call(e.childNodes,function(n){return n.nodeName==="TH"})}function DE(e){var t=e.previousSibling;return e.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function Zx(e,t=null,n=null){if(n===null)n=RE.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=HE(r,t," ");return o+r+" |"}function Wx(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(Wx(n))return!0}return!1}var Qd=(e,t)=>{if(!e.childNodes)return!1;for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(t==="code"&&Yd&&Yd(o))return!0;if(t.includes(o.nodeName))return!0;if(Qd(o,t))return!0}return!1},qx=(e,t)=>{let n=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];if(t.preserveNestedTables)n.push("TABLE");return Qd(e,"code")||Qd(e,n)};function ep(e){let t=Dx.get(e);if(t!==void 0)return t;let n=FE(e);return Dx.set(e,n),n}function FE(e){if(!e)return!0;if(!e.rows)return!0;if(e.rows.length===1&&e.rows[0].childNodes.length<=1)return!0;if(Wx(e))return!0;return!1}function BE(e){let t=e.parentNode;while(t.nodeName!=="DIV")if(t=t.parentNode,!t)return null;return t}function Gx(e){let t=e.parentNode;while(t.nodeName!=="TABLE")if(t=t.parentNode,!t)return null;return t}function HE(e,t,n){let o=t.getAttribute("colspan")||1;for(let r=1;r<o;r++)e+=" | "+n.repeat(3);return e}function Vx(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 Xx(e){Yd=e.isCodeBlock,Hx=e.options,e.keep(function(n){if(n.nodeName==="TABLE"&&qx(n,e.options))return!0;return!1});for(var t in Zo)e.addRule(t,Zo[t])}function Kx(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 jE(e){e.use([Fx,Bx,Xx,Kx])}Jx.gfm=jE;Jx.highlightedCodeBlock=Fx;Jx.strikethrough=Bx;Jx.tables=Xx;Jx.taskListItems=Kx});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 wa,$e,mf,hu,Ao,lf,ff,hf,gf,gu,pu,mu,k0,ya={},ba=[],T0=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_a=Array.isArray;function ro(e,t){for(var n in t)e[n]=t[n];return e}function vu(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function C0(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?wa.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 va(e,a,o,r,null)}function va(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?++mf:r,__i:-1,__u:0};return r==null&&$e.vnode!=null&&$e.vnode(s),s}function _e(e){return e.children}function qr(e,t){this.props=e,this.context=t}function Gr(e,t){if(t==null)return e.__?Gr(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"?Gr(e):null}function E0(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,o=[],r=[],s=ro({},t);s.__v=t.__v+1,$e.vnode&&$e.vnode(s),yu(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,o,n==null?Gr(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,xf(o,s,r),t.__e=t.__=null,s.__e!=n&&vf(s)}}function vf(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}),vf(e)}function uf(e){(!e.__d&&(e.__d=!0)&&Ao.push(e)&&!xa.__r++||lf!=$e.debounceRendering)&&((lf=$e.debounceRendering)||ff)(xa)}function xa(){try{for(var e,t=1;Ao.length;)Ao.length>t&&Ao.sort(hf),e=Ao.shift(),t=Ao.length,E0(e)}finally{Ao.length=xa.__r=0}}function yf(e,t,n,o,r,s,a,c,l,u,p){var d,m,f,h,v,x,g,b=o&&o.__k||ba,I=t.length;for(l=A0(n,t,b,l,I),d=0;d<I;d++)(f=n.__k[d])!=null&&(m=f.__i!=-1&&b[f.__i]||ya,f.__i=d,x=yu(e,f,m,r,s,a,c,l,u,p),h=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&bu(m.ref,null,f),p.push(f.ref,f.__c||h,f)),v==null&&h!=null&&(v=h),(g=!!(4&f.__u))||m.__k===f.__k?l=bf(f,l,e,g):typeof f.type=="function"&&x!==void 0?l=x:h&&(l=h.nextSibling),f.__u&=-7);return n.__e=v,l}function A0(e,t,n,o,r){var s,a,c,l,u,p=n.length,d=p,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]=va(null,a,null,null,null):_a(a)?a=e.__k[s]=va(_e,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=e.__k[s]=va(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=I0(a,n,l,d))!=-1&&(d--,(c=n[u])&&(c.__u|=2)),c==null||c.__v==null?(u==-1&&(r>p?m--:r<p&&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(d)for(s=0;s<p;s++)(c=n[s])!=null&&(2&c.__u)==0&&(c.__e==o&&(o=Gr(c)),_f(c,c));return o}function bf(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=bf(r[s],t,n,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=Gr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function I0(e,t,n,o){var r,s,a,{key:c,type:l}=e,u=t[n],p=u!=null&&(2&u.__u)==0;if(u===null&&c==null||p&&c==u.key&&l==u.type)return n;if(o>(p?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 df(e,t,n){t[0]=="-"?e.setProperty(t,n==null?"":n):e[t]=n==null?"":typeof n!="number"||T0.test(t)?n:n+"px"}function ga(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||df(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||df(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(gf,"$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=gu,e.addEventListener(t,s?mu:pu,s)):e.removeEventListener(t,s?mu:pu,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 pf(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=gu++;else if(t.t<n.u)return;return n($e.event?$e.event(t):t)}}}function yu(e,t,n,o,r,s,a,c,l,u){var p,d,m,f,h,v,x,g,b,I,R,M,_,N,w,k=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),s=[c=t.__e=n.__e]),(p=$e.__b)&&p(t);e:if(typeof k=="function")try{if(g=t.props,b=k.prototype&&k.prototype.render,I=(p=k.contextType)&&o[p.__c],R=p?I?I.props.value:p.__:o,n.__c?x=(d=t.__c=n.__c).__=d.__E:(b?t.__c=d=new k(g,R):(t.__c=d=new qr(g,R),d.constructor=k,d.render=N0),I&&I.sub(d),d.state||(d.state={}),d.__n=o,m=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&k.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ro({},d.__s)),ro(d.__s,k.getDerivedStateFromProps(g,d.__s))),f=d.props,h=d.state,d.__v=t,m)b&&k.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&k.getDerivedStateFromProps==null&&g!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(g,R),t.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(g,d.__s,R)===!1){t.__v!=n.__v&&(d.props=g,d.state=d.__s,d.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(z){z&&(z.__=t)}),ba.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(g,d.__s,R),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,h,v)})}if(d.context=R,d.props=g,d.__P=e,d.__e=!1,M=$e.__r,_=0,b)d.state=d.__s,d.__d=!1,M&&M(t),p=d.render(d.props,d.state,d.context),ba.push.apply(d.__h,d._sb),d._sb=[];else do d.__d=!1,M&&M(t),p=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++_<25);d.state=d.__s,d.getChildContext!=null&&(o=ro(ro({},o),d.getChildContext())),b&&!m&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(f,h)),N=p!=null&&p.type===_e&&p.key==null?wf(p.props.children):p,c=yf(e,_a(N)?N:[N],t,n,o,r,s,a,c,l,u),d.base=t.__e,t.__u&=-161,d.__h.length&&a.push(d),x&&(d.__E=d.__=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(w=s.length;w--;)vu(s[w]);fu(t)}else t.__e=n.__e,t.__k=n.__k,z.then||fu(t);$e.__e(z,t,n)}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=P0(n.__e,t,n,o,r,s,a,l,u);return(p=$e.diffed)&&p(t),128&t.__u?void 0:c}function fu(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(fu))}function xf(e,t,n){for(var o=0;o<n.length;o++)bu(n[o],n[++o],n[++o]);$e.__c&&$e.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(s){s.call(r)})}catch(s){$e.__e(s,r.__v)}})}function wf(e){return typeof e!="object"||e==null||e.__b>0?e:_a(e)?e.map(wf):ro({},e)}function P0(e,t,n,o,r,s,a,c,l){var u,p,d,m,f,h,v,x=n.props||ya,{props:g,type:b}=t;if(b=="svg"?r="http://www.w3.org/2000/svg":b=="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==!!b&&(b?f.localName==b:f.nodeType==3)){e=f,s[u]=null;break}}if(e==null){if(b==null)return document.createTextNode(g);e=document.createElementNS(r,b,g.is&&g),c&&($e.__m&&$e.__m(t,s),c=!1),s=null}if(b==null)x===g||c&&e.data==g||(e.data=g);else{if(s=s&&wa.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"?d=f:u=="children"||(u in g)||u=="value"&&("defaultValue"in g)||u=="checked"&&("defaultChecked"in g)||ga(e,u,null,f,r);for(u in g)f=g[u],u=="children"?m=f:u=="dangerouslySetInnerHTML"?p=f:u=="value"?h=f:u=="checked"?v=f:c&&typeof f!="function"||x[u]===f||ga(e,u,f,x[u],r);if(p)c||d&&(p.__html==d.__html||p.__html==e.innerHTML)||(e.innerHTML=p.__html),t.__k=[];else if(d&&(e.innerHTML=""),yf(t.type=="template"?e.content:e,_a(m)?m:[m],t,n,o,b=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&Gr(n,0),c,l),s!=null)for(u=s.length;u--;)vu(s[u]);c||(u="value",b=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[u]||b=="progress"&&!h||b=="option"&&h!=x[u])&&ga(e,u,h,x[u],r),u="checked",v!=null&&v!=e[u]&&ga(e,u,v,x[u],r))}return e}function bu(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){$e.__e(r,n)}}function _f(e,t,n){var o,r;if($e.unmount&&$e.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||bu(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){$e.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(r=0;r<o.length;r++)o[r]&&_f(o[r],t,n||typeof e.type!="function");n||vu(e.__e),e.__c=e.__=e.__e=void 0}function N0(e,t,n){return this.constructor(e,n)}function Qi(e,t,n){var o,r,s,a;t==document&&(t=document.documentElement),$e.__&&$e.__(e,t),r=(o=typeof n=="function")?null:n&&n.__k||t.__k,s=[],a=[],yu(t,e=(!o&&n||t).__k=C0(_e,null,[e]),r||ya,ya,t.namespaceURI,!o&&n?[n]:r?null:t.firstChild?wa.call(t.childNodes):null,s,!o&&n?n:r?r.__e:t.firstChild,o,a),xf(s,e,a)}wa=ba.slice,$e={__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}},mf=0,hu=function(e){return e!=null&&e.constructor===void 0},qr.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ro({},this.state),typeof e=="function"&&(e=e(ro({},n),this.props)),e&&ro(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),uf(this))},qr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),uf(this))},qr.prototype.render=_e,Ao=[],ff=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,hf=function(e,t){return e.__v.__b-t.__v.__b},xa.__r=0,gf=/(PointerCapture)$|Capture$/i,gu=0,pu=pf(!1),mu=pf(!0),k0=0;var Vr,dt,xu,Sf,es=0,Nf=[],mt=$e,{__b:kf,__r:Tf,diffed:Cf,__c:Ef,unmount:Af,__:If}=mt;function ka(e,t){mt.__h&&mt.__h(dt,e,es||t),es=0;var n=dt.__H||(dt.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function A(e){return es=1,z0(zf,e)}function z0(e,t,n){var o=ka(Vr++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):zf(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=dt,!dt.__f)){var r=function(c,l,u){if(!o.__c.__H)return!0;var p=o.__c.__H.__.filter(function(m){return m.__c});if(p.every(function(m){return!m.__N}))return!s||s.call(this,c,l,u);var d=o.__c.props!==c;return p.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(d=!0)}}),s&&s.call(this,c,l,u)||d};dt.__f=!0;var s=dt.shouldComponentUpdate,a=dt.componentWillUpdate;dt.componentWillUpdate=function(c,l,u){if(this.__e){var p=s;s=void 0,r(c,l,u),s=p}a&&a.call(this,c,l,u)},dt.shouldComponentUpdate=r}return o.__N||o.__}function H(e,t){var n=ka(Vr++,3);!mt.__s&&_u(n.__H,t)&&(n.__=e,n.u=t,dt.__H.__h.push(n))}function _n(e,t){var n=ka(Vr++,4);!mt.__s&&_u(n.__H,t)&&(n.__=e,n.u=t,dt.__h.push(n))}function L(e){return es=5,Be(function(){return{current:e}},[])}function Be(e,t){var n=ka(Vr++,7);return _u(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function j(e,t){return es=8,Be(function(){return e},t)}function R0(){for(var e;e=Nf.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Sa),t.__h.some(wu),t.__h=[]}catch(n){t.__h=[],mt.__e(n,e.__v)}}}mt.__b=function(e){dt=null,kf&&kf(e)},mt.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),If&&If(e,t)},mt.__r=function(e){Tf&&Tf(e),Vr=0;var t=(dt=e.__c).__H;t&&(xu===dt?(t.__h=[],dt.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Sa),t.__h.some(wu),t.__h=[],Vr=0)),xu=dt},mt.diffed=function(e){Cf&&Cf(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Nf.push(t)!==1&&Sf===mt.requestAnimationFrame||((Sf=mt.requestAnimationFrame)||M0)(R0)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),xu=dt=null},mt.__c=function(e,t){t.some(function(n){try{n.__h.some(Sa),n.__h=n.__h.filter(function(o){return!o.__||wu(o)})}catch(o){t.some(function(r){r.__h&&(r.__h=[])}),t=[],mt.__e(o,n.__v)}}),Ef&&Ef(e,t)},mt.unmount=function(e){Af&&Af(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(o){try{Sa(o)}catch(r){t=r}}),n.__H=void 0,t&&mt.__e(t,n.__v))};var Pf=typeof requestAnimationFrame=="function";function M0(e){var t,n=function(){clearTimeout(o),Pf&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);Pf&&(t=requestAnimationFrame(n))}function Sa(e){var t=dt,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),dt=t}function wu(e){var t=dt;e.__c=e.__(),dt=t}function _u(e,t){return!e||e.length!==t.length||t.some(function(n,o){return n!==e[o]})}function zf(e,t){return typeof t=="function"?t(e):t}var wR=Object.freeze({status:"aborted"});function B(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,p=Object.keys(u);for(let d=0;d<p.length;d++){let m=p[d];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 p of u._zod.deferred)p();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 _R=Symbol("zod_brand");class io extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ts extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}var Ta={};function Sn(e){if(e)Object.assign(Ta,e);return Ta}function Ea(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 ku(e,t="|"){return e.map((n)=>Au(n)).join(t)}function ns(e,t){if(typeof t==="bigint")return t.toString();return t}function os(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Aa(e){return e===null||e===void 0}function Ia(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Mf(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 Rf=Symbol("evaluating");function De(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===Rf)return;if(o===void 0)o=Rf,o=n();return o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ur(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Io(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Tu(e){return JSON.stringify(e)}function $f(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Cu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Xr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Of=os(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function dr(e){if(Xr(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(Xr(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Eu(e){if(dr(e))return{...e};if(Array.isArray(e))return[...e];return e}var Lf=new Set(["string","number","symbol"]);function Po(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wn(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function ee(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 Au(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Df(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ff={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 $0(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=Io(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 ur(this,"shape",a),a},checks:[]});return Wn(e,s)}function O0(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=Io(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 ur(this,"shape",a),a},checks:[]});return Wn(e,s)}function L0(e,t){if(!dr(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=Io(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return ur(this,"shape",s),s}});return Wn(e,r)}function D0(e,t){if(!dr(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Io(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return ur(this,"shape",o),o}});return Wn(e,n)}function F0(e,t){let n=Io(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return ur(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return Wn(e,n)}function B0(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=Io(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 ur(this,"shape",l),l},checks:[]});return Wn(t,a)}function H0(e,t,n){let o=Io(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 ur(this,"shape",s),s}});return Wn(t,o)}function pr(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 No(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Ca(e){return typeof e==="string"?e:e?.message}function qn(e,t,n){let o={...e,path:e.path??[]};if(!e.message){let r=Ca(e.inst?._zod.def?.error?.(e))??Ca(t?.error?.(e))??Ca(n.customError?.(e))??Ca(n.localeError?.(e))??"Invalid input";o.message=r}if(delete o.inst,delete o.continue,!t?.reportInput)delete o.input;return o}function Pa(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Bf(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 mr(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}var Hf=(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,ns,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Na=B("$ZodError",Hf),Iu=B("$ZodError",Hf,{Parent:Error});function jf(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 Uf(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 za=(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 io;if(a.issues.length){let c=new(r?.Err??e)(a.issues.map((l)=>qn(l,s,Sn())));throw Cu(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)=>qn(l,s,Sn())));throw Cu(c,r?.callee),c}return a.value};var rs=(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 io;return s.issues.length?{success:!1,error:new(e??Na)(s.issues.map((a)=>qn(a,r,Sn())))}:{success:!0,data:s.value}},is=rs(Iu),ss=(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)=>qn(a,r,Sn())))}:{success:!0,data:s.value}},Ma=ss(Iu),Zf=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return za(e)(t,n,r)};var Wf=(e)=>(t,n,o)=>za(e)(t,n,o);var qf=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Ra(e)(t,n,r)};var Gf=(e)=>async(t,n,o)=>Ra(e)(t,n,o);var Vf=(e)=>(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return rs(e)(t,n,r)};var Xf=(e)=>(t,n,o)=>rs(e)(t,n,o);var Kf=(e)=>async(t,n,o)=>{let r=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return ss(e)(t,n,r)};var Jf=(e)=>async(t,n,o)=>ss(e)(t,n,o);var Yf=/^[cC][^\s-]{8,}$/,Qf=/^[0-9a-z]+$/,eh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,th=/^[0-9a-vA-V]{20}$/,nh=/^[A-Za-z0-9]{27}$/,oh=/^[a-zA-Z0-9_-]{21}$/,rh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ih=/^([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})$/,Pu=(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 sh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var U0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ah(){return new RegExp(U0,"u")}var ch=/^(?:(?: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])$/,lh=/^(([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 uh=/^((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])$/,dh=/^(([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])$/,ph=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nu=/^[A-Za-z0-9_-]*$/;var mh=/^\+[1-9]\d{6,14}$/,fh="(?:(?:\\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])))",hh=new RegExp(`^${fh}$`);function gh(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 vh(e){return new RegExp(`^${gh(e)}$`)}function yh(e){let t=gh({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(`^${fh}T(?:${o})$`)}var bh=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var xh=/^-?\d+$/,zu=/^-?\d+(?:\.\d+)?$/,wh=/^(?:true|false)$/i,_h=/^null$/i;var Sh=/^undefined$/i;var kh=/^[^A-Z]*$/,Th=/^[^a-z]*$/;var Pt=B("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ch={number:"number",bigint:"bigint",object:"date"},Ru=B("$ZodCheckLessThan",(e,t)=>{Pt.init(e,t);let n=Ch[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})}}),Mu=B("$ZodCheckGreaterThan",(e,t)=>{Pt.init(e,t);let n=Ch[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})}}),Eh=B("$ZodCheckMultipleOf",(e,t)=>{Pt.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):Mf(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})}}),Ah=B("$ZodCheckNumberFormat",(e,t)=>{Pt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[r,s]=Ff[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=xh}),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 Ih=B("$ZodCheckMaxLength",(e,t)=>{var n;Pt.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Aa(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=Pa(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ph=B("$ZodCheckMinLength",(e,t)=>{var n;Pt.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Aa(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=Pa(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Nh=B("$ZodCheckLengthEquals",(e,t)=>{var n;Pt.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let r=o.value;return!Aa(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=Pa(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})}}),as=B("$ZodCheckStringFormat",(e,t)=>{var n,o;if(Pt.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=()=>{})}),zh=B("$ZodCheckRegex",(e,t)=>{as.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})}}),Rh=B("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kh),as.init(e,t)}),Mh=B("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Th),as.init(e,t)}),$h=B("$ZodCheckIncludes",(e,t)=>{Pt.init(e,t);let n=Po(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})}}),Oh=B("$ZodCheckStartsWith",(e,t)=>{Pt.init(e,t);let n=new RegExp(`^${Po(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})}}),Lh=B("$ZodCheckEndsWith",(e,t)=>{Pt.init(e,t);let n=new RegExp(`.*${Po(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 Dh=B("$ZodCheckOverwrite",(e,t)=>{Pt.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class $u{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(`
23
23
  `).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(`
24
24
  `))}}var Bh={major:4,minor:3,patch:6};var Ke=B("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Bh;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=pr(a),p;for(let d of c){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,f=d._zod.check(a);if(f instanceof Promise&&l?.async===!1)throw new io;if(p||f instanceof Promise)p=(p??Promise.resolve()).then(async()=>{if(await f,a.issues.length===m)return;if(!u)u=pr(a,m)});else{if(a.issues.length===m)continue;if(!u)u=pr(a,m)}}if(p)return p.then(()=>a);return a},s=(a,c,l)=>{if(pr(a))return a.aborted=!0,a;let u=r(c,o,l);if(u instanceof Promise){if(l.async===!1)throw new io;return u.then((p)=>e._zod.parse(p,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((p)=>s(p,a,c));return s(u,a,c)}let l=e._zod.parse(a,c);if(l instanceof Promise){if(c.async===!1)throw new io;return l.then((u)=>r(u,o,c))}return r(l,o,c)}}De(e,"~standard",()=>({validate:(r)=>{try{let s=is(e,r);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Ma(e,r).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Da=B("$ZodString",(e,t)=>{Ke.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??bh(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}}),et=B("$ZodStringFormat",(e,t)=>{as.init(e,t),Da.init(e,t)}),Xh=B("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ih),et.init(e,t)}),Kh=B("$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=Pu(o))}else t.pattern??(t.pattern=Pu());et.init(e,t)}),Jh=B("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sh),et.init(e,t)}),Yh=B("$ZodURL",(e,t)=>{et.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})}}}),Qh=B("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ah()),et.init(e,t)}),eg=B("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=oh),et.init(e,t)}),tg=B("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Yf),et.init(e,t)}),ng=B("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Qf),et.init(e,t)}),og=B("$ZodULID",(e,t)=>{t.pattern??(t.pattern=eh),et.init(e,t)}),rg=B("$ZodXID",(e,t)=>{t.pattern??(t.pattern=th),et.init(e,t)}),ig=B("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=nh),et.init(e,t)}),sg=B("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=yh(t)),et.init(e,t)}),ag=B("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=hh),et.init(e,t)}),cg=B("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=vh(t)),et.init(e,t)}),lg=B("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=rh),et.init(e,t)}),ug=B("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ch),et.init(e,t),e._zod.bag.format="ipv4"}),dg=B("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=lh),et.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 pg=B("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=uh),et.init(e,t)}),mg=B("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=dh),et.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 fg(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var hg=B("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ph),et.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(fg(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function q0(e){if(!Nu.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return fg(n)}var gg=B("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Nu),et.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(q0(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),vg=B("$ZodE164",(e,t)=>{t.pattern??(t.pattern=mh),et.init(e,t)});function G0(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 yg=B("$ZodJWT",(e,t)=>{et.init(e,t),e._zod.check=(n)=>{if(G0(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Lu=B("$ZodNumber",(e,t)=>{Ke.init(e,t),e._zod.pattern=e._zod.bag.pattern??zu,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}}),bg=B("$ZodNumberFormat",(e,t)=>{Ah.init(e,t),Lu.init(e,t)}),xg=B("$ZodBoolean",(e,t)=>{Ke.init(e,t),e._zod.pattern=wh,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 wg=B("$ZodUndefined",(e,t)=>{Ke.init(e,t),e._zod.pattern=Sh,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}}),_g=B("$ZodNull",(e,t)=>{Ke.init(e,t),e._zod.pattern=_h,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 Sg=B("$ZodUnknown",(e,t)=>{Ke.init(e,t),e._zod.parse=(n)=>n}),kg=B("$ZodNever",(e,t)=>{Ke.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Hh(e,t,n){if(e.issues.length)t.issues.push(...No(n,e.issues));t.value[n]=e.value}var Tg=B("$ZodArray",(e,t)=>{Ke.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)=>Hh(u,n,a)));else Hh(l,n,a)}if(s.length)return Promise.all(s).then(()=>n);return n}});function La(e,t,n,o,r){if(e.issues.length){if(r&&!(n in o))return;t.issues.push(...No(n,e.issues))}if(e.value===void 0){if(n in o)t.value[n]=void 0}else t.value[n]=e.value}function Cg(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=Df(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Eg(e,t,n,o,r,s){let a=[],c=r.keySet,l=r.catchall._zod,u=l.def.type,p=l.optout==="optional";for(let d in t){if(c.has(d))continue;if(u==="never"){a.push(d);continue}let m=l.run({value:t[d],issues:[]},o);if(m instanceof Promise)e.push(m.then((f)=>La(f,n,d,t,p)));else La(m,n,d,t,p)}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 V0=B("$ZodObject",(e,t)=>{if(Ke.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=os(()=>Cg(t));De(e._zod,"propValues",()=>{let c=t.shape,l={};for(let u in c){let p=c[u]._zod;if(p.values){l[u]??(l[u]=new Set);for(let d of p.values)l[u].add(d)}}return l});let r=Xr,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 p=[],d=a.shape;for(let m of a.keys){let f=d[m],h=f._zod.optout==="optional",v=f._zod.run({value:u[m],issues:[]},l);if(v instanceof Promise)p.push(v.then((x)=>La(x,c,m,u,h)));else La(v,c,m,u,h)}if(!s)return p.length?Promise.all(p).then(()=>c):c;return Eg(p,u,c,l,o.value,e)}}),Ag=B("$ZodObjectJIT",(e,t)=>{V0.init(e,t);let n=e._zod.parse,o=os(()=>Cg(t)),r=(m)=>{let f=new $u(["shape","payload","ctx"]),h=o.value,v=(I)=>{let R=Tu(I);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};f.write("const input = payload.value;");let x=Object.create(null),g=0;for(let I of h.keys)x[I]=`key_${g++}`;f.write("const newResult = {};");for(let I of h.keys){let R=x[I],M=Tu(I),N=m[I]?._zod?.optout==="optional";if(f.write(`const ${R} = ${v(I)};`),N)f.write(`
25
25
  if (${R}.issues.length) {
@@ -55,9 +55,9 @@ ${l}${u}
55
55
  newResult[${M}] = ${R}.value;
56
56
  }
57
57
 
58
- `)}f.write("payload.value = newResult;"),f.write("return payload;");let b=f.compile();return(I,R)=>b(m,I,R)},s,a=Xr,c=!Ta.jitless,u=c&&Of.value,p=t.catchall,d;e._zod.parse=(m,f)=>{d??(d=o.value);let h=m.value;if(!a(h))return m.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),m;if(c&&u&&f?.async===!1&&f.jitless!==!0){if(!s)s=r(t.shape);if(m=s(m,f),!p)return m;return Eg([],h,m,f,d,e)}return n(m,f)}});function jh(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)=>!pr(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)=>qn(a,o,Sn())))}),t}var Du=B("$ZodUnion",(e,t)=>{Ke.init(e,t),De(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),De(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),De(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),De(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)=>Ia(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 jh(c,r,e,s);return Promise.all(c).then((l)=>jh(l,r,e,s))}});var Ig=B("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Du.init(e,t);let n=e._zod.parse;De(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=os(()=>{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(!Xr(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}}),Pg=B("$ZodIntersection",(e,t)=>{Ke.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])=>Uh(n,l,u));return Uh(n,s,a)}});function Ou(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(dr(e)&&dr(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=Ou(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=Ou(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 Uh(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(pr(e))return e;let a=Ou(t.value,n.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ng=B("$ZodRecord",(e,t)=>{Ke.init(e,t),e._zod.parse=(n,o)=>{let r=n.value;if(!dr(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 p=t.valueType._zod.run({value:r[u],issues:[]},o);if(p instanceof Promise)s.push(p.then((d)=>{if(d.issues.length)n.issues.push(...No(u,d.issues));n.value[u]=d.value}));else{if(p.issues.length)n.issues.push(...No(u,p.issues));n.value[u]=p.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"&&zu.test(c)&&l.issues.length){let d=t.keyType._zod.run({value:Number(c),issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)l=d}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((d)=>qn(d,o,Sn())),input:c,path:[c],inst:e});continue}let p=t.valueType._zod.run({value:r[c],issues:[]},o);if(p instanceof Promise)s.push(p.then((d)=>{if(d.issues.length)n.issues.push(...No(c,d.issues));n.value[l.value]=d.value}));else{if(p.issues.length)n.issues.push(...No(c,p.issues));n.value[l.value]=p.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var zg=B("$ZodEnum",(e,t)=>{Ke.init(e,t);let n=Ea(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Lf.has(typeof r)).map((r)=>typeof r==="string"?Po(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}}),Rg=B("$ZodLiteral",(e,t)=>{if(Ke.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"?Po(o):o?Po(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 Mg=B("$ZodTransform",(e,t)=>{Ke.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new ts(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 io;return n.value=r,n}});function Zh(e,t){if(e.issues.length&&t===void 0)return{issues:[],value:void 0};return e}var Fu=B("$ZodOptional",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),De(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ia(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)=>Zh(s,n.value));return Zh(r,n.value)}if(n.value===void 0)return n;return t.innerType._zod.run(n,o)}}),$g=B("$ZodExactOptional",(e,t)=>{Fu.init(e,t),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),Og=B("$ZodNullable",(e,t)=>{Ke.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ia(n.source)}|null)$`):void 0}),De(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)}}),Lg=B("$ZodDefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",De(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)=>Wh(s,t));return Wh(r,t)}});function Wh(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Dg=B("$ZodPrefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",De(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)}}),Fg=B("$ZodNonOptional",(e,t)=>{Ke.init(e,t),De(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)=>qh(s,e));return qh(r,e)}});function qh(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 Bg=B("$ZodCatch",(e,t)=>{Ke.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(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)=>qn(a,o,Sn()))},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)=>qn(s,o,Sn()))},input:n.value}),n.issues=[];return n}});var Hg=B("$ZodPipe",(e,t)=>{Ke.init(e,t),De(e._zod,"values",()=>t.in._zod.values),De(e._zod,"optin",()=>t.in._zod.optin),De(e._zod,"optout",()=>t.out._zod.optout),De(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)=>Oa(a,t.in,o));return Oa(s,t.in,o)}let r=t.in._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Oa(s,t.out,o));return Oa(r,t.out,o)}});function Oa(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var jg=B("$ZodReadonly",(e,t)=>{Ke.init(e,t),De(e._zod,"propValues",()=>t.innerType._zod.propValues),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"optin",()=>t.innerType?._zod?.optin),De(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(Gh);return Gh(r)}});function Gh(e){return e.value=Object.freeze(e.value),e}var Ug=B("$ZodCustom",(e,t)=>{Pt.init(e,t),Ke.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)=>Vh(s,n,o,e));Vh(r,n,o,e);return}});function Vh(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(mr(r))}}var X0=()=>{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=Bf(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 ${Au(r.values[0])}`;return`Invalid option: expected one of ${ku(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":""}: ${ku(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 Bu(){return{localeError:X0()}}var Zg,DR=Symbol("ZodOutput"),FR=Symbol("ZodInput");class Wg{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 K0(){return new Wg}(Zg=globalThis).__zod_globalRegistry??(Zg.__zod_globalRegistry=K0());var fr=globalThis.__zod_globalRegistry;function qg(e,t){return new e({type:"string",...ee(t)})}function Gg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ee(t)})}function Hu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ee(t)})}function Vg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(t)})}function Xg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(t)})}function Kg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(t)})}function Jg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(t)})}function Yg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ee(t)})}function Qg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(t)})}function ev(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(t)})}function tv(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(t)})}function nv(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(t)})}function ov(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(t)})}function rv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ee(t)})}function iv(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(t)})}function sv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(t)})}function av(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(t)})}function cv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(t)})}function lv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(t)})}function uv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ee(t)})}function dv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(t)})}function pv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ee(t)})}function mv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(t)})}function fv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(t)})}function hv(e,t){return new e({type:"string",format:"date",check:"string_format",...ee(t)})}function gv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ee(t)})}function vv(e,t){return new e({type:"string",format:"duration",check:"string_format",...ee(t)})}function yv(e,t){return new e({type:"number",checks:[],...ee(t)})}function bv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(t)})}function xv(e,t){return new e({type:"boolean",...ee(t)})}function wv(e,t){return new e({type:"undefined",...ee(t)})}function _v(e,t){return new e({type:"null",...ee(t)})}function Sv(e){return new e({type:"unknown"})}function kv(e,t){return new e({type:"never",...ee(t)})}function Fa(e,t){return new Ru({check:"less_than",...ee(t),value:e,inclusive:!1})}function cs(e,t){return new Ru({check:"less_than",...ee(t),value:e,inclusive:!0})}function Ba(e,t){return new Mu({check:"greater_than",...ee(t),value:e,inclusive:!1})}function ls(e,t){return new Mu({check:"greater_than",...ee(t),value:e,inclusive:!0})}function Ha(e,t){return new Eh({check:"multiple_of",...ee(t),value:e})}function ja(e,t){return new Ih({check:"max_length",...ee(t),maximum:e})}function Kr(e,t){return new Ph({check:"min_length",...ee(t),minimum:e})}function Ua(e,t){return new Nh({check:"length_equals",...ee(t),length:e})}function ju(e,t){return new zh({check:"string_format",format:"regex",...ee(t),pattern:e})}function Uu(e){return new Rh({check:"string_format",format:"lowercase",...ee(e)})}function Zu(e){return new Mh({check:"string_format",format:"uppercase",...ee(e)})}function Wu(e,t){return new $h({check:"string_format",format:"includes",...ee(t),includes:e})}function qu(e,t){return new Oh({check:"string_format",format:"starts_with",...ee(t),prefix:e})}function Gu(e,t){return new Lh({check:"string_format",format:"ends_with",...ee(t),suffix:e})}function zo(e){return new Dh({check:"overwrite",tx:e})}function Vu(e){return zo((t)=>t.normalize(e))}function Xu(){return zo((e)=>e.trim())}function Ku(){return zo((e)=>e.toLowerCase())}function Ju(){return zo((e)=>e.toUpperCase())}function Yu(){return zo((e)=>$f(e))}function Tv(e,t,n){return new e({type:"array",element:t,...ee(n)})}function Cv(e,t,n){let o=ee(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ev(e,t,n){return new e({type:"custom",check:"custom",fn:t,...ee(n)})}function Av(e){let t=J0((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(mr(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(mr(r))}},e(n.value,n)));return t}function J0(e,t){let n=new Pt({check:"custom",...ee(t)});return n._zod.check=e,n}function Qu(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??fr,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 ft(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 p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,p);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,p)}let d=e._zod.parent;if(d){if(!a.ref)a.ref=d;ft(d,t,p),t.seen.get(d).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 ed(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 d=e.external.registry.get(a[0])?.id,m=e.external.uri??((h)=>h);if(d)return{ref:m(d)};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}/`,p=a[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:u+p}},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 p=c.schema;for(let d in p)delete p[d];p.$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>
58
+ `)}f.write("payload.value = newResult;"),f.write("return payload;");let b=f.compile();return(I,R)=>b(m,I,R)},s,a=Xr,c=!Ta.jitless,u=c&&Of.value,p=t.catchall,d;e._zod.parse=(m,f)=>{d??(d=o.value);let h=m.value;if(!a(h))return m.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),m;if(c&&u&&f?.async===!1&&f.jitless!==!0){if(!s)s=r(t.shape);if(m=s(m,f),!p)return m;return Eg([],h,m,f,d,e)}return n(m,f)}});function jh(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)=>!pr(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)=>qn(a,o,Sn())))}),t}var Du=B("$ZodUnion",(e,t)=>{Ke.init(e,t),De(e._zod,"optin",()=>t.options.some((r)=>r._zod.optin==="optional")?"optional":void 0),De(e._zod,"optout",()=>t.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),De(e._zod,"values",()=>{if(t.options.every((r)=>r._zod.values))return new Set(t.options.flatMap((r)=>Array.from(r._zod.values)));return}),De(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)=>Ia(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 jh(c,r,e,s);return Promise.all(c).then((l)=>jh(l,r,e,s))}});var Ig=B("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Du.init(e,t);let n=e._zod.parse;De(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=os(()=>{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(!Xr(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}}),Pg=B("$ZodIntersection",(e,t)=>{Ke.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])=>Uh(n,l,u));return Uh(n,s,a)}});function Ou(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(dr(e)&&dr(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=Ou(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=Ou(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 Uh(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(pr(e))return e;let a=Ou(t.value,n.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ng=B("$ZodRecord",(e,t)=>{Ke.init(e,t),e._zod.parse=(n,o)=>{let r=n.value;if(!dr(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 p=t.valueType._zod.run({value:r[u],issues:[]},o);if(p instanceof Promise)s.push(p.then((d)=>{if(d.issues.length)n.issues.push(...No(u,d.issues));n.value[u]=d.value}));else{if(p.issues.length)n.issues.push(...No(u,p.issues));n.value[u]=p.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"&&zu.test(c)&&l.issues.length){let d=t.keyType._zod.run({value:Number(c),issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)l=d}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((d)=>qn(d,o,Sn())),input:c,path:[c],inst:e});continue}let p=t.valueType._zod.run({value:r[c],issues:[]},o);if(p instanceof Promise)s.push(p.then((d)=>{if(d.issues.length)n.issues.push(...No(c,d.issues));n.value[l.value]=d.value}));else{if(p.issues.length)n.issues.push(...No(c,p.issues));n.value[l.value]=p.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var zg=B("$ZodEnum",(e,t)=>{Ke.init(e,t);let n=Ea(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Lf.has(typeof r)).map((r)=>typeof r==="string"?Po(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}}),Rg=B("$ZodLiteral",(e,t)=>{if(Ke.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"?Po(o):o?Po(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 Mg=B("$ZodTransform",(e,t)=>{Ke.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new ts(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 io;return n.value=r,n}});function Zh(e,t){if(e.issues.length&&t===void 0)return{issues:[],value:void 0};return e}var Fu=B("$ZodOptional",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),De(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ia(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)=>Zh(s,n.value));return Zh(r,n.value)}if(n.value===void 0)return n;return t.innerType._zod.run(n,o)}}),$g=B("$ZodExactOptional",(e,t)=>{Fu.init(e,t),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),Og=B("$ZodNullable",(e,t)=>{Ke.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ia(n.source)}|null)$`):void 0}),De(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)}}),Lg=B("$ZodDefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",De(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)=>Wh(s,t));return Wh(r,t)}});function Wh(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Dg=B("$ZodPrefault",(e,t)=>{Ke.init(e,t),e._zod.optin="optional",De(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)}}),Fg=B("$ZodNonOptional",(e,t)=>{Ke.init(e,t),De(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)=>qh(s,e));return qh(r,e)}});function qh(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 Bg=B("$ZodCatch",(e,t)=>{Ke.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(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)=>qn(a,o,Sn()))},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)=>qn(s,o,Sn()))},input:n.value}),n.issues=[];return n}});var Hg=B("$ZodPipe",(e,t)=>{Ke.init(e,t),De(e._zod,"values",()=>t.in._zod.values),De(e._zod,"optin",()=>t.in._zod.optin),De(e._zod,"optout",()=>t.out._zod.optout),De(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)=>Oa(a,t.in,o));return Oa(s,t.in,o)}let r=t.in._zod.run(n,o);if(r instanceof Promise)return r.then((s)=>Oa(s,t.out,o));return Oa(r,t.out,o)}});function Oa(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var jg=B("$ZodReadonly",(e,t)=>{Ke.init(e,t),De(e._zod,"propValues",()=>t.innerType._zod.propValues),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"optin",()=>t.innerType?._zod?.optin),De(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(Gh);return Gh(r)}});function Gh(e){return e.value=Object.freeze(e.value),e}var Ug=B("$ZodCustom",(e,t)=>{Pt.init(e,t),Ke.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)=>Vh(s,n,o,e));Vh(r,n,o,e);return}});function Vh(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(mr(r))}}var X0=()=>{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=Bf(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 ${Au(r.values[0])}`;return`Invalid option: expected one of ${ku(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":""}: ${ku(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 Bu(){return{localeError:X0()}}var Zg,FR=Symbol("ZodOutput"),BR=Symbol("ZodInput");class Wg{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 K0(){return new Wg}(Zg=globalThis).__zod_globalRegistry??(Zg.__zod_globalRegistry=K0());var fr=globalThis.__zod_globalRegistry;function qg(e,t){return new e({type:"string",...ee(t)})}function Gg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ee(t)})}function Hu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ee(t)})}function Vg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(t)})}function Xg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(t)})}function Kg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(t)})}function Jg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(t)})}function Yg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ee(t)})}function Qg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(t)})}function ev(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(t)})}function tv(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(t)})}function nv(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(t)})}function ov(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(t)})}function rv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ee(t)})}function iv(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(t)})}function sv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(t)})}function av(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(t)})}function cv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(t)})}function lv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(t)})}function uv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ee(t)})}function dv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(t)})}function pv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ee(t)})}function mv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(t)})}function fv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(t)})}function hv(e,t){return new e({type:"string",format:"date",check:"string_format",...ee(t)})}function gv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ee(t)})}function vv(e,t){return new e({type:"string",format:"duration",check:"string_format",...ee(t)})}function yv(e,t){return new e({type:"number",checks:[],...ee(t)})}function bv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(t)})}function xv(e,t){return new e({type:"boolean",...ee(t)})}function wv(e,t){return new e({type:"undefined",...ee(t)})}function _v(e,t){return new e({type:"null",...ee(t)})}function Sv(e){return new e({type:"unknown"})}function kv(e,t){return new e({type:"never",...ee(t)})}function Fa(e,t){return new Ru({check:"less_than",...ee(t),value:e,inclusive:!1})}function cs(e,t){return new Ru({check:"less_than",...ee(t),value:e,inclusive:!0})}function Ba(e,t){return new Mu({check:"greater_than",...ee(t),value:e,inclusive:!1})}function ls(e,t){return new Mu({check:"greater_than",...ee(t),value:e,inclusive:!0})}function Ha(e,t){return new Eh({check:"multiple_of",...ee(t),value:e})}function ja(e,t){return new Ih({check:"max_length",...ee(t),maximum:e})}function Kr(e,t){return new Ph({check:"min_length",...ee(t),minimum:e})}function Ua(e,t){return new Nh({check:"length_equals",...ee(t),length:e})}function ju(e,t){return new zh({check:"string_format",format:"regex",...ee(t),pattern:e})}function Uu(e){return new Rh({check:"string_format",format:"lowercase",...ee(e)})}function Zu(e){return new Mh({check:"string_format",format:"uppercase",...ee(e)})}function Wu(e,t){return new $h({check:"string_format",format:"includes",...ee(t),includes:e})}function qu(e,t){return new Oh({check:"string_format",format:"starts_with",...ee(t),prefix:e})}function Gu(e,t){return new Lh({check:"string_format",format:"ends_with",...ee(t),suffix:e})}function zo(e){return new Dh({check:"overwrite",tx:e})}function Vu(e){return zo((t)=>t.normalize(e))}function Xu(){return zo((e)=>e.trim())}function Ku(){return zo((e)=>e.toLowerCase())}function Ju(){return zo((e)=>e.toUpperCase())}function Yu(){return zo((e)=>$f(e))}function Tv(e,t,n){return new e({type:"array",element:t,...ee(n)})}function Cv(e,t,n){let o=ee(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ev(e,t,n){return new e({type:"custom",check:"custom",fn:t,...ee(n)})}function Av(e){let t=J0((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(mr(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(mr(r))}},e(n.value,n)));return t}function J0(e,t){let n=new Pt({check:"custom",...ee(t)});return n._zod.check=e,n}function Qu(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??fr,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 ft(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 p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,p);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,p)}let d=e._zod.parent;if(d){if(!a.ref)a.ref=d;ft(d,t,p),t.seen.get(d).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 ed(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 d=e.external.registry.get(a[0])?.id,m=e.external.uri??((h)=>h);if(d)return{ref:m(d)};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}/`,p=a[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:u+p}},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 p=c.schema;for(let d in p)delete p[d];p.$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>
59
59
 
60
- 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 td(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},p=c.ref;if(c.ref=null,p){o(p);let m=e.seen.get(p),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===p)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(!(v in u))delete l[v]}if(f.$ref&&m.def)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(v in m.def&&JSON.stringify(l[v])===JSON.stringify(m.def[v]))delete l[v]}}let d=a._zod.parent;if(d&&d!==p){o(d);let m=e.seen.get(d);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:us(t,"input",e.processors),output:us(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 Iv=(e,t={})=>(n)=>{let o=Qu({...n,processors:t});return ft(e,o),ed(o,e),td(o,e)},us=(e,t,n={})=>(o)=>{let{libraryOptions:r,target:s}=o??{},a=Qu({...r??{},target:s,io:t,processors:n});return ft(e,a),ed(a,e),td(a,e)};var Y0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Pv=(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=Y0[c]??c,r.format==="")delete r.format;if(c==="time")delete r.format}if(u)r.contentEncoding=u;if(l&&l.size>0){let p=[...l];if(p.length===1)r.pattern=p[0].source;else if(p.length>1)r.allOf=[...p.map((d)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))]}},Nv=(e,t,n,o)=>{let r=n,{minimum:s,maximum:a,format:c,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:p}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))r.type="integer";else r.type="number";if(typeof p==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")r.minimum=p,r.exclusiveMinimum=!0;else r.exclusiveMinimum=p;if(typeof s==="number"){if(r.minimum=s,typeof p==="number"&&t.target!=="draft-04")if(p>=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},zv=(e,t,n,o)=>{n.type="boolean"};var Rv=(e,t,n,o)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Mv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")};var $v=(e,t,n,o)=>{n.not={}};var Ov=(e,t,n,o)=>{};var Lv=(e,t,n,o)=>{let r=e._zod.def,s=Ea(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},Dv=(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 Fv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var Bv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Hv=(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=ft(s.element,t,{...o,path:[...o.path,"items"]})},jv=(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]=ft(a[u],t,{...o,path:[...o.path,"properties",u]});let c=new Set(Object.keys(a)),l=new Set([...c].filter((u)=>{let p=s.shape[u]._zod;if(t.io==="input")return p.optin===void 0;else return p.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=ft(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Uv=(e,t,n,o)=>{let r=e._zod.def,s=r.inclusive===!1,a=r.options.map((c,l)=>ft(c,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)n.oneOf=a;else n.anyOf=a},Zv=(e,t,n,o)=>{let r=e._zod.def,s=ft(r.left,t,{...o,path:[...o.path,"allOf",0]}),a=ft(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 Wv=(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 p=ft(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let d of l)r.patternProperties[d.source]=p}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=ft(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});r.additionalProperties=ft(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values;if(u){let p=[...u].filter((d)=>typeof d==="string"||typeof d==="number");if(p.length>0)r.required=p}},qv=(e,t,n,o)=>{let r=e._zod.def,s=ft(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"}]},Gv=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType},Vv=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Xv=(e,t,n,o)=>{let r=e._zod.def;ft(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))},Kv=(e,t,n,o)=>{let r=e._zod.def;ft(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},Jv=(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;ft(s,t,o);let a=t.seen.get(e);a.ref=s},Yv=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var nd=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType};var sT=B("ZodISODateTime",(e,t)=>{sg.init(e,t),nt.init(e,t)});function od(e){return fv(sT,e)}var aT=B("ZodISODate",(e,t)=>{ag.init(e,t),nt.init(e,t)});function Qv(e){return hv(aT,e)}var cT=B("ZodISOTime",(e,t)=>{cg.init(e,t),nt.init(e,t)});function ey(e){return gv(cT,e)}var lT=B("ZodISODuration",(e,t)=>{lg.init(e,t),nt.init(e,t)});function ty(e){return vv(lT,e)}var ny=(e,t)=>{Na.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Uf(e,n)},flatten:{value:(n)=>jf(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ns,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ns,2)}},isEmpty:{get(){return e.issues.length===0}}})},hM=B("ZodError",ny),dn=B("ZodError",ny,{Parent:Error});var oy=za(dn),ry=Ra(dn),iy=rs(dn),sy=ss(dn),ay=Zf(dn),cy=Wf(dn),ly=qf(dn),uy=Gf(dn),dy=Vf(dn),py=Xf(dn),my=Kf(dn),fy=Jf(dn);var tt=B("ZodType",(e,t)=>(Ke.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:us(e,"input"),output:us(e,"output")}}),e.toJSONSchema=Iv(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Io(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)=>Wn(e,n,o),e.brand=()=>e,e.register=(n,o)=>(n.add(e,o),e),e.parse=(n,o)=>oy(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>iy(e,n,o),e.parseAsync=async(n,o)=>ry(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>sy(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>ay(e,n,o),e.decode=(n,o)=>cy(e,n,o),e.encodeAsync=async(n,o)=>ly(e,n,o),e.decodeAsync=async(n,o)=>uy(e,n,o),e.safeEncode=(n,o)=>dy(e,n,o),e.safeDecode=(n,o)=>py(e,n,o),e.safeEncodeAsync=async(n,o)=>my(e,n,o),e.safeDecodeAsync=async(n,o)=>fy(e,n,o),e.refine=(n,o)=>e.check(tC(n,o)),e.superRefine=(n)=>e.check(nC(n)),e.overwrite=(n)=>e.check(zo(n)),e.optional=()=>at(e),e.exactOptional=()=>UT(e),e.nullable=()=>vy(e),e.nullish=()=>at(vy(e)),e.nonoptional=(n)=>XT(e,n),e.array=()=>he(e),e.or=(n)=>Ae([e,n]),e.and=(n)=>Wa(e,n),e.transform=(n)=>sd(e,Sy(n)),e.default=(n)=>qT(e,n),e.prefault=(n)=>VT(e,n),e.catch=(n)=>JT(e,n),e.pipe=(n)=>sd(e,n),e.readonly=()=>eC(e),e.describe=(n)=>{let o=e.clone();return fr.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return fr.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return fr.get(e);let o=e.clone();return fr.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),yy=B("_ZodString",(e,t)=>{Da.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Pv(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(ju(...o)),e.includes=(...o)=>e.check(Wu(...o)),e.startsWith=(...o)=>e.check(qu(...o)),e.endsWith=(...o)=>e.check(Gu(...o)),e.min=(...o)=>e.check(Kr(...o)),e.max=(...o)=>e.check(ja(...o)),e.length=(...o)=>e.check(Ua(...o)),e.nonempty=(...o)=>e.check(Kr(1,...o)),e.lowercase=(o)=>e.check(Uu(o)),e.uppercase=(o)=>e.check(Zu(o)),e.trim=()=>e.check(Xu()),e.normalize=(...o)=>e.check(Vu(...o)),e.toLowerCase=()=>e.check(Ku()),e.toUpperCase=()=>e.check(Ju()),e.slugify=()=>e.check(Yu())}),pT=B("ZodString",(e,t)=>{Da.init(e,t),yy.init(e,t),e.email=(n)=>e.check(Gg(mT,n)),e.url=(n)=>e.check(Yg(fT,n)),e.jwt=(n)=>e.check(mv(IT,n)),e.emoji=(n)=>e.check(Qg(hT,n)),e.guid=(n)=>e.check(Hu(hy,n)),e.uuid=(n)=>e.check(Vg(Za,n)),e.uuidv4=(n)=>e.check(Xg(Za,n)),e.uuidv6=(n)=>e.check(Kg(Za,n)),e.uuidv7=(n)=>e.check(Jg(Za,n)),e.nanoid=(n)=>e.check(ev(gT,n)),e.guid=(n)=>e.check(Hu(hy,n)),e.cuid=(n)=>e.check(tv(vT,n)),e.cuid2=(n)=>e.check(nv(yT,n)),e.ulid=(n)=>e.check(ov(bT,n)),e.base64=(n)=>e.check(uv(CT,n)),e.base64url=(n)=>e.check(dv(ET,n)),e.xid=(n)=>e.check(rv(xT,n)),e.ksuid=(n)=>e.check(iv(wT,n)),e.ipv4=(n)=>e.check(sv(_T,n)),e.ipv6=(n)=>e.check(av(ST,n)),e.cidrv4=(n)=>e.check(cv(kT,n)),e.cidrv6=(n)=>e.check(lv(TT,n)),e.e164=(n)=>e.check(pv(AT,n)),e.datetime=(n)=>e.check(od(n)),e.date=(n)=>e.check(Qv(n)),e.time=(n)=>e.check(ey(n)),e.duration=(n)=>e.check(ty(n))});function P(e){return qg(pT,e)}var nt=B("ZodStringFormat",(e,t)=>{et.init(e,t),yy.init(e,t)}),mT=B("ZodEmail",(e,t)=>{Jh.init(e,t),nt.init(e,t)});var hy=B("ZodGUID",(e,t)=>{Xh.init(e,t),nt.init(e,t)});var Za=B("ZodUUID",(e,t)=>{Kh.init(e,t),nt.init(e,t)});var fT=B("ZodURL",(e,t)=>{Yh.init(e,t),nt.init(e,t)});var hT=B("ZodEmoji",(e,t)=>{Qh.init(e,t),nt.init(e,t)});var gT=B("ZodNanoID",(e,t)=>{eg.init(e,t),nt.init(e,t)});var vT=B("ZodCUID",(e,t)=>{tg.init(e,t),nt.init(e,t)});var yT=B("ZodCUID2",(e,t)=>{ng.init(e,t),nt.init(e,t)});var bT=B("ZodULID",(e,t)=>{og.init(e,t),nt.init(e,t)});var xT=B("ZodXID",(e,t)=>{rg.init(e,t),nt.init(e,t)});var wT=B("ZodKSUID",(e,t)=>{ig.init(e,t),nt.init(e,t)});var _T=B("ZodIPv4",(e,t)=>{ug.init(e,t),nt.init(e,t)});var ST=B("ZodIPv6",(e,t)=>{dg.init(e,t),nt.init(e,t)});var kT=B("ZodCIDRv4",(e,t)=>{pg.init(e,t),nt.init(e,t)});var TT=B("ZodCIDRv6",(e,t)=>{mg.init(e,t),nt.init(e,t)});var CT=B("ZodBase64",(e,t)=>{hg.init(e,t),nt.init(e,t)});var ET=B("ZodBase64URL",(e,t)=>{gg.init(e,t),nt.init(e,t)});var AT=B("ZodE164",(e,t)=>{vg.init(e,t),nt.init(e,t)});var IT=B("ZodJWT",(e,t)=>{yg.init(e,t),nt.init(e,t)});var by=B("ZodNumber",(e,t)=>{Lu.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Nv(e,o,r,s),e.gt=(o,r)=>e.check(Ba(o,r)),e.gte=(o,r)=>e.check(ls(o,r)),e.min=(o,r)=>e.check(ls(o,r)),e.lt=(o,r)=>e.check(Fa(o,r)),e.lte=(o,r)=>e.check(cs(o,r)),e.max=(o,r)=>e.check(cs(o,r)),e.int=(o)=>e.check(gy(o)),e.safe=(o)=>e.check(gy(o)),e.positive=(o)=>e.check(Ba(0,o)),e.nonnegative=(o)=>e.check(ls(0,o)),e.negative=(o)=>e.check(Fa(0,o)),e.nonpositive=(o)=>e.check(cs(0,o)),e.multipleOf=(o,r)=>e.check(Ha(o,r)),e.step=(o,r)=>e.check(Ha(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 ge(e){return yv(by,e)}var PT=B("ZodNumberFormat",(e,t)=>{bg.init(e,t),by.init(e,t)});function gy(e){return bv(PT,e)}var NT=B("ZodBoolean",(e,t)=>{xg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>zv(e,n,o,r)});function Xe(e){return xv(NT,e)}var zT=B("ZodUndefined",(e,t)=>{wg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Mv(e,n,o,r)});function ad(e){return wv(zT,e)}var RT=B("ZodNull",(e,t)=>{_g.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Rv(e,n,o,r)});function cd(e){return _v(RT,e)}var MT=B("ZodUnknown",(e,t)=>{Sg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ov(e,n,o,r)});function qe(){return Sv(MT)}var $T=B("ZodNever",(e,t)=>{kg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>$v(e,n,o,r)});function xy(e){return kv($T,e)}var OT=B("ZodArray",(e,t)=>{Tg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Hv(e,n,o,r),e.element=t.element,e.min=(n,o)=>e.check(Kr(n,o)),e.nonempty=(n)=>e.check(Kr(1,n)),e.max=(n,o)=>e.check(ja(n,o)),e.length=(n,o)=>e.check(Ua(n,o)),e.unwrap=()=>e.element});function he(e,t){return Tv(OT,e,t)}var ld=B("ZodObject",(e,t)=>{Ag.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>jv(e,n,o,r),De(e,"shape",()=>t.shape),e.keyof=()=>Jt(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:qe()}),e.loose=()=>e.clone({...e._zod.def,catchall:qe()}),e.strict=()=>e.clone({...e._zod.def,catchall:xy()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>L0(e,n),e.safeExtend=(n)=>D0(e,n),e.merge=(n)=>F0(e,n),e.pick=(n)=>$0(e,n),e.omit=(n)=>O0(e,n),e.partial=(...n)=>B0(ky,e,n[0]),e.required=(...n)=>H0(Ty,e,n[0])});function O(e,t){let n={type:"object",shape:e??{},...ee(t)};return new ld(n)}function wy(e,t){return new ld({type:"object",shape:e,catchall:xy(),...ee(t)})}function Kt(e,t){return new ld({type:"object",shape:e,catchall:qe(),...ee(t)})}var _y=B("ZodUnion",(e,t)=>{Du.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Uv(e,n,o,r),e.options=t.options});function Ae(e,t){return new _y({type:"union",options:e,...ee(t)})}var LT=B("ZodDiscriminatedUnion",(e,t)=>{_y.init(e,t),Ig.init(e,t)});function ud(e,t,n){return new LT({type:"union",options:t,discriminator:e,...ee(n)})}var DT=B("ZodIntersection",(e,t)=>{Pg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Zv(e,n,o,r)});function Wa(e,t){return new DT({type:"intersection",left:e,right:t})}var FT=B("ZodRecord",(e,t)=>{Ng.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Wv(e,n,o,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ze(e,t,n){return new FT({type:"record",keyType:e,valueType:t,...ee(n)})}var id=B("ZodEnum",(e,t)=>{zg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Lv(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 id({...t,checks:[],...ee(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 id({...t,checks:[],...ee(r),entries:s})}});function Jt(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new id({type:"enum",entries:n,...ee(t)})}var BT=B("ZodLiteral",(e,t)=>{Rg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Dv(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 C(e,t){return new BT({type:"literal",values:Array.isArray(e)?e:[e],...ee(t)})}var HT=B("ZodTransform",(e,t)=>{Mg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Bv(e,n,o,r),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new ts(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(mr(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(mr(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 Sy(e){return new HT({type:"transform",transform:e})}var ky=B("ZodOptional",(e,t)=>{Fu.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>nd(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function at(e){return new ky({type:"optional",innerType:e})}var jT=B("ZodExactOptional",(e,t)=>{$g.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>nd(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function UT(e){return new jT({type:"optional",innerType:e})}var ZT=B("ZodNullable",(e,t)=>{Og.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>qv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function vy(e){return new ZT({type:"nullable",innerType:e})}var WT=B("ZodDefault",(e,t)=>{Lg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Vv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function qT(e,t){return new WT({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Eu(t)}})}var GT=B("ZodPrefault",(e,t)=>{Dg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Xv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function VT(e,t){return new GT({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Eu(t)}})}var Ty=B("ZodNonOptional",(e,t)=>{Fg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Gv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function XT(e,t){return new Ty({type:"nonoptional",innerType:e,...ee(t)})}var KT=B("ZodCatch",(e,t)=>{Bg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Kv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function JT(e,t){return new KT({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var YT=B("ZodPipe",(e,t)=>{Hg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Jv(e,n,o,r),e.in=t.in,e.out=t.out});function sd(e,t){return new YT({type:"pipe",in:e,out:t})}var QT=B("ZodReadonly",(e,t)=>{jg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Yv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function eC(e){return new QT({type:"readonly",innerType:e})}var Cy=B("ZodCustom",(e,t)=>{Ug.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Fv(e,n,o,r)});function Ey(e,t){return Cv(Cy,e??(()=>!0),t)}function tC(e,t={}){return Ev(Cy,e,t)}function nC(e){return Av(e)}function dd(e,t){return sd(Sy(e),t)}Sn(Bu());var pd=O({x:ge(),y:ge(),scale:ge().positive()}),oC=O({target:Ae([wy({nodeId:P().min(1)}),wy({viewport:pd})]),duration:ge().nonnegative().max(3600).optional(),easing:Jt(["linear","ease-in-out","ease-out"]).optional(),padding:ge().nonnegative().optional(),pullback:ge().min(0).max(4).optional()}),P$=O({stops:he(oC).max(1000)});function Ay(e,t,n,o){if("viewport"in e.target)return e.target.viewport;let r=e.target.nodeId,s=t.find((l)=>l.id===r);if(!s)throw Error(`Tour target not found: ${r}`);let a=e.padding??40;if(a*2>=Math.min(n,o))throw Error("Tour padding exceeds viewport");let c=Math.min((n-a*2)/s.size.width,(o-a*2)/s.size.height);return{x:n/2-(s.position.x+s.size.width/2)*c,y:o/2-(s.position.y+s.size.height/2)*c,scale:c}}function Iy(e,t,n,o,r,s="ease-in-out",a=0){let c=Math.max(0,Math.min(1,n));if(c===0)return{...e};if(c===1)return{...t};let l=s==="linear"?c:s==="ease-out"?1-(1-c)**3:c*c*(3-2*c),u=Math.exp(Math.log(e.scale)*(1-l)+Math.log(t.scale)*l-a*Math.sin(Math.PI*l)),p=(o/2-e.x)/e.scale*(1-l)+(o/2-t.x)/t.scale*l,d=(r/2-e.y)/e.scale*(1-l)+(r/2-t.y)/t.scale*l;return{x:o/2-p*u,y:r/2-d*u,scale:u}}var md=null;function Py(e){md=e}function bt(){if(md?.isConnected){let e=md.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 Ro(){let e=bt();return{x:e.left+e.width/2,y:e.top+e.height/2}}function fd(){let e=16;try{let t=bt(),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 rC=Symbol.for("preact-signals");function Ka(){if(!(ao>1)){var e,t=!1;(function(){var r=Va;Va=void 0;while(r!==void 0){if(r.S.v===r.v)r.S.i=r.i;r=r.o}})();while(ps!==void 0){var n=ps;ps=void 0,Ga++;while(n!==void 0){var o=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Ry(n))try{n.c()}catch(r){if(!t)e=r,t=!0}n=o}}if(Ga=0,ao--,t)throw e}else ao--}function pn(e){if(ao>0)return e();hd=++iC,ao++;try{return e()}finally{Ka()}}var He=void 0;function gd(e){var t=He;He=void 0;try{return e()}finally{He=t}}var Ny,ps=void 0,ao=0,Ga=0,iC=0,hd=0,Va=void 0,Xa=0;function zy(e){if(He!==void 0){var t=e.n;if(t===void 0||t.t!==He){if(t={i:0,S:e,p:He.s,n:void 0,t:He,e:void 0,x:void 0,r:t},He.s!==void 0)He.s.n=t;if(He.s=t,e.n=t,32&He.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=He.s,t.n=void 0,He.s.n=t,He.s=t}return t}}}function xt(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}xt.prototype.brand=rC;xt.prototype.h=function(){return!0};xt.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 gd(function(){var o;(o=t.W)==null||o.call(t)})};xt.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)gd(function(){var r;(r=t.Z)==null||r.call(t)})}}};xt.prototype.subscribe=function(e){var t=this;return nn(function(){var n=t.value,o=He;He=void 0;try{e(n)}finally{He=o}},{name:"sub"})};xt.prototype.valueOf=function(){return this.value};xt.prototype.toString=function(){return this.value+""};xt.prototype.toJSON=function(){return this.value};xt.prototype.peek=function(){var e=He;He=void 0;try{return this.value}finally{He=e}};Object.defineProperty(xt.prototype,"value",{get:function(){var e=zy(this);if(e!==void 0)e.i=this.i;return this.v},set:function(e){if(e!==this.v){if(Ga>100)throw Error("Cycle detected");(function(n){if(ao!==0&&Ga===0){if(n.l!==hd)n.l=hd,Va={S:n,v:n.v,i:n.i,o:Va}}})(this),this.v=e,this.i++,Xa++,ao++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Ka()}}}});function K(e,t){return new xt(e,t)}function Ry(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 My(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 $y(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 hr(e,t){xt.call(this,void 0),this.x=e,this.s=void 0,this.g=Xa-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}hr.prototype=new xt;hr.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===Xa)return!0;if(this.g=Xa,this.f|=1,this.i>0&&!Ry(this))return this.f&=-2,!0;var e=He;try{My(this),He=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 He=e,$y(this),this.f&=-2,!0};hr.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)}xt.prototype.S.call(this,e)};hr.prototype.U=function(e){if(this.t!==void 0){if(xt.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)}}};hr.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(hr.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=zy(this);if(this.h(),e!==void 0)e.i=this.i;if(16&this.f)throw this.v;return this.v}});function Ge(e,t){return new hr(e,t)}function Oy(e){var t=e.m;if(e.m=void 0,typeof t=="function"){ao++;var n=He;He=void 0;try{t()}catch(o){throw e.f&=-2,e.f|=8,vd(e),o}finally{He=n,Ka()}}}function vd(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Oy(e)}function sC(e){if(He!==this)throw Error("Out-of-order effect");if($y(this),He=e,this.f&=-2,8&this.f)vd(this);Ka()}function Jr(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,Ny)Ny.push(this)}Jr.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()}};Jr.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,Oy(this),My(this),ao++;var e=He;return He=this,sC.bind(this,e)};Jr.prototype.N=function(){if(!(2&this.f))this.f|=2,this.u=ps,ps=this};Jr.prototype.d=function(){if(this.f|=8,!(1&this.f))vd(this)};Jr.prototype.dispose=function(){this.d()};function nn(e,t){var n=new Jr(e,t);try{n.c()}catch(r){throw n.d(),r}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Ly,yd,Ja,aC=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__;var Dy=[];nn(function(){Ly=this.N})();function Yr(e,t){$e[e]=t.bind(null,$e[e]||function(){})}function Ya(e){if(Ja){var t=Ja;Ja=void 0,t()}Ja=e&&e.S()}function Fy(e){var t=this,n=e.data,o=lC(n);o.value=n;var r=Be(function(){var c=t,l=t.__v;while(l=l.__)if(l.__c){l.__c.__$f|=4;break}var u=Ge(function(){var f=o.value.value;return f===0?0:f===!0?"":f||""}),p=Ge(function(){return!Array.isArray(u.value)&&!hu(u.value)}),d=nn(function(){if(this.N=By,p.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(){d(),m.call(this)},[p,u]},[]),s=r[0],a=r[1];return s.value?a.peek():a.value}Fy.displayName="ReactiveTextNode";Object.defineProperties(xt.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Fy},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}});Yr("__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 xt){if(!n)t.__np=n={};n[r]=s,o[r]=s.peek()}}}e(t)});Yr("__r",function(e,t){if(e(t),t.type!==_e){Ya();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 nn(function(){a=this},{name:s}),a.c=r,a}(function(){var r;if(aC)(r=n.y)==null||r.call(n);o.__$f|=1,o.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:"")}yd=o,Ya(n)}});Yr("__e",function(e,t,n,o){Ya(),yd=void 0,e(t,n,o)});Yr("diffed",function(e,t){Ya(),yd=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],p=o[l];if(u===void 0)u=cC(n,l,p),s[l]=u;else u.o(p,r)}for(var d in o)r[d]=o[d]}}e(t)});function cC(e,t,n,o){var r=t in e&&e.ownerSVGElement===void 0,s=K(n),a=n.peek();return{o:function(c,l){s.value=c,a=c.peek()},d:nn(function(){this.N=By;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})}}Yr("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)});Yr("__h",function(e,t,n,o){if(o<3||o===9)t.__$f|=2;e(t,n,o)});qr.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 lC(e,t){return Be(function(){return K(e,t)},[])}var uC=function(e){queueMicrotask(function(){queueMicrotask(e)})};function dC(){pn(function(){var e;while(e=Dy.shift())Ly.call(e)})}function By(){if(Dy.push(this)===1)($e.requestAnimationFrame||uC)(dC)}var Nt={markdown:"MD","mcp-app":"APP",webpage:"WEB","json-render":"UI",graph:"GRAPH",board:"BOARD",prompt:"ASK",response:"ANS",status:"STATUS",context:"CONTEXT",ledger:"LOG",trace:"TRACE",file:"FILE",diff:"DIFF",mermaid:"MERMAID",image:"IMG",html:"HTML",group:"GROUP"},ms=new Set(["markdown","mcp-app","webpage","json-render","graph","context","ledger","file","diff","mermaid","image","html"]);function Hy(e){return e.type==="mcp-app"&&e.data.mode==="ext-app"&&e.data.serverName==="Excalidraw"&&e.data.toolName==="create_view"}function jy(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 pC(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:"",p=u?n.get(u):void 0;if(!p||p.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 p=u.map((f)=>({position:f.position,size:f.size})),d=jy(p);if(!d)continue;let m=`group:${l.id}`;r.push({id:m,memberIds:u.map((f)=>f.id),origin:{x:d.x,y:d.y},size:{width:d.width,height:d.height},sortKey:{x:d.x,y:d.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 mC(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 fC(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 p of t.get(u)??[]){if(o.has(p))continue;o.add(p),a.push(p)}}let l=c.map((u)=>n.get(u)).filter((u)=>u!==void 0).sort((u,p)=>u.sortKey.y-p.sortKey.y||u.sortKey.x-p.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 hC(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 gC(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((b)=>b.id)),a=e.filter((b)=>(o.get(b.id)??0)===0&&(r.get(b.id)??0)>0).sort((b,I)=>b.sortKey.x-I.sortKey.x||b.sortKey.y-I.sortKey.y),c=a.length>0?a:[e.slice().sort((b,I)=>b.sortKey.x-I.sortKey.x||b.sortKey.y-I.sortKey.y)[0]],l=new Map,u=c.map((b)=>b.id);for(let b of c)l.set(b.id,0);while(u.length>0){let b=u.shift(),I=l.get(b)??0;for(let R of n.get(b)??[]){if(!s.has(R)||l.has(R))continue;l.set(R,I+1),u.push(R)}}let p=0;for(let b of e){if(l.has(b.id))continue;l.set(b.id,p),p+=1}let d=new Map;for(let b of e){let I=l.get(b.id)??0;if(!d.has(I))d.set(I,[]);d.get(I).push(b)}let m=Array.from(d.keys()).sort((b,I)=>b-I);for(let b of m)d.get(b).sort((I,R)=>I.sortKey.y-R.sortKey.y||I.sortKey.x-R.sortKey.x);let f=new Map,h=new Map,v=0;for(let b of m){let I=d.get(b),R=I.reduce((_,N,w)=>_+N.size.height+(w>0?72:0),0),M=Math.max(...I.map((_)=>_.size.width));f.set(b,R),h.set(b,M),v=Math.max(v,R)}let x=new Map,g=0;for(let b of m){let I=d.get(b),R=f.get(b)??0,M=h.get(b)??0,_=Math.max(0,(v-R)/2);for(let N of I)x.set(N.id,{x:g,y:_}),_+=N.size.height+72;g+=M+96}return{positions:x,size:{width:Math.max(0,g-96),height:v},sortKey:e[0].sortKey}}function vC(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 p=l;while(n.get(p)!==p){let d=n.get(p);n.set(p,u),p=d}return u},r=(l,u)=>{let p=o(l),d=o(u);if(p!==d)n.set(p,d)},s=160;for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++){let p=e[l],d=e[u];if(p.origin.x-160<d.origin.x+d.size.width+160&&p.origin.x+p.size.width+160>d.origin.x-160&&p.origin.y-160<d.origin.y+d.size.height+160&&p.origin.y+p.size.height+160>d.origin.y-160)r(p.id,d.id)}for(let[l,u]of t)for(let p of u)if(n.has(l)&&n.has(p))r(l,p);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,p)=>u.sortKey.y-p.sortKey.y||u.sortKey.x-p.sortKey.x);return c.sort((l,u)=>l[0].sortKey.y-u[0].sortKey.y||l[0].sortKey.x-u[0].sortKey.x)}function yC(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 bd(e,t,n){let{units:o,nodesById:r,nodeToUnit:s}=pC(e),a=new Map,c=new Map;if(o.length===0)return{nodePositions:a,groupBounds:c};let{outgoing:l,undirected:u,indegree:p,outdegree:d}=mC(o,s,t),m=vC(o,u),f=new Map,h=[];for(let v of m){let x=fC(v,u).map((_)=>n==="graph"?gC(_,l,u,p,d):hC(_)),g={x:Math.min(...v.map((_)=>_.origin.x)),y:Math.min(...v.map((_)=>_.origin.y))},b=yC(x,g),I=new Map(v.map((_)=>[_.id,_.size])),R=(_)=>{let{POSITIVE_INFINITY:N,POSITIVE_INFINITY:w,NEGATIVE_INFINITY:k,NEGATIVE_INFINITY:z}=Number;for(let[X,W]of _){let J=I.get(X);if(!J)continue;N=Math.min(N,W.x),w=Math.min(w,W.y),k=Math.max(k,W.x+J.width),z=Math.max(z,W.y+J.height)}return{x:N,y:w,width:k-N,height:z-w}},M=b;for(let _=0;_<=h.length;_++){let N=R(M),w=h.filter((X)=>N.x<X.x+X.width+220&&N.x+N.width+220>X.x&&N.y<X.y+X.height+180&&N.y+N.height+180>X.y);if(w.length===0)break;let k=Math.max(...w.map((X)=>X.y+X.height))+180-N.y;if(k<=0)break;let z=new Map;for(let[X,W]of M)z.set(X,{x:W.x,y:W.y+k});M=z}for(let[_,N]of M)f.set(_,N);h.push(R(M))}for(let v of o){let x=f.get(v.id);if(!x)continue;let g=x.x-v.origin.x,b=x.y-v.origin.y;if(v.groupId){let M=[];for(let N of v.memberIds){let w=r.get(N);if(!w)continue;let k={x:w.position.x+g,y:w.position.y+b};a.set(N,k),M.push({position:k,size:w.size})}let _=jy(M);if(_)c.set(v.groupId,_);continue}let I=v.memberIds[0],R=r.get(I);if(!R)continue;a.set(I,{x:R.position.x+g,y:R.position.y+b})}return{nodePositions:a,groupBounds:c}}var bC=700,xC=1600;function wC(e){return e.replace(/\r\n?/g,`
60
+ 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 td(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},p=c.ref;if(c.ref=null,p){o(p);let m=e.seen.get(p),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===p)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(!(v in u))delete l[v]}if(f.$ref&&m.def)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(v in m.def&&JSON.stringify(l[v])===JSON.stringify(m.def[v]))delete l[v]}}let d=a._zod.parent;if(d&&d!==p){o(d);let m=e.seen.get(d);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:us(t,"input",e.processors),output:us(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 Iv=(e,t={})=>(n)=>{let o=Qu({...n,processors:t});return ft(e,o),ed(o,e),td(o,e)},us=(e,t,n={})=>(o)=>{let{libraryOptions:r,target:s}=o??{},a=Qu({...r??{},target:s,io:t,processors:n});return ft(e,a),ed(a,e),td(a,e)};var Y0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Pv=(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=Y0[c]??c,r.format==="")delete r.format;if(c==="time")delete r.format}if(u)r.contentEncoding=u;if(l&&l.size>0){let p=[...l];if(p.length===1)r.pattern=p[0].source;else if(p.length>1)r.allOf=[...p.map((d)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))]}},Nv=(e,t,n,o)=>{let r=n,{minimum:s,maximum:a,format:c,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:p}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))r.type="integer";else r.type="number";if(typeof p==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")r.minimum=p,r.exclusiveMinimum=!0;else r.exclusiveMinimum=p;if(typeof s==="number"){if(r.minimum=s,typeof p==="number"&&t.target!=="draft-04")if(p>=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},zv=(e,t,n,o)=>{n.type="boolean"};var Rv=(e,t,n,o)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Mv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")};var $v=(e,t,n,o)=>{n.not={}};var Ov=(e,t,n,o)=>{};var Lv=(e,t,n,o)=>{let r=e._zod.def,s=Ea(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},Dv=(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 Fv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var Bv=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Hv=(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=ft(s.element,t,{...o,path:[...o.path,"items"]})},jv=(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]=ft(a[u],t,{...o,path:[...o.path,"properties",u]});let c=new Set(Object.keys(a)),l=new Set([...c].filter((u)=>{let p=s.shape[u]._zod;if(t.io==="input")return p.optin===void 0;else return p.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=ft(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Uv=(e,t,n,o)=>{let r=e._zod.def,s=r.inclusive===!1,a=r.options.map((c,l)=>ft(c,t,{...o,path:[...o.path,s?"oneOf":"anyOf",l]}));if(s)n.oneOf=a;else n.anyOf=a},Zv=(e,t,n,o)=>{let r=e._zod.def,s=ft(r.left,t,{...o,path:[...o.path,"allOf",0]}),a=ft(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 Wv=(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 p=ft(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(let d of l)r.patternProperties[d.source]=p}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=ft(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});r.additionalProperties=ft(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values;if(u){let p=[...u].filter((d)=>typeof d==="string"||typeof d==="number");if(p.length>0)r.required=p}},qv=(e,t,n,o)=>{let r=e._zod.def,s=ft(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"}]},Gv=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType},Vv=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Xv=(e,t,n,o)=>{let r=e._zod.def;ft(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))},Kv=(e,t,n,o)=>{let r=e._zod.def;ft(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},Jv=(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;ft(s,t,o);let a=t.seen.get(e);a.ref=s},Yv=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var nd=(e,t,n,o)=>{let r=e._zod.def;ft(r.innerType,t,o);let s=t.seen.get(e);s.ref=r.innerType};var sT=B("ZodISODateTime",(e,t)=>{sg.init(e,t),nt.init(e,t)});function od(e){return fv(sT,e)}var aT=B("ZodISODate",(e,t)=>{ag.init(e,t),nt.init(e,t)});function Qv(e){return hv(aT,e)}var cT=B("ZodISOTime",(e,t)=>{cg.init(e,t),nt.init(e,t)});function ey(e){return gv(cT,e)}var lT=B("ZodISODuration",(e,t)=>{lg.init(e,t),nt.init(e,t)});function ty(e){return vv(lT,e)}var ny=(e,t)=>{Na.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Uf(e,n)},flatten:{value:(n)=>jf(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ns,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ns,2)}},isEmpty:{get(){return e.issues.length===0}}})},gM=B("ZodError",ny),dn=B("ZodError",ny,{Parent:Error});var oy=za(dn),ry=Ra(dn),iy=rs(dn),sy=ss(dn),ay=Zf(dn),cy=Wf(dn),ly=qf(dn),uy=Gf(dn),dy=Vf(dn),py=Xf(dn),my=Kf(dn),fy=Jf(dn);var tt=B("ZodType",(e,t)=>(Ke.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:us(e,"input"),output:us(e,"output")}}),e.toJSONSchema=Iv(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Io(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)=>Wn(e,n,o),e.brand=()=>e,e.register=(n,o)=>(n.add(e,o),e),e.parse=(n,o)=>oy(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>iy(e,n,o),e.parseAsync=async(n,o)=>ry(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>sy(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>ay(e,n,o),e.decode=(n,o)=>cy(e,n,o),e.encodeAsync=async(n,o)=>ly(e,n,o),e.decodeAsync=async(n,o)=>uy(e,n,o),e.safeEncode=(n,o)=>dy(e,n,o),e.safeDecode=(n,o)=>py(e,n,o),e.safeEncodeAsync=async(n,o)=>my(e,n,o),e.safeDecodeAsync=async(n,o)=>fy(e,n,o),e.refine=(n,o)=>e.check(tC(n,o)),e.superRefine=(n)=>e.check(nC(n)),e.overwrite=(n)=>e.check(zo(n)),e.optional=()=>at(e),e.exactOptional=()=>UT(e),e.nullable=()=>vy(e),e.nullish=()=>at(vy(e)),e.nonoptional=(n)=>XT(e,n),e.array=()=>he(e),e.or=(n)=>Ae([e,n]),e.and=(n)=>Wa(e,n),e.transform=(n)=>sd(e,Sy(n)),e.default=(n)=>qT(e,n),e.prefault=(n)=>VT(e,n),e.catch=(n)=>JT(e,n),e.pipe=(n)=>sd(e,n),e.readonly=()=>eC(e),e.describe=(n)=>{let o=e.clone();return fr.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return fr.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return fr.get(e);let o=e.clone();return fr.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),yy=B("_ZodString",(e,t)=>{Da.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Pv(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(ju(...o)),e.includes=(...o)=>e.check(Wu(...o)),e.startsWith=(...o)=>e.check(qu(...o)),e.endsWith=(...o)=>e.check(Gu(...o)),e.min=(...o)=>e.check(Kr(...o)),e.max=(...o)=>e.check(ja(...o)),e.length=(...o)=>e.check(Ua(...o)),e.nonempty=(...o)=>e.check(Kr(1,...o)),e.lowercase=(o)=>e.check(Uu(o)),e.uppercase=(o)=>e.check(Zu(o)),e.trim=()=>e.check(Xu()),e.normalize=(...o)=>e.check(Vu(...o)),e.toLowerCase=()=>e.check(Ku()),e.toUpperCase=()=>e.check(Ju()),e.slugify=()=>e.check(Yu())}),pT=B("ZodString",(e,t)=>{Da.init(e,t),yy.init(e,t),e.email=(n)=>e.check(Gg(mT,n)),e.url=(n)=>e.check(Yg(fT,n)),e.jwt=(n)=>e.check(mv(IT,n)),e.emoji=(n)=>e.check(Qg(hT,n)),e.guid=(n)=>e.check(Hu(hy,n)),e.uuid=(n)=>e.check(Vg(Za,n)),e.uuidv4=(n)=>e.check(Xg(Za,n)),e.uuidv6=(n)=>e.check(Kg(Za,n)),e.uuidv7=(n)=>e.check(Jg(Za,n)),e.nanoid=(n)=>e.check(ev(gT,n)),e.guid=(n)=>e.check(Hu(hy,n)),e.cuid=(n)=>e.check(tv(vT,n)),e.cuid2=(n)=>e.check(nv(yT,n)),e.ulid=(n)=>e.check(ov(bT,n)),e.base64=(n)=>e.check(uv(CT,n)),e.base64url=(n)=>e.check(dv(ET,n)),e.xid=(n)=>e.check(rv(xT,n)),e.ksuid=(n)=>e.check(iv(wT,n)),e.ipv4=(n)=>e.check(sv(_T,n)),e.ipv6=(n)=>e.check(av(ST,n)),e.cidrv4=(n)=>e.check(cv(kT,n)),e.cidrv6=(n)=>e.check(lv(TT,n)),e.e164=(n)=>e.check(pv(AT,n)),e.datetime=(n)=>e.check(od(n)),e.date=(n)=>e.check(Qv(n)),e.time=(n)=>e.check(ey(n)),e.duration=(n)=>e.check(ty(n))});function P(e){return qg(pT,e)}var nt=B("ZodStringFormat",(e,t)=>{et.init(e,t),yy.init(e,t)}),mT=B("ZodEmail",(e,t)=>{Jh.init(e,t),nt.init(e,t)});var hy=B("ZodGUID",(e,t)=>{Xh.init(e,t),nt.init(e,t)});var Za=B("ZodUUID",(e,t)=>{Kh.init(e,t),nt.init(e,t)});var fT=B("ZodURL",(e,t)=>{Yh.init(e,t),nt.init(e,t)});var hT=B("ZodEmoji",(e,t)=>{Qh.init(e,t),nt.init(e,t)});var gT=B("ZodNanoID",(e,t)=>{eg.init(e,t),nt.init(e,t)});var vT=B("ZodCUID",(e,t)=>{tg.init(e,t),nt.init(e,t)});var yT=B("ZodCUID2",(e,t)=>{ng.init(e,t),nt.init(e,t)});var bT=B("ZodULID",(e,t)=>{og.init(e,t),nt.init(e,t)});var xT=B("ZodXID",(e,t)=>{rg.init(e,t),nt.init(e,t)});var wT=B("ZodKSUID",(e,t)=>{ig.init(e,t),nt.init(e,t)});var _T=B("ZodIPv4",(e,t)=>{ug.init(e,t),nt.init(e,t)});var ST=B("ZodIPv6",(e,t)=>{dg.init(e,t),nt.init(e,t)});var kT=B("ZodCIDRv4",(e,t)=>{pg.init(e,t),nt.init(e,t)});var TT=B("ZodCIDRv6",(e,t)=>{mg.init(e,t),nt.init(e,t)});var CT=B("ZodBase64",(e,t)=>{hg.init(e,t),nt.init(e,t)});var ET=B("ZodBase64URL",(e,t)=>{gg.init(e,t),nt.init(e,t)});var AT=B("ZodE164",(e,t)=>{vg.init(e,t),nt.init(e,t)});var IT=B("ZodJWT",(e,t)=>{yg.init(e,t),nt.init(e,t)});var by=B("ZodNumber",(e,t)=>{Lu.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Nv(e,o,r,s),e.gt=(o,r)=>e.check(Ba(o,r)),e.gte=(o,r)=>e.check(ls(o,r)),e.min=(o,r)=>e.check(ls(o,r)),e.lt=(o,r)=>e.check(Fa(o,r)),e.lte=(o,r)=>e.check(cs(o,r)),e.max=(o,r)=>e.check(cs(o,r)),e.int=(o)=>e.check(gy(o)),e.safe=(o)=>e.check(gy(o)),e.positive=(o)=>e.check(Ba(0,o)),e.nonnegative=(o)=>e.check(ls(0,o)),e.negative=(o)=>e.check(Fa(0,o)),e.nonpositive=(o)=>e.check(cs(0,o)),e.multipleOf=(o,r)=>e.check(Ha(o,r)),e.step=(o,r)=>e.check(Ha(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 ge(e){return yv(by,e)}var PT=B("ZodNumberFormat",(e,t)=>{bg.init(e,t),by.init(e,t)});function gy(e){return bv(PT,e)}var NT=B("ZodBoolean",(e,t)=>{xg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>zv(e,n,o,r)});function Xe(e){return xv(NT,e)}var zT=B("ZodUndefined",(e,t)=>{wg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Mv(e,n,o,r)});function ad(e){return wv(zT,e)}var RT=B("ZodNull",(e,t)=>{_g.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Rv(e,n,o,r)});function cd(e){return _v(RT,e)}var MT=B("ZodUnknown",(e,t)=>{Sg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ov(e,n,o,r)});function qe(){return Sv(MT)}var $T=B("ZodNever",(e,t)=>{kg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>$v(e,n,o,r)});function xy(e){return kv($T,e)}var OT=B("ZodArray",(e,t)=>{Tg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Hv(e,n,o,r),e.element=t.element,e.min=(n,o)=>e.check(Kr(n,o)),e.nonempty=(n)=>e.check(Kr(1,n)),e.max=(n,o)=>e.check(ja(n,o)),e.length=(n,o)=>e.check(Ua(n,o)),e.unwrap=()=>e.element});function he(e,t){return Tv(OT,e,t)}var ld=B("ZodObject",(e,t)=>{Ag.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>jv(e,n,o,r),De(e,"shape",()=>t.shape),e.keyof=()=>Jt(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:qe()}),e.loose=()=>e.clone({...e._zod.def,catchall:qe()}),e.strict=()=>e.clone({...e._zod.def,catchall:xy()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>L0(e,n),e.safeExtend=(n)=>D0(e,n),e.merge=(n)=>F0(e,n),e.pick=(n)=>$0(e,n),e.omit=(n)=>O0(e,n),e.partial=(...n)=>B0(ky,e,n[0]),e.required=(...n)=>H0(Ty,e,n[0])});function O(e,t){let n={type:"object",shape:e??{},...ee(t)};return new ld(n)}function wy(e,t){return new ld({type:"object",shape:e,catchall:xy(),...ee(t)})}function Kt(e,t){return new ld({type:"object",shape:e,catchall:qe(),...ee(t)})}var _y=B("ZodUnion",(e,t)=>{Du.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Uv(e,n,o,r),e.options=t.options});function Ae(e,t){return new _y({type:"union",options:e,...ee(t)})}var LT=B("ZodDiscriminatedUnion",(e,t)=>{_y.init(e,t),Ig.init(e,t)});function ud(e,t,n){return new LT({type:"union",options:t,discriminator:e,...ee(n)})}var DT=B("ZodIntersection",(e,t)=>{Pg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Zv(e,n,o,r)});function Wa(e,t){return new DT({type:"intersection",left:e,right:t})}var FT=B("ZodRecord",(e,t)=>{Ng.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Wv(e,n,o,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ze(e,t,n){return new FT({type:"record",keyType:e,valueType:t,...ee(n)})}var id=B("ZodEnum",(e,t)=>{zg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Lv(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 id({...t,checks:[],...ee(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 id({...t,checks:[],...ee(r),entries:s})}});function Jt(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new id({type:"enum",entries:n,...ee(t)})}var BT=B("ZodLiteral",(e,t)=>{Rg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Dv(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 C(e,t){return new BT({type:"literal",values:Array.isArray(e)?e:[e],...ee(t)})}var HT=B("ZodTransform",(e,t)=>{Mg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Bv(e,n,o,r),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new ts(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(mr(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(mr(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 Sy(e){return new HT({type:"transform",transform:e})}var ky=B("ZodOptional",(e,t)=>{Fu.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>nd(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function at(e){return new ky({type:"optional",innerType:e})}var jT=B("ZodExactOptional",(e,t)=>{$g.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>nd(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function UT(e){return new jT({type:"optional",innerType:e})}var ZT=B("ZodNullable",(e,t)=>{Og.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>qv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function vy(e){return new ZT({type:"nullable",innerType:e})}var WT=B("ZodDefault",(e,t)=>{Lg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Vv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function qT(e,t){return new WT({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Eu(t)}})}var GT=B("ZodPrefault",(e,t)=>{Dg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Xv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function VT(e,t){return new GT({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Eu(t)}})}var Ty=B("ZodNonOptional",(e,t)=>{Fg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Gv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function XT(e,t){return new Ty({type:"nonoptional",innerType:e,...ee(t)})}var KT=B("ZodCatch",(e,t)=>{Bg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Kv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function JT(e,t){return new KT({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var YT=B("ZodPipe",(e,t)=>{Hg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Jv(e,n,o,r),e.in=t.in,e.out=t.out});function sd(e,t){return new YT({type:"pipe",in:e,out:t})}var QT=B("ZodReadonly",(e,t)=>{jg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Yv(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function eC(e){return new QT({type:"readonly",innerType:e})}var Cy=B("ZodCustom",(e,t)=>{Ug.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Fv(e,n,o,r)});function Ey(e,t){return Cv(Cy,e??(()=>!0),t)}function tC(e,t={}){return Ev(Cy,e,t)}function nC(e){return Av(e)}function dd(e,t){return sd(Sy(e),t)}Sn(Bu());var pd=O({x:ge(),y:ge(),scale:ge().positive()}),oC=O({target:Ae([wy({nodeId:P().min(1)}),wy({viewport:pd})]),duration:ge().nonnegative().max(3600).optional(),easing:Jt(["linear","ease-in-out","ease-out"]).optional(),padding:ge().nonnegative().optional(),pullback:ge().min(0).max(4).optional()}),N$=O({stops:he(oC).max(1000)});function Ay(e,t,n,o){if("viewport"in e.target)return e.target.viewport;let r=e.target.nodeId,s=t.find((l)=>l.id===r);if(!s)throw Error(`Tour target not found: ${r}`);let a=e.padding??40;if(a*2>=Math.min(n,o))throw Error("Tour padding exceeds viewport");let c=Math.min((n-a*2)/s.size.width,(o-a*2)/s.size.height);return{x:n/2-(s.position.x+s.size.width/2)*c,y:o/2-(s.position.y+s.size.height/2)*c,scale:c}}function Iy(e,t,n,o,r,s="ease-in-out",a=0){let c=Math.max(0,Math.min(1,n));if(c===0)return{...e};if(c===1)return{...t};let l=s==="linear"?c:s==="ease-out"?1-(1-c)**3:c*c*(3-2*c),u=Math.exp(Math.log(e.scale)*(1-l)+Math.log(t.scale)*l-a*Math.sin(Math.PI*l)),p=(o/2-e.x)/e.scale*(1-l)+(o/2-t.x)/t.scale*l,d=(r/2-e.y)/e.scale*(1-l)+(r/2-t.y)/t.scale*l;return{x:o/2-p*u,y:r/2-d*u,scale:u}}var md=null;function Py(e){md=e}function bt(){if(md?.isConnected){let e=md.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 Ro(){let e=bt();return{x:e.left+e.width/2,y:e.top+e.height/2}}function fd(){let e=16;try{let t=bt(),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 rC=Symbol.for("preact-signals");function Ka(){if(!(ao>1)){var e,t=!1;(function(){var r=Va;Va=void 0;while(r!==void 0){if(r.S.v===r.v)r.S.i=r.i;r=r.o}})();while(ps!==void 0){var n=ps;ps=void 0,Ga++;while(n!==void 0){var o=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Ry(n))try{n.c()}catch(r){if(!t)e=r,t=!0}n=o}}if(Ga=0,ao--,t)throw e}else ao--}function pn(e){if(ao>0)return e();hd=++iC,ao++;try{return e()}finally{Ka()}}var He=void 0;function gd(e){var t=He;He=void 0;try{return e()}finally{He=t}}var Ny,ps=void 0,ao=0,Ga=0,iC=0,hd=0,Va=void 0,Xa=0;function zy(e){if(He!==void 0){var t=e.n;if(t===void 0||t.t!==He){if(t={i:0,S:e,p:He.s,n:void 0,t:He,e:void 0,x:void 0,r:t},He.s!==void 0)He.s.n=t;if(He.s=t,e.n=t,32&He.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=He.s,t.n=void 0,He.s.n=t,He.s=t}return t}}}function xt(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}xt.prototype.brand=rC;xt.prototype.h=function(){return!0};xt.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 gd(function(){var o;(o=t.W)==null||o.call(t)})};xt.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)gd(function(){var r;(r=t.Z)==null||r.call(t)})}}};xt.prototype.subscribe=function(e){var t=this;return nn(function(){var n=t.value,o=He;He=void 0;try{e(n)}finally{He=o}},{name:"sub"})};xt.prototype.valueOf=function(){return this.value};xt.prototype.toString=function(){return this.value+""};xt.prototype.toJSON=function(){return this.value};xt.prototype.peek=function(){var e=He;He=void 0;try{return this.value}finally{He=e}};Object.defineProperty(xt.prototype,"value",{get:function(){var e=zy(this);if(e!==void 0)e.i=this.i;return this.v},set:function(e){if(e!==this.v){if(Ga>100)throw Error("Cycle detected");(function(n){if(ao!==0&&Ga===0){if(n.l!==hd)n.l=hd,Va={S:n,v:n.v,i:n.i,o:Va}}})(this),this.v=e,this.i++,Xa++,ao++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Ka()}}}});function K(e,t){return new xt(e,t)}function Ry(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 My(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 $y(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 hr(e,t){xt.call(this,void 0),this.x=e,this.s=void 0,this.g=Xa-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}hr.prototype=new xt;hr.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===Xa)return!0;if(this.g=Xa,this.f|=1,this.i>0&&!Ry(this))return this.f&=-2,!0;var e=He;try{My(this),He=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 He=e,$y(this),this.f&=-2,!0};hr.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)}xt.prototype.S.call(this,e)};hr.prototype.U=function(e){if(this.t!==void 0){if(xt.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)}}};hr.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(hr.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=zy(this);if(this.h(),e!==void 0)e.i=this.i;if(16&this.f)throw this.v;return this.v}});function Ge(e,t){return new hr(e,t)}function Oy(e){var t=e.m;if(e.m=void 0,typeof t=="function"){ao++;var n=He;He=void 0;try{t()}catch(o){throw e.f&=-2,e.f|=8,vd(e),o}finally{He=n,Ka()}}}function vd(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Oy(e)}function sC(e){if(He!==this)throw Error("Out-of-order effect");if($y(this),He=e,this.f&=-2,8&this.f)vd(this);Ka()}function Jr(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,Ny)Ny.push(this)}Jr.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()}};Jr.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,Oy(this),My(this),ao++;var e=He;return He=this,sC.bind(this,e)};Jr.prototype.N=function(){if(!(2&this.f))this.f|=2,this.u=ps,ps=this};Jr.prototype.d=function(){if(this.f|=8,!(1&this.f))vd(this)};Jr.prototype.dispose=function(){this.d()};function nn(e,t){var n=new Jr(e,t);try{n.c()}catch(r){throw n.d(),r}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Ly,yd,Ja,aC=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__;var Dy=[];nn(function(){Ly=this.N})();function Yr(e,t){$e[e]=t.bind(null,$e[e]||function(){})}function Ya(e){if(Ja){var t=Ja;Ja=void 0,t()}Ja=e&&e.S()}function Fy(e){var t=this,n=e.data,o=lC(n);o.value=n;var r=Be(function(){var c=t,l=t.__v;while(l=l.__)if(l.__c){l.__c.__$f|=4;break}var u=Ge(function(){var f=o.value.value;return f===0?0:f===!0?"":f||""}),p=Ge(function(){return!Array.isArray(u.value)&&!hu(u.value)}),d=nn(function(){if(this.N=By,p.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(){d(),m.call(this)},[p,u]},[]),s=r[0],a=r[1];return s.value?a.peek():a.value}Fy.displayName="ReactiveTextNode";Object.defineProperties(xt.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Fy},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}});Yr("__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 xt){if(!n)t.__np=n={};n[r]=s,o[r]=s.peek()}}}e(t)});Yr("__r",function(e,t){if(e(t),t.type!==_e){Ya();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 nn(function(){a=this},{name:s}),a.c=r,a}(function(){var r;if(aC)(r=n.y)==null||r.call(n);o.__$f|=1,o.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:"")}yd=o,Ya(n)}});Yr("__e",function(e,t,n,o){Ya(),yd=void 0,e(t,n,o)});Yr("diffed",function(e,t){Ya(),yd=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],p=o[l];if(u===void 0)u=cC(n,l,p),s[l]=u;else u.o(p,r)}for(var d in o)r[d]=o[d]}}e(t)});function cC(e,t,n,o){var r=t in e&&e.ownerSVGElement===void 0,s=K(n),a=n.peek();return{o:function(c,l){s.value=c,a=c.peek()},d:nn(function(){this.N=By;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})}}Yr("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)});Yr("__h",function(e,t,n,o){if(o<3||o===9)t.__$f|=2;e(t,n,o)});qr.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 lC(e,t){return Be(function(){return K(e,t)},[])}var uC=function(e){queueMicrotask(function(){queueMicrotask(e)})};function dC(){pn(function(){var e;while(e=Dy.shift())Ly.call(e)})}function By(){if(Dy.push(this)===1)($e.requestAnimationFrame||uC)(dC)}var Nt={markdown:"MD","mcp-app":"APP",webpage:"WEB","json-render":"UI",graph:"GRAPH",board:"BOARD",prompt:"ASK",response:"ANS",status:"STATUS",context:"CONTEXT",ledger:"LOG",trace:"TRACE",file:"FILE",diff:"DIFF",mermaid:"MERMAID",image:"IMG",html:"HTML",group:"GROUP"},ms=new Set(["markdown","mcp-app","webpage","json-render","graph","context","ledger","file","diff","mermaid","image","html"]);function Hy(e){return e.type==="mcp-app"&&e.data.mode==="ext-app"&&e.data.serverName==="Excalidraw"&&e.data.toolName==="create_view"}function jy(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 pC(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:"",p=u?n.get(u):void 0;if(!p||p.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 p=u.map((f)=>({position:f.position,size:f.size})),d=jy(p);if(!d)continue;let m=`group:${l.id}`;r.push({id:m,memberIds:u.map((f)=>f.id),origin:{x:d.x,y:d.y},size:{width:d.width,height:d.height},sortKey:{x:d.x,y:d.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 mC(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 fC(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 p of t.get(u)??[]){if(o.has(p))continue;o.add(p),a.push(p)}}let l=c.map((u)=>n.get(u)).filter((u)=>u!==void 0).sort((u,p)=>u.sortKey.y-p.sortKey.y||u.sortKey.x-p.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 hC(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 gC(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((b)=>b.id)),a=e.filter((b)=>(o.get(b.id)??0)===0&&(r.get(b.id)??0)>0).sort((b,I)=>b.sortKey.x-I.sortKey.x||b.sortKey.y-I.sortKey.y),c=a.length>0?a:[e.slice().sort((b,I)=>b.sortKey.x-I.sortKey.x||b.sortKey.y-I.sortKey.y)[0]],l=new Map,u=c.map((b)=>b.id);for(let b of c)l.set(b.id,0);while(u.length>0){let b=u.shift(),I=l.get(b)??0;for(let R of n.get(b)??[]){if(!s.has(R)||l.has(R))continue;l.set(R,I+1),u.push(R)}}let p=0;for(let b of e){if(l.has(b.id))continue;l.set(b.id,p),p+=1}let d=new Map;for(let b of e){let I=l.get(b.id)??0;if(!d.has(I))d.set(I,[]);d.get(I).push(b)}let m=Array.from(d.keys()).sort((b,I)=>b-I);for(let b of m)d.get(b).sort((I,R)=>I.sortKey.y-R.sortKey.y||I.sortKey.x-R.sortKey.x);let f=new Map,h=new Map,v=0;for(let b of m){let I=d.get(b),R=I.reduce((_,N,w)=>_+N.size.height+(w>0?72:0),0),M=Math.max(...I.map((_)=>_.size.width));f.set(b,R),h.set(b,M),v=Math.max(v,R)}let x=new Map,g=0;for(let b of m){let I=d.get(b),R=f.get(b)??0,M=h.get(b)??0,_=Math.max(0,(v-R)/2);for(let N of I)x.set(N.id,{x:g,y:_}),_+=N.size.height+72;g+=M+96}return{positions:x,size:{width:Math.max(0,g-96),height:v},sortKey:e[0].sortKey}}function vC(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 p=l;while(n.get(p)!==p){let d=n.get(p);n.set(p,u),p=d}return u},r=(l,u)=>{let p=o(l),d=o(u);if(p!==d)n.set(p,d)},s=160;for(let l=0;l<e.length;l++)for(let u=l+1;u<e.length;u++){let p=e[l],d=e[u];if(p.origin.x-160<d.origin.x+d.size.width+160&&p.origin.x+p.size.width+160>d.origin.x-160&&p.origin.y-160<d.origin.y+d.size.height+160&&p.origin.y+p.size.height+160>d.origin.y-160)r(p.id,d.id)}for(let[l,u]of t)for(let p of u)if(n.has(l)&&n.has(p))r(l,p);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,p)=>u.sortKey.y-p.sortKey.y||u.sortKey.x-p.sortKey.x);return c.sort((l,u)=>l[0].sortKey.y-u[0].sortKey.y||l[0].sortKey.x-u[0].sortKey.x)}function yC(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 bd(e,t,n){let{units:o,nodesById:r,nodeToUnit:s}=pC(e),a=new Map,c=new Map;if(o.length===0)return{nodePositions:a,groupBounds:c};let{outgoing:l,undirected:u,indegree:p,outdegree:d}=mC(o,s,t),m=vC(o,u),f=new Map,h=[];for(let v of m){let x=fC(v,u).map((_)=>n==="graph"?gC(_,l,u,p,d):hC(_)),g={x:Math.min(...v.map((_)=>_.origin.x)),y:Math.min(...v.map((_)=>_.origin.y))},b=yC(x,g),I=new Map(v.map((_)=>[_.id,_.size])),R=(_)=>{let{POSITIVE_INFINITY:N,POSITIVE_INFINITY:w,NEGATIVE_INFINITY:k,NEGATIVE_INFINITY:z}=Number;for(let[X,W]of _){let J=I.get(X);if(!J)continue;N=Math.min(N,W.x),w=Math.min(w,W.y),k=Math.max(k,W.x+J.width),z=Math.max(z,W.y+J.height)}return{x:N,y:w,width:k-N,height:z-w}},M=b;for(let _=0;_<=h.length;_++){let N=R(M),w=h.filter((X)=>N.x<X.x+X.width+220&&N.x+N.width+220>X.x&&N.y<X.y+X.height+180&&N.y+N.height+180>X.y);if(w.length===0)break;let k=Math.max(...w.map((X)=>X.y+X.height))+180-N.y;if(k<=0)break;let z=new Map;for(let[X,W]of M)z.set(X,{x:W.x,y:W.y+k});M=z}for(let[_,N]of M)f.set(_,N);h.push(R(M))}for(let v of o){let x=f.get(v.id);if(!x)continue;let g=x.x-v.origin.x,b=x.y-v.origin.y;if(v.groupId){let M=[];for(let N of v.memberIds){let w=r.get(N);if(!w)continue;let k={x:w.position.x+g,y:w.position.y+b};a.set(N,k),M.push({position:k,size:w.size})}let _=jy(M);if(_)c.set(v.groupId,_);continue}let I=v.memberIds[0],R=r.get(I);if(!R)continue;a.set(I,{x:R.position.x+g,y:R.position.y+b})}return{nodePositions:a,groupBounds:c}}var bC=700,xC=1600;function wC(e){return e.replace(/\r\n?/g,`
61
61
  `).replace(/[ \t\f\v]+/g," ").replace(/\n\s+/g,`
62
62
  `).replace(/\s+\n/g,`
63
63
  `).replace(/\n{3,}/g,`
@@ -164,7 +164,7 @@ ${r}
164
164
 
165
165
  `.substring(0,r);return n+s+o}function gA(e){return e!=null&&(typeof e==="string"||e.nodeType&&(e.nodeType===1||e.nodeType===9||e.nodeType===11))}function Wc(){let e=window.getSelection(),t=e&&e.rangeCount>0?e.getRangeAt(0).cloneRange():null;hn("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 pw(){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 qc=8,vA=[{kind:"exec",command:"bold",icon:"B",title:`Bold (${rt("B")})`},{kind:"exec",command:"italic",icon:"I",title:`Italic (${rt("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 (${rt("K")})`,dividerBefore:!0}];function yA(e){switch(e.kind){case"exec":document.execCommand(e.command);return;case"block":document.execCommand("formatBlock",!1,e.tag);return;case"code":pw();return;case"link":Wc();return}}function mw({hostRef:e,onChange:t}){let[n,o]=A(!1),[r,s]=A({top:0,left:0}),[a,c]=A(0),l=L(null),u=L(null),p=j(()=>{let f=e.current;if(!f){o(!1);return}let h=window.getSelection();if(!h||h.rangeCount===0||h.isCollapsed){o(!1);return}let v=h.getRangeAt(0);if(!f.contains(v.commonAncestorContainer)){o(!1);return}let x=v.getBoundingClientRect();if(x.width===0&&x.height===0){o(!1);return}let g=a||420,b=Math.max(qc,Math.min(x.left+x.width/2-g/2,window.innerWidth-g-qc)),I=Math.max(qc,x.top-qc-36);s({top:I,left:b}),o(!0)},[e,a]),d=j(()=>{if(u.current!==null)return;u.current=requestAnimationFrame(()=>{u.current=null,p()})},[p]);H(()=>(document.addEventListener("selectionchange",d),window.addEventListener("scroll",d,!0),window.addEventListener("resize",d),()=>{if(document.removeEventListener("selectionchange",d),window.removeEventListener("scroll",d,!0),window.removeEventListener("resize",d),u.current!==null)cancelAnimationFrame(u.current)}),[d]),_n(()=>{if(!n)return;let f=l.current;if(!f)return;let h=f.getBoundingClientRect().width;if(h&&Math.abs(h-a)>1)c(h)},[n,a]);let m=j((f)=>{yA(f),t(),p()},[t,p]);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:vA.flatMap((f,h)=>{let v=i("button",{type:"button",class:"md-inline-format-btn",title:f.title,onClick:()=>m(f),children:f.icon},`btn-${h}`,!1,void 0,this);return f.dividerBefore?[i("span",{class:"md-inline-format-divider"},`div-${h}`,!1,void 0,this),v]:[v]})},void 0,!1,void 0,this)}/*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */function fw(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function bA(e){if(Array.isArray(e))return e}function xA(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var o,r,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t===0);else for(;!(l=(o=s.call(n)).done)&&(c.push(o.value),c.length!==t);l=!0);}catch(p){u=!0,r=p}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return c}}function wA(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
166
166
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _A(e,t){return bA(e)||xA(e,t)||SA(e,t)||wA()}function SA(e,t){if(e){if(typeof e=="string")return fw(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?fw(e,t):void 0}}var{entries:Iw,setPrototypeOf:hw,isFrozen:kA,getPrototypeOf:TA,getOwnPropertyDescriptor:CA,freeze:Mt,seal:$t,create:yi}=Object,Pw=typeof Reflect<"u"&&Reflect,{apply:hp,construct:gp}=Pw;if(!Mt)Mt=function(t){return t};if(!$t)$t=function(t){return t};if(!hp)hp=function(t,n){for(var o=arguments.length,r=Array(o>2?o-2:0),s=2;s<o;s++)r[s-2]=arguments[s];return t.apply(n,r)};if(!gp)gp=function(t){for(var n=arguments.length,o=Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return new t(...o)};var gi=vt(Array.prototype.forEach),EA=vt(Array.prototype.lastIndexOf),gw=vt(Array.prototype.pop),vi=vt(Array.prototype.push),AA=vt(Array.prototype.splice),qo=Array.isArray,zs=vt(String.prototype.toLowerCase),up=vt(String.prototype.toString),vw=vt(String.prototype.match),Ps=vt(String.prototype.replace),yw=vt(String.prototype.indexOf),IA=vt(String.prototype.trim),PA=vt(Number.prototype.toString),NA=vt(Boolean.prototype.toString),bw=typeof BigInt>"u"?null:vt(BigInt.prototype.toString),xw=typeof Symbol>"u"?null:vt(Symbol.prototype.toString),Et=vt(Object.prototype.hasOwnProperty),Ns=vt(Object.prototype.toString),Ct=vt(RegExp.prototype.test),Cr=zA(TypeError);function vt(e){return function(t){if(t instanceof RegExp)t.lastIndex=0;for(var n=arguments.length,o=Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return hp(e,t,o)}}function zA(e){return function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];return gp(e,n)}}function ze(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:zs;if(hw)hw(e,null);if(!qo(t))return e;let o=t.length;while(o--){let r=t[o];if(typeof r==="string"){let s=n(r);if(s!==r){if(!kA(t))t[o]=s;r=s}}e[r]=!0}return e}function RA(e){for(let t=0;t<e.length;t++)if(!Et(e,t))e[t]=null;return e}function Wt(e){let t=yi(null);for(let o of Iw(e)){var n=_A(o,2);let r=n[0],s=n[1];if(Et(e,r))if(qo(s))t[r]=RA(s);else if(s&&typeof s==="object"&&s.constructor===Object)t[r]=Wt(s);else t[r]=s}return t}function MA(e){switch(typeof e){case"string":return e;case"number":return PA(e);case"boolean":return NA(e);case"bigint":return bw?bw(e):"0";case"symbol":return xw?xw(e):"Symbol()";case"undefined":return Ns(e);case"function":case"object":{if(e===null)return Ns(e);let t=e,n=jn(t,"toString");if(typeof n==="function"){let o=n(t);return typeof o==="string"?o:Ns(o)}return Ns(e)}default:return Ns(e)}}function jn(e,t){while(e!==null){let o=CA(e,t);if(o){if(o.get)return vt(o.get);if(typeof o.value==="function")return vt(o.value)}e=TA(e)}function n(){return null}return n}function $A(e){try{return Ct(e,""),!0}catch(t){return!1}}var ww=Mt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),dp=Mt(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),pp=Mt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),OA=Mt(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mp=Mt(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),LA=Mt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),_w=Mt(["#text"]),Sw=Mt(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),fp=Mt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),kw=Mt(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Gc=Mt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),DA=$t(/{{[\w\W]*|^[\w\W]*}}/g),FA=$t(/<%[\w\W]*|^[\w\W]*%>/g),BA=$t(/\${[\w\W]*/g),HA=$t(/^data-[\-\w.\u00B7-\uFFFF]+$/),jA=$t(/^aria-[\-\w]+$/),Tw=$t(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),UA=$t(/^(?:\w+script|data):/i),ZA=$t(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),WA=$t(/^html$/i),qA=$t(/^[a-z][.\w]*(-[.\w]+)+$/i),Cw=$t(/<[/\w!]/g),Ew=$t(/<[/\w]/g),GA=$t(/<\/no(script|embed|frames)/i),VA=$t(/\/>/i),gn={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},XA=function(){return typeof window>"u"?null:window},KA=function(t,n){if(typeof t!=="object"||typeof t.createPolicy!=="function")return null;let o=null,r="data-tt-policy-suffix";if(n&&n.hasAttribute(r))o=n.getAttribute(r);let s="dompurify"+(o?"#"+o:"");try{return t.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch(a){return console.warn("TrustedTypes policy "+s+" could not be created."),null}},Aw=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Wo=function(t,n,o,r){return Et(t,n)&&qo(t[n])?ze(r.base?Wt(r.base):{},t[n],r.transform):o};function Nw(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:XA(),t=(V)=>Nw(V);if(t.version="3.4.13",t.removed=[],!e||!e.document||e.document.nodeType!==gn.document||!e.Element)return t.isSupported=!1,t;let n=e.document,o=n,r=o.currentScript;e.DocumentFragment;let{HTMLTemplateElement:s,Node:a,Element:c,NodeFilter:l,NamedNodeMap:u}=e;u===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let{DOMParser:p,trustedTypes:d}=e,m=c.prototype,f=jn(m,"cloneNode"),h=jn(m,"remove"),v=jn(m,"nextSibling"),x=jn(m,"childNodes"),g=jn(m,"parentNode"),b=jn(m,"shadowRoot"),I=jn(m,"attributes"),R=a&&a.prototype?jn(a.prototype,"nodeType"):null,M=a&&a.prototype?jn(a.prototype,"nodeName"):null,_=a&&a.prototype?jn(a.prototype,"ownerDocument"):null;if(typeof s==="function"){let V=n.createElement("template");if(V.content&&V.content.ownerDocument)n=V.content.ownerDocument}let N,w="",k,z=!1,X=0,W=function(){if(X>0)throw Cr('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},J=function(y){W(),X++;try{return N.createHTML(y)}finally{X--}},G=function(y){W(),X++;try{return N.createScriptURL(y)}finally{X--}},S=function(){if(!z)k=KA(d,r),z=!0;return k},q=n,{implementation:ie,createNodeIterator:ye,createDocumentFragment:ue,getElementsByTagName:Pe}=q,ke=o.importNode,Me=Aw();t.isSupported=typeof Iw==="function"&&typeof g==="function"&&ie&&ie.createHTMLDocument!==void 0;let cn=DA,Pn=FA,D=BA,Y=HA,Te=jA,de=UA,be=ZA,se=qA,re=Tw,Z=null,xe=ze({},[...ww,...dp,...pp,...mp,..._w]),T=null,ce=ze({},[...Sw,...fp,...kw,...Gc]),pe=Object.seal(yi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),me=null,qt=null,St=Object.seal(yi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Gt=!0,yn=!0,ar=!1,da=!0,bn=!1,Nn=!0,eo=!1,Gi=!1,to=null,_o=null,Vi=!1,So=!1,ko=!1,ln=!1,cr=!0,Hr=!1,jr="user-content-",Q=!0,le=!1,Ce={},Ie=null,Bt=ze({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),zn=null,Un=ze({},["audio","video","img","source","image","track"]),To=null,au=ze({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),un="http://www.w3.org/1998/Math/MathML",xn="http://www.w3.org/2000/svg",wn="http://www.w3.org/1999/xhtml",no=wn,Ur=!1,Fe=null,Xi=ze({},[un,xn,wn],up),Ki=Mt(["mi","mo","mn","ms","mtext"]),Ee=ze({},Ki),ut=Mt(["annotation-xml"]),Ht=ze({},ut),oo=ze({},["title","style","font","a","script"]),Co=null,n0=["application/xhtml+xml","text/html"],o0="text/html",it=null,Zr=null,r0=n.createElement("form"),Km=function(y){return y instanceof RegExp||y instanceof Function},cu=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Zr&&Zr===y)return;if(!y||typeof y!=="object")y={};y=Wt(y),Co=n0.indexOf(y.PARSER_MEDIA_TYPE)===-1?o0:y.PARSER_MEDIA_TYPE,it=Co==="application/xhtml+xml"?up:zs,Z=Wo(y,"ALLOWED_TAGS",xe,{transform:it}),T=Wo(y,"ALLOWED_ATTR",ce,{transform:it}),Fe=Wo(y,"ALLOWED_NAMESPACES",Xi,{transform:up}),To=Wo(y,"ADD_URI_SAFE_ATTR",au,{transform:it,base:au}),zn=Wo(y,"ADD_DATA_URI_TAGS",Un,{transform:it,base:Un}),Ie=Wo(y,"FORBID_CONTENTS",Bt,{transform:it}),me=Wo(y,"FORBID_TAGS",Wt({}),{transform:it}),qt=Wo(y,"FORBID_ATTR",Wt({}),{transform:it}),Ce=Et(y,"USE_PROFILES")?y.USE_PROFILES&&typeof y.USE_PROFILES==="object"?Wt(y.USE_PROFILES):y.USE_PROFILES:!1,Gt=y.ALLOW_ARIA_ATTR!==!1,yn=y.ALLOW_DATA_ATTR!==!1,ar=y.ALLOW_UNKNOWN_PROTOCOLS||!1,da=y.ALLOW_SELF_CLOSE_IN_ATTR!==!1,bn=y.SAFE_FOR_TEMPLATES||!1,Nn=y.SAFE_FOR_XML!==!1,eo=y.WHOLE_DOCUMENT||!1,So=y.RETURN_DOM||!1,ko=y.RETURN_DOM_FRAGMENT||!1,ln=y.RETURN_TRUSTED_TYPE||!1,Vi=y.FORCE_BODY||!1,cr=y.SANITIZE_DOM!==!1,Hr=y.SANITIZE_NAMED_PROPS||!1,Q=y.KEEP_CONTENT!==!1,le=y.IN_PLACE||!1,re=$A(y.ALLOWED_URI_REGEXP)?y.ALLOWED_URI_REGEXP:Tw,no=typeof y.NAMESPACE==="string"?y.NAMESPACE:wn,Ee=Et(y,"MATHML_TEXT_INTEGRATION_POINTS")&&y.MATHML_TEXT_INTEGRATION_POINTS&&typeof y.MATHML_TEXT_INTEGRATION_POINTS==="object"?Wt(y.MATHML_TEXT_INTEGRATION_POINTS):ze({},Ki),Ht=Et(y,"HTML_INTEGRATION_POINTS")&&y.HTML_INTEGRATION_POINTS&&typeof y.HTML_INTEGRATION_POINTS==="object"?Wt(y.HTML_INTEGRATION_POINTS):ze({},ut);let E=Et(y,"CUSTOM_ELEMENT_HANDLING")&&y.CUSTOM_ELEMENT_HANDLING&&typeof y.CUSTOM_ELEMENT_HANDLING==="object"?Wt(y.CUSTOM_ELEMENT_HANDLING):yi(null);if(pe=yi(null),Et(E,"tagNameCheck")&&Km(E.tagNameCheck))pe.tagNameCheck=E.tagNameCheck;if(Et(E,"attributeNameCheck")&&Km(E.attributeNameCheck))pe.attributeNameCheck=E.attributeNameCheck;if(Et(E,"allowCustomizedBuiltInElements")&&typeof E.allowCustomizedBuiltInElements==="boolean")pe.allowCustomizedBuiltInElements=E.allowCustomizedBuiltInElements;if($t(pe),bn)yn=!1;if(ko)So=!0;if(Ce){if(Z=ze({},_w),T=yi(null),Ce.html===!0)ze(Z,ww),ze(T,Sw);if(Ce.svg===!0)ze(Z,dp),ze(T,fp),ze(T,Gc);if(Ce.svgFilters===!0)ze(Z,pp),ze(T,fp),ze(T,Gc);if(Ce.mathMl===!0)ze(Z,mp),ze(T,kw),ze(T,Gc)}if(St.tagCheck=null,St.attributeCheck=null,Et(y,"ADD_TAGS")){if(typeof y.ADD_TAGS==="function")St.tagCheck=y.ADD_TAGS;else if(qo(y.ADD_TAGS)){if(Z===xe)Z=Wt(Z);ze(Z,y.ADD_TAGS,it)}}if(Et(y,"ADD_ATTR")){if(typeof y.ADD_ATTR==="function")St.attributeCheck=y.ADD_ATTR;else if(qo(y.ADD_ATTR)){if(T===ce)T=Wt(T);ze(T,y.ADD_ATTR,it)}}if(Et(y,"ADD_URI_SAFE_ATTR")&&qo(y.ADD_URI_SAFE_ATTR))ze(To,y.ADD_URI_SAFE_ATTR,it);if(Et(y,"FORBID_CONTENTS")&&qo(y.FORBID_CONTENTS)){if(Ie===Bt)Ie=Wt(Ie);ze(Ie,y.FORBID_CONTENTS,it)}if(Et(y,"ADD_FORBID_CONTENTS")&&qo(y.ADD_FORBID_CONTENTS)){if(Ie===Bt)Ie=Wt(Ie);ze(Ie,y.ADD_FORBID_CONTENTS,it)}if(Q)Z["#text"]=!0;if(eo)ze(Z,["html","head","body"]);if(Z.table)ze(Z,["tbody"]),delete me.tbody;if(y.TRUSTED_TYPES_POLICY){if(typeof y.TRUSTED_TYPES_POLICY.createHTML!=="function")throw Cr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof y.TRUSTED_TYPES_POLICY.createScriptURL!=="function")throw Cr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let U=N;N=y.TRUSTED_TYPES_POLICY;try{w=J("")}catch(te){throw N=U,te}}else if(y.TRUSTED_TYPES_POLICY===null)N=void 0,w="";else{if(N===void 0)N=S();if(N&&typeof w==="string")w=J("")}if(Mt)Mt(y);Zr=y},Jm=ze({},[...dp,...pp,...OA]),Ym=ze({},[...mp,...LA]),i0=function(y,E,U){if(E.namespaceURI===wn)return y==="svg";if(E.namespaceURI===un)return y==="svg"&&(U==="annotation-xml"||Ee[U]);return Boolean(Jm[y])},s0=function(y,E,U){if(E.namespaceURI===wn)return y==="math";if(E.namespaceURI===xn)return y==="math"&&Ht[U];return Boolean(Ym[y])},a0=function(y,E,U){if(E.namespaceURI===xn&&!Ht[U])return!1;if(E.namespaceURI===un&&!Ee[U])return!1;return!Ym[y]&&(oo[y]||!Jm[y])},c0=function(y){let E=g(y);if(!E||!E.tagName)E={namespaceURI:no,tagName:"template"};let U=zs(y.tagName),te=zs(E.tagName);if(!Fe[y.namespaceURI])return!1;if(y.namespaceURI===xn)return i0(U,E,te);if(y.namespaceURI===un)return s0(U,E,te);if(y.namespaceURI===wn)return a0(U,E,te);if(Co==="application/xhtml+xml"&&Fe[y.namespaceURI])return!0;return!1},Eo=function(y){vi(t.removed,{element:y});try{g(y).removeChild(y)}catch(E){if(h(y),!g(y))throw Cr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},pa=function(y){Ji(y);let E=x(y);if(E){let te=[];gi(E,(ae)=>{vi(te,ae)}),gi(te,(ae)=>{try{h(ae)}catch(we){}})}let U=I(y);if(U)for(let te=U.length-1;te>=0;--te){let ae=U[te],we=ae&&ae.name;if(typeof we==="string")try{y.removeAttribute(we)}catch(We){}}},lr=function(y,E){try{vi(t.removed,{attribute:E.getAttributeNode(y),from:E})}catch(U){vi(t.removed,{attribute:null,from:E})}if(E.removeAttribute(y),y==="is")if(So||ko)try{Eo(E)}catch(U){}else try{E.setAttribute(y,"")}catch(U){}},l0=function(y){let E=I(y);if(!E)return;for(let U=E.length-1;U>=0;--U){let te=E[U],ae=te&&te.name;if(typeof ae!=="string"||T[it(ae)])continue;try{y.removeAttribute(ae)}catch(we){}}},Ji=function(y){let E=[y];while(E.length>0){let U=E.pop();if((R?R(U):U.nodeType)===gn.element)l0(U);let ae=x(U);if(ae)for(let we=ae.length-1;we>=0;--we)E.push(ae[we])}},u0=function(y){if(!Nn)return;let E=[y];while(E.length>0){let U=E.pop(),te=R?R(U):U.nodeType;if(te===gn.processingInstruction||te===gn.comment&&Ct(Ew,U.data)){try{h(U)}catch(we){}continue}if(te===gn.element){let we=U,We=it(M?M(U):U.nodeName);try{if(we.hasAttribute&&we.hasAttribute("patchsrc"))we.removeAttribute("patchsrc");if(we.hasAttribute&&we.hasAttribute("for")&&We!=="label"&&We!=="output")we.removeAttribute("for")}catch(st){}}let ae=x(U);if(ae)for(let we=ae.length-1;we>=0;--we)E.push(ae[we])}},Qm=function(y){let E=null,U=null;if(Vi)y="<remove></remove>"+y;else{let we=vw(y,/^[\r\n\t ]+/);U=we&&we[0]}if(Co==="application/xhtml+xml"&&no===wn)y='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+y+"</body></html>";let te=N?J(y):y;if(no===wn)try{E=new p().parseFromString(te,Co)}catch(we){}if(!E||!E.documentElement){E=ie.createDocument(no,"template",null);try{E.documentElement.innerHTML=Ur?w:te}catch(we){}}let ae=E.body||E.documentElement;if(y&&U)ae.insertBefore(n.createTextNode(U),ae.childNodes[0]||null);if(no===wn)return Pe.call(E,eo?"html":"body")[0];return eo?E.documentElement:ae},ef=function(y){let E=_?_(y):y.ownerDocument;return ye.call(E||y,y,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ma=function(y){return y=Ps(y,cn," "),y=Ps(y,Pn," "),y=Ps(y,D," "),y},lu=function(y){var E;y.normalize();let U=_?_(y):y.ownerDocument,te=ye.call(U||y,y,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),ae=te.nextNode();while(ae)ae.data=ma(ae.data),ae=te.nextNode();let we=(E=y.querySelectorAll)===null||E===void 0?void 0:E.call(y,"template");if(we)gi(we,(We)=>{if(Wr(We.content))lu(We.content)})},fa=function(y){let E=M?M(y):null;if(typeof E!=="string")return!1;if(it(E)!=="form")return!1;return typeof y.nodeName!=="string"||typeof y.textContent!=="string"||typeof y.removeChild!=="function"||y.attributes!==I(y)||typeof y.removeAttribute!=="function"||typeof y.setAttribute!=="function"||typeof y.namespaceURI!=="string"||typeof y.insertBefore!=="function"||typeof y.hasChildNodes!=="function"||y.nodeType!==R(y)||y.childNodes!==x(y)},Wr=function(y){if(!R||typeof y!=="object"||y===null)return!1;try{return R(y)===gn.documentFragment}catch(E){return!1}},Yi=function(y){if(!R||typeof y!=="object"||y===null)return!1;try{return typeof R(y)==="number"}catch(E){return!1}};function Zn(V,y,E){if(V.length===0)return;gi(V,(U)=>{U.call(t,y,E,Zr)})}let d0=function(y,E){if(Nn&&y.hasChildNodes()&&!Yi(y.firstElementChild)&&Ct(Cw,y.textContent)&&Ct(Cw,y.innerHTML))return!0;if(Nn&&y.namespaceURI===wn&&E==="style"&&Yi(y.firstElementChild))return!0;if(y.nodeType===gn.processingInstruction)return!0;if(Nn&&y.nodeType===gn.comment&&Ct(Ew,y.data))return!0;return!1},p0=function(y,E,U){if(!me[E]&&rf(E)){if(pe.tagNameCheck instanceof RegExp&&Ct(pe.tagNameCheck,E))return!1;if(pe.tagNameCheck instanceof Function&&pe.tagNameCheck(E))return!1}if(Q&&!Ie[E]){let te=g(y),ae=x(y);if(ae&&te){let we=ae.length;for(let We=we-1;We>=0;--We){let st=y===U?f(ae[We],!0):ae[We];te.insertBefore(st,v(y))}}}return Eo(y),!0},tf=function(y,E,U,te){if(y.length===0)return E;return E===U||E===te?Wt(E):E},nf=function(y,E){if(Zn(Me.beforeSanitizeElements,y,null),y!==E&&g(y)===null){if(le)Ji(y);return!0}if(fa(y))return Eo(y),!0;let U=it(M?M(y):y.nodeName);if(Z=tf(Me.uponSanitizeElement,Z,xe,to),Zn(Me.uponSanitizeElement,y,{tagName:U,allowedTags:Z}),y!==E&&g(y)===null){if(le)Ji(y);return!0}if(d0(y,U))return Eo(y),!0;if(me[U]||!(St.tagCheck instanceof Function&&St.tagCheck(U))&&!Z[U]){let ae=p0(y,U,E);if(ae===!1)Zn(Me.afterSanitizeElements,y,null);return ae}if((R?R(y):y.nodeType)===gn.element&&!c0(y))return Eo(y),!0;if((U==="noscript"||U==="noembed"||U==="noframes")&&Ct(GA,y.innerHTML))return Eo(y),!0;if(bn&&y.nodeType===gn.text){let ae=ma(y.textContent);if(y.textContent!==ae)vi(t.removed,{element:y.cloneNode()}),y.textContent=ae}return Zn(Me.afterSanitizeElements,y,null),!1},of=function(y,E,U){if(qt[E])return!1;if(Nn&&E==="patchsrc")return!1;if(Nn&&E==="for"&&y!=="label"&&y!=="output")return!1;if(cr&&(E==="id"||E==="name")&&((U in n)||(U in r0)))return!1;let te=T[E]||St.attributeCheck instanceof Function&&St.attributeCheck(E,y);if(yn&&Ct(Y,E));else if(Gt&&Ct(Te,E));else if(!te)if(rf(y)&&(pe.tagNameCheck instanceof RegExp&&Ct(pe.tagNameCheck,y)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(y))&&(pe.attributeNameCheck instanceof RegExp&&Ct(pe.attributeNameCheck,E)||pe.attributeNameCheck instanceof Function&&pe.attributeNameCheck(E,y))||E==="is"&&pe.allowCustomizedBuiltInElements&&(pe.tagNameCheck instanceof RegExp&&Ct(pe.tagNameCheck,U)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(U)));else return!1;else if(To[E]);else if(Ct(re,Ps(U,be,"")));else if((E==="src"||E==="xlink:href"||E==="href")&&y!=="script"&&yw(U,"data:")===0&&zn[y]);else if(ar&&!Ct(de,Ps(U,be,"")));else if(U)return!1;return!0},m0=ze({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),rf=function(y){return!m0[zs(y)]&&Ct(se,y)},f0=function(y,E,U,te){if(N&&typeof d==="object"&&typeof d.getAttributeType==="function"&&!U)switch(d.getAttributeType(y,E)){case"TrustedHTML":return J(te);case"TrustedScriptURL":return G(te)}return te},h0=function(y,E,U,te){try{if(U)y.setAttributeNS(U,E,te);else y.setAttribute(E,te);if(fa(y))Eo(y);else gw(t.removed)}catch(ae){lr(E,y)}},sf=function(y){Zn(Me.beforeSanitizeAttributes,y,null);let E=y.attributes;if(!E||fa(y))return;T=tf(Me.uponSanitizeAttribute,T,ce,_o);let U={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:T,forceKeepAttr:void 0},te=E.length,ae=it(y.nodeName);while(te--){let we=E[te],{name:We,namespaceURI:st,value:en}=we,tn=it(We),du=en,Vt=We==="value"?du:IA(du);if(U.attrName=tn,U.attrValue=Vt,U.keepAttr=!0,U.forceKeepAttr=void 0,Zn(Me.uponSanitizeAttribute,y,U),Vt=U.attrValue,Hr&&(tn==="id"||tn==="name")&&yw(Vt,jr)!==0)lr(We,y),Vt=jr+Vt;if(Nn&&Ct(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Vt)){lr(We,y);continue}if(tn==="attributename"&&vw(Vt,"href")){lr(We,y);continue}if(U.forceKeepAttr)continue;if(!U.keepAttr){lr(We,y);continue}if(!da&&Ct(VA,Vt)){lr(We,y);continue}if(bn)Vt=ma(Vt);if(!of(ae,tn,Vt)){lr(We,y);continue}if(Vt=f0(ae,tn,st,Vt),Vt!==du)h0(y,We,st,Vt)}Zn(Me.afterSanitizeAttributes,y,null)},ha=function(y){let E=null,U=ef(y);Zn(Me.beforeSanitizeShadowDOM,y,null);while(E=U.nextNode()){if(Zn(Me.uponSanitizeShadowNode,E,null),nf(E,y),sf(E),Wr(E.content))ha(E.content);if((R?R(E):E.nodeType)===gn.element){let ae=b(E);if(Wr(ae))uu(ae),ha(ae)}}Zn(Me.afterSanitizeShadowDOM,y,null)},uu=function(y){let E=[{node:y,shadow:null}];while(E.length>0){let U=E.pop();if(U.shadow){ha(U.shadow);continue}let te=U.node,we=(R?R(te):te.nodeType)===gn.element,We=x(te);if(We)for(let st=We.length-1;st>=0;--st)E.push({node:We[st],shadow:null});if(we){let st=M?M(te):null;if(typeof st==="string"&&it(st)==="template"){let en=te.content;if(Wr(en))E.push({node:en,shadow:null})}}if(we){let st=b(te);if(Wr(st))E.push({node:null,shadow:st},{node:st,shadow:null})}}};return t.sanitize=function(V){let y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=null,U=null,te=null,ae=null;if(Ur=!V,Ur)V="<!-->";if(typeof V!=="string"&&!Yi(V)){if(V=MA(V),typeof V!=="string")throw Cr("dirty is not a string, aborting")}if(!t.isSupported)return V;if(Gi)Z=to,T=_o;else cu(y);if(Me.uponSanitizeElement.length>0||Me.uponSanitizeAttribute.length>0)Z=Wt(Z);if(Me.uponSanitizeAttribute.length>0)T=Wt(T);t.removed=[];let we=le&&typeof V!=="string"&&Yi(V);if(we){u0(V);let en=M?M(V):V.nodeName;if(typeof en==="string"){let tn=it(en);if(!Z[tn]||me[tn])throw pa(V),Cr("root node is forbidden and cannot be sanitized in-place")}if(fa(V))throw pa(V),Cr("root node is clobbered and cannot be sanitized in-place");try{uu(V)}catch(tn){throw pa(V),tn}}else if(Yi(V)){if(E=Qm("<!---->"),U=E.ownerDocument.importNode(V,!0),U.nodeType===gn.element&&U.nodeName==="BODY")E=U;else if(U.nodeName==="HTML")E=U;else E.appendChild(U);uu(U)}else{if(!So&&!bn&&!eo&&V.indexOf("<")===-1)return N&&ln?J(V):V;if(E=Qm(V),!E)return So?null:ln?w:""}if(E&&Vi)Eo(E.firstChild);let We=we?V:E;try{let en=ef(We);while(te=en.nextNode())if(nf(te,We),sf(te),Wr(te.content))ha(te.content)}catch(en){if(we)pa(V),gi(t.removed,(tn)=>{if(tn.element)Ji(tn.element)});throw en}if(we){if(gi(t.removed,(en)=>{if(en.element)Ji(en.element)}),bn)lu(V);return V}if(So){if(bn)lu(E);if(ko){ae=ue.call(E.ownerDocument);while(E.firstChild)ae.appendChild(E.firstChild)}else ae=E;if(T.shadowroot||T.shadowrootmode)ae=ke.call(o,ae,!0);return ae}let st=eo?E.outerHTML:E.innerHTML;if(eo&&Z["!doctype"]&&E.ownerDocument&&E.ownerDocument.doctype&&E.ownerDocument.doctype.name&&Ct(WA,E.ownerDocument.doctype.name))st="<!DOCTYPE "+E.ownerDocument.doctype.name+`>
167
- `+st;if(bn)st=ma(st);return N&&ln?J(st):st},t.setConfig=function(){let V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};cu(V),Gi=!0,to=Z,_o=T},t.clearConfig=function(){Zr=null,Gi=!1,to=null,_o=null,N=k,w=""},t.isValidAttribute=function(V,y,E){if(!Zr)cu({});let U=it(V),te=it(y);return of(U,te,E)},t.addHook=function(V,y){if(typeof y!=="function")return;if(!Et(Me,V))return;vi(Me[V],y)},t.removeHook=function(V,y){if(!Et(Me,V))return;if(y!==void 0){let E=EA(Me[V],y);return E===-1?void 0:AA(Me[V],E,1)[0]}return gw(Me[V])},t.removeHooks=function(V){if(!Et(Me,V))return;Me[V]=[]},t.removeAllHooks=function(){Me=Aw()},t}var zw=Nw();function Qn(e){return zw.sanitize(e,{FORBID_TAGS:["form","svg","math"]})}var vp=null;function JA(){if(vp)return vp;let e=new Is({headingStyle:"atx",codeBlockStyle:"fenced",emDelimiter:"*",bulletListMarker:"-"});return e.use(Rw.gfm),vp=e,e}function Mw({initialHtml:e,className:t,onChange:n,onSave:o}){let r=L(null),s=L(e);H(()=>{let m=r.current;if(!m)return;m.innerHTML=Qn(s.current);for(let f of m.querySelectorAll('input[type="checkbox"][disabled]'))f.removeAttribute("disabled")},[]);let a=j(()=>{let m=r.current;if(!m)return"";return JA().turndown(m.innerHTML)},[]),c=j(()=>{n(a())},[n,a]),l=j(()=>{let m=r.current;if(!m||!m.isConnected||m.innerHTML==="")return;o?.(a())},[o,a]),u=j((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(),Wc(),c()},[c,l]),p=j((m)=>{let f=m.target;if(f instanceof HTMLInputElement&&f.type==="checkbox")f.toggleAttribute("checked",f.checked),c()},[c]),d=j((m)=>{let f=m.clipboardData?.getData("text/plain");if(f==null)return;m.preventDefault(),document.execCommand("insertText",!1,f),c()},[c]);return i(_e,{children:[i("div",{ref:r,class:t,contentEditable:!0,spellcheck:!1,onInput:c,onKeyDown:u,onPaste:d,onClick:p,onBlur:l},void 0,!1,void 0,this),i(mw,{hostRef:r,onChange:c},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yp({html:e,className:t,style:n,onTaskToggle:o}){let r=L(null),s=L(o);return s.current=o,H(()=>{let c=r.current;if(!c)return;if(c.replaceChildren(),!e)return;let l=document.createElement("template");if(l.innerHTML=Qn(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 p=c.target,d=null;if(p instanceof HTMLInputElement&&p.type==="checkbox")d=p;else{let h=p.closest("li")?.querySelector(':scope > input[type="checkbox"]');if(h&&c.clientX<=h.getBoundingClientRect().right+6)d=h}if(!d)return;c.stopPropagation();let m=[...u.querySelectorAll('input[type="checkbox"]')].indexOf(d);if(m>=0)l(m)}:void 0},void 0,!1,void 0,this)}function YA(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 Vc({node:e,expanded:t=!1}){let n=dc(),o=e.data.path,[r,s]=A(""),[a,c]=A(""),[l,u]=A(!1),[p,d]=A(!1),[m,f]=A(!1),[h,v]=A(!1),x=L(null),g=L(null),b=L(""),I=L(null),R=L(!1),M=L({boardId:Oe.value,revision:e.contentRevision??0}),_=L(Promise.resolve()),N=e.data.reviewActive;H(()=>{if(Se()&&R.current)return;M.current={boardId:Oe.value,revision:e.contentRevision??0};let S=!1;return(async()=>{let q;if(o){let ye=await vs(o);if(S)return;q=ye.content}else if(e.data.content)q=e.data.content;else{u(!0);return}s(q);let ie=await Vn(q);if(S||Se()&&R.current)return;c(ie),u(!0),fe(e.id,{content:q,rendered:ie})})(),()=>{S=!0}},[o,e.id,e.data.content]);let w=j(async(S)=>{let q=S.target.value;R.current=!0,b.current=q,s(q),v(!0);let ie=await Vn(q);c(ie)},[]),k=j(async(S)=>{if(Se()){_.current=_.current.then(async()=>{f(!0);let ie=await kt(e.id,{content:S,expectedBoardId:M.current.boardId,expectedContentRevision:M.current.revision});if(f(!1),!ie.ok)return;M.current.revision=ie.contentRevision??M.current.revision;let ye=F.value.get(e.id);if(ye)F.value=new Map(F.value).set(e.id,{...ye,contentRevision:M.current.revision});if(b.current!==S)return;R.current=!1,v(!1);let ue=await Vn(S);c(ue),fe(e.id,{content:S,rendered:ue})}),await _.current;return}if(!o){let ie=await Vn(S);c(ie),v(!1),fe(e.id,{content:S,rendered:ie}),await kt(e.id,{content:S,data:{rendered:ie}});return}f(!0);let q=await mb(o,S);if(f(!1),q.ok){let ie=await Vn(S);c(ie),v(!1),fe(e.id,{content:S,rendered:ie,savedAt:q.updatedAt}),await kt(e.id,{content:S,data:{rendered:ie,savedAt:q.updatedAt}})}},[o,e.id]),z=j(async()=>{if(!h)return;await k(r)},[h,r,k]),X=j((S)=>{if((S.metaKey||S.ctrlKey)&&S.key==="s"){S.preventDefault(),z();return}let q=x.current;if(q&&$x(S,q))return;if(q&&S.key==="Tab")S.preventDefault(),Mx(q,S.shiftKey)},[z]);I.current=k;let W=j((S)=>{if(R.current=!0,s(S),v(!0),b.current=S,g.current!==null)window.clearTimeout(g.current);g.current=window.setTimeout(()=>{g.current=null,k(S)},800)},[k]),J=j((S)=>{if(R.current=!0,s(S),b.current=S,g.current!==null)window.clearTimeout(g.current),g.current=null;k(S)},[k]);H(()=>()=>{if(g.current===null)return;window.clearTimeout(g.current),g.current=null;let S=I.current;if(S)S(b.current)},[e.id]);let G=N?i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-ok) 10%, transparent)",color:"var(--c-ok)",borderBottom:"1px solid color-mix(in srgb, var(--c-ok) 20%, transparent)",textTransform:"uppercase",letterSpacing:"0.05em",fontWeight:600},children:"Review active"},void 0,!1,void 0,this):null;if(p&&t)return i("div",{class:"md-editor-expanded",onKeyDown:X,children:[i("div",{class:"md-editor-toolbar",children:[i("button",{type:"button",class:"md-toolbar-btn",onClick:()=>d(!1),children:[i(sx,{size:14},void 0,!1,void 0,this)," Back to document"]},void 0,!0,void 0,this),i("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[o&&i("span",{class:"md-toolbar-path",children:o.split("/").pop()},void 0,!1,void 0,this),i("button",{type:"button",class:`md-toolbar-btn${h?" md-toolbar-btn-primary":""}`,onClick:z,disabled:!h||m,children:m?"Saving…":h?"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:x,value:r,onInput:w,spellcheck:!1},void 0,!1,void 0,this),i(Jd,{textareaRef:x},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(yp,{html:a,className:"md-preview"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(p)return i("div",{class:"md-editor-split",style:{height:"100%"},onKeyDown:X,children:[i("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[i("textarea",{ref:x,value:r,onInput:w,spellcheck:!1},void 0,!1,void 0,this),i(Jd,{textareaRef:x},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(yp,{html:a,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:z,disabled:!h||m,style:{padding:"4px 10px",fontSize:"11px",background:h?"color-mix(in srgb, var(--c-accent) 25%, transparent)":"var(--c-input-bg)",border:`1px solid ${h?"var(--c-accent)":"var(--c-line)"}`,borderRadius:"6px",color:h?"var(--c-text)":"var(--c-dim)",cursor:h?"pointer":"default"},children:m?"Saving…":h?"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:[G,i("div",{class:"md-reader",children:l?i(Mw,{initialHtml:a||"<p><br></p>",className:"md-reader-content md-reader-editable",onChange:W,onSave:J},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",{class:"md-card-preview",children:[i("div",{class:"md-card-content",children:[G,i(yp,{html:a,style:{padding:a?"0":"12px",color:a?void 0:"var(--c-dim)"},onTaskToggle:(S)=>{let q=YA(r,S);if(q!==r)J(q)}},void 0,!1,void 0,this),!l&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Loading…"},void 0,!1,void 0,this),l&&!a&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Empty node"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.data.source&&typeof e.data.source==="object"&&"attachmentId"in e.data.source&&i("div",{class:"md-import-source",children:["Source material ·"," ",i("a",{href:`/api/canvas/attachments/${encodeURIComponent(String(e.data.source.attachmentId))}/bytes`,target:"_blank",rel:"noopener noreferrer",children:String(e.data.source.filename??"Original")},void 0,!1,void 0,this)," · ",String(e.data.source.reference??"Location not supplied")]},void 0,!0,void 0,this),i("div",{class:"md-card-actions",children:[n&&i("button",{type:"button",class:"md-readme-btn","aria-pressed":n.readmeNodeId===e.id,onClick:()=>void ub(n.id,n.readmeNodeId===e.id?null:e.id),children:n.readmeNodeId===e.id?"README":"Set as README"},void 0,!1,void 0,this),i("button",{type:"button",class:"md-card-edit",onClick:()=>kn(e.id),children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Xc="pmx-canvas-ax",Kc="pmx-canvas-ax-ack",Tn="pmx-canvas-html-node",bp="pmx-canvas-json-state",Jc="pmx-canvas-ext-app-alive",xp="pmx-canvas-ext-app-paint-probe";function $w(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 wp="allow-scripts allow-popups allow-popups-to-escape-sandbox";function bi(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 Rs(e,t={}){let n=new URLSearchParams;if(n.set("theme",t.theme??gt.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 Yc(e){return $w(e.type,e.data)}async function Qc(e){if(Se()){on("context","Open in focus mode","This surface has no public URL. Use Expand to view it here, or export the board to download it.");return}let t=Rs(e.id);if(!(await bb(e.id,t)).opened)window.open(t,"_blank","noopener")}var Ow=30000;var _p=80;var lt=K(new Map),wi=K(null),QA=480,eI=320,tI=650,Ms=new Map,xi=new Map,el=new Map,vo=null;function Sp(e){lt.value=e,nI()}function kp(e){let t=Ms.get(e);if(t)clearTimeout(t),Ms.delete(e)}function Tp(e){let t=xi.get(e);if(t)clearTimeout(t),xi.delete(e)}function Dw(e){if(kp(e.id),Tp(e.id),!lt.value.has(e.id))el.set(e.id,Date.now());let t=new Map(lt.value);t.set(e.id,{...e,phase:"forming"}),Sp(t)}function Er(e){if(kp(e),Tp(e),el.delete(e),!lt.value.has(e))return;let t=new Map(lt.value);t.delete(e),Sp(t)}function Lw(e,t,n,o){let r=lt.value.get(e);if(!r||r.phase===t)return;let s=new Map(lt.value);s.set(e,{...r,phase:t,...o?{settledNodeId:o}:{}}),Sp(s),kp(e),Ms.set(e,setTimeout(()=>Er(e),n+1500))}function Fw(e,t,n,o){Tp(e);let r=Date.now()-(el.get(e)??0),s=Math.max(0,tI-r);if(s===0){Lw(e,t,n,o);return}xi.set(e,setTimeout(()=>{xi.delete(e),Lw(e,t,n,o)},s))}function Bw(e,t){Fw(e,"settling",QA,t)}function Cp(e){Fw(e,"dissolving",eI)}function tl(){for(let e of Ms.values())clearTimeout(e);Ms.clear();for(let e of xi.values())clearTimeout(e);if(xi.clear(),el.clear(),vo)clearInterval(vo),vo=null;wi.value=null,lt.value=new Map}function nI(){if(vo||lt.value.size===0)return;vo=setInterval(()=>{let e=Date.now();for(let t of lt.value.values())if(t.phase==="forming"&&t.expiresAt<=e)Cp(t.id);if(lt.value.size===0&&vo)clearInterval(vo),vo=null},1000),vo.unref?.()}function oI(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 rl=oI("pmx-canvas-human-client",()=>`tab-${Math.random().toString(36).slice(2,8)}`);function rI(){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-${rl.slice(-4)}`}var jw=K(rI()),Uw=K([]),Os=Ge(()=>Uw.value.filter((e)=>e.clientId!==rl)),Ar=K(new Map);function Ep(e){if(!e||!Array.isArray(e.humans))return;Uw.value=e.humans}var _i=K(null),il=null,Zw=0,$s=null;function ol(e){if(Se())return;$n("humanPresence","/api/canvas/human-presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:rl,name:jw.value,...e})})}function Hw(){$s=null,Zw=Date.now(),ol({cursor:il,grabbingNodeId:_i.value})}function sl(e){il=e;let t=Date.now()-Zw;if(t>=_p){if($s)clearTimeout($s);Hw()}else if(!$s)$s=setTimeout(Hw,_p-t)}function Ap(e){_i.value=e,ol({cursor:il,grabbingNodeId:e})}function iI(e,t){let n=new Map(Ar.value);n.set(e,t),Ar.value=n,setTimeout(()=>{let o=new Map(Ar.value);if(o.get(e)===t)o.delete(e),Ar.value=o},6000)}function Ww(e,t){let n=[...lt.value.values()].filter((r)=>r.nodeId===e&&!r.auto&&r.phase==="forming");if(n.length===0)return;let o=jw.value;iI(e,o);for(let r of n)br({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)Er(r.id)});$n("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 nl=null;function qw(){ol({cursor:il,grabbingNodeId:_i.value}),nl=setInterval(()=>ol({grabbingNodeId:_i.value}),3000);let e=()=>{try{navigator.sendBeacon?.("/api/canvas/human-presence",new Blob([JSON.stringify({clientId:rl,left:!0})],{type:"application/json"}))}catch{}};return window.addEventListener("pagehide",e),()=>{if(nl)clearInterval(nl);nl=null,window.removeEventListener("pagehide",e)}}var sI={markdown:{width:360,height:180},board:{width:320,height:140},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 Gw(e){return sI[e]}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 aI(e,t,n,o,r){return o.some((s)=>Vw(e,t,n,s,r))}function al(e,t,n,o,r){return o.find((s)=>Vw(e,t,n,s,r))}function cl(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(!aI(s,t,n,e,o))return s;let a=40,c=80,l=3000,u=c;for(let d=0;d<20;d++){let m=a;while(m+t<l){let v=al({x:m,y:u},t,n,e,o);if(!v)return{x:m,y:u};m=v.position.x+v.size.width+o}u=e.filter((v)=>v.position.y<=u+n+o&&v.position.y+v.size.height+o>u).reduce((v,x)=>Math.max(v,x.position.y+x.size.height),u)+o}let p=e.reduce((d,m)=>Math.max(d,m.position.y+m.size.height),0);return{x:a,y:p+o}}var Si=37,cI=600,lI=1400,uI=24;function dI(e){return e.type==="html"||e.type==="mermaid"||e.type==="json-render"||e.type==="graph"||e.type==="mcp-app"||e.type==="webpage"}function pI(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 Xw(e){return e.collapsed===!0||e.data.strictSize===!0||e.data.userResized===!0||e.type==="group"}function Ip(e){return!Xw(e)&&!dI(e)}function Kw(e,t){if(!Ip(e)||t<=0)return null;let n=Math.min(t+Si,cI),o=Gw(e.type);return o?Math.max(n,o.height):n}function Pp(e){return pI(e)&&!Xw(e)}function Jw(e,t){if(!Pp(e)||!Number.isFinite(t)||t<=0)return null;let n=Math.min(t+Si+uI,lI);return n>e.size.height+8?n:null}function Yw(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=al(r,e.size.width,t,o,24);while(s)r.y=s.position.y+s.size.height+24,s=al(r,e.size.width,t,o,24);return r}function ki(e,t,n){H(()=>{if(!n)return;let o=null,r=null,s=()=>_i.value===e.id||Os.value.some((p)=>p.grabbingNodeId===e.id);function a(){if(o=null,s()||r===null)return;let p=r;r=null;let d=F.value.get(e.id);if(!d)return;let m=Jw(d,p);if(m===null)return;let f=Yw(d,m,Array.from(F.value.values())),h=f.x!==d.position.x||f.y!==d.position.y,v={size:{width:d.size.width,height:m},...h?{position:f}:{}};wt(d.id,v),hc([{id:d.id,...v}],{recordHistory:h})}function c(){if(o!==null)clearTimeout(o);o=r!==null&&!s()?setTimeout(a,300):null}let l=nn(()=>{s(),c()});function u(p){if(p.source!==t.current?.contentWindow)return;let d=p.data;if(!d||d.source!=="pmx-canvas-frame"||d.type!=="content-height"||d.token!==n)return;if(typeof d.height!=="number"||!Number.isFinite(d.height)||d.height<=0)return;r=d.height,c()}return window.addEventListener("message",u),()=>{if(window.removeEventListener("message",u),l(),o!==null)clearTimeout(o)}},[e.id,n])}function mI(e){if(Se())return e.startsWith("/")&&!e.startsWith("//");try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Ti(e){let t=Rt.value,[n,o]=A(null),r=Boolean(e)&&mI(e),s=t==="srcdoc"&&r;if(H(()=>{if(!s)return;let a=!1;return ct(`${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 ll({node:e,expanded:t=!1}){let n=L(null),o=gt.value,r=Be(()=>`theme-${crypto.randomUUID()}`,[]),s=Be(()=>`frame-${crypto.randomUUID()}`,[]),a=typeof e.data.content==="string"?e.data.content:"",c=e.data.fit==="none"?"none":"contain",l=Be(()=>bi(`${c}:${a}`),[a,c]),u=Be(()=>a?Rs(e.id,{theme:o,themeToken:r,v:l,frameToken:s}):"",[a,r,l,e.id,s]),p=Ti(u);ki(e,n,t?"":s);let d=()=>{n.current?.contentWindow?.postMessage({source:Tn,type:"theme-update",token:r,theme:o},"*")};if(H(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",...p,onLoad:d,style:{width:"100%",height:"100%",minHeight:t?"70vh":"0",border:"none",background:"var(--c-bg)",borderRadius:"6px",display:"block"}},void 0,!1,void 0,this)}var Np=["harbor","daylight","high-contrast","midnight","sepia","arctic","ember","forest","volt"];function Ls(e){return typeof e==="string"&&Np.includes(e)}function zp(e,t="harbor"){return Ls(e)?e:t}var Ci={harbor:{label:"Harbor",scheme:"dark",swatchBg:"#081524",swatchAccent:"#4BBCFF"},daylight:{label:"Daylight",scheme:"light",swatchBg:"#F6F7F9",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 Go(e){return Ci[zp(e)].scheme}var Vo="io.modelcontextprotocol/related-task",dl="2.0",Ot=Ey((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),Qw=Ae([P(),ge().int()]),e_=P(),d2=Kt({ttl:Ae([ge(),cd()]).optional(),pollInterval:ge().optional()}),fI=O({ttl:ge().optional()}),hI=O({taskId:P()}),Rp=Kt({progressToken:Qw.optional(),[Vo]:hI.optional()}),vn=O({_meta:Rp.optional()}),Ds=vn.extend({task:fI.optional()}),t_=(e)=>Ds.safeParse(e).success,Lt=O({method:P(),params:vn.loose().optional()}),Cn=O({_meta:Rp.optional()}),En=O({method:P(),params:Cn.loose().optional()}),Dt=Kt({_meta:Rp.optional()}),Ai=Ae([P(),ge().int()]),n_=O({jsonrpc:C(dl),id:Ai,...Lt.shape}).strict(),Mp=(e)=>n_.safeParse(e).success,o_=O({jsonrpc:C(dl),...En.shape}).strict(),r_=(e)=>o_.safeParse(e).success,$p=O({jsonrpc:C(dl),id:Ai,result:Dt}).strict(),Fs=(e)=>$p.safeParse(e).success;var Ue;(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"})(Ue||(Ue={}));var Op=O({jsonrpc:C(dl),id:Ai.optional(),error:O({code:ge().int(),message:P(),data:qe().optional()})}).strict();var i_=(e)=>Op.safeParse(e).success;var s_=Ae([n_,o_,$p,Op]),p2=Ae([$p,Op]),Lp=Dt.strict(),gI=Cn.extend({requestId:Ai.optional(),reason:P().optional()}),pl=En.extend({method:C("notifications/cancelled"),params:gI}),vI=O({src:P(),mimeType:P().optional(),sizes:he(P()).optional(),theme:Jt(["light","dark"]).optional()}),Bs=O({icons:he(vI).optional()}),Ei=O({name:P(),title:P().optional()}),Hs=Ei.extend({...Ei.shape,...Bs.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),yI=Wa(O({applyDefaults:Xe().optional()}),Ze(P(),qe())),bI=dd((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Wa(O({form:yI.optional(),url:Ot.optional()}),Ze(P(),qe()).optional())),xI=Kt({list:Ot.optional(),cancel:Ot.optional(),requests:Kt({sampling:Kt({createMessage:Ot.optional()}).optional(),elicitation:Kt({create:Ot.optional()}).optional()}).optional()}),wI=Kt({list:Ot.optional(),cancel:Ot.optional(),requests:Kt({tools:Kt({call:Ot.optional()}).optional()}).optional()}),_I=O({experimental:Ze(P(),Ot).optional(),sampling:O({context:Ot.optional(),tools:Ot.optional()}).optional(),elicitation:bI.optional(),roots:O({listChanged:Xe().optional()}).optional(),tasks:xI.optional()}),SI=vn.extend({protocolVersion:P(),capabilities:_I,clientInfo:Hs}),kI=Lt.extend({method:C("initialize"),params:SI});var TI=O({experimental:Ze(P(),Ot).optional(),logging:Ot.optional(),completions:Ot.optional(),prompts:O({listChanged:Xe().optional()}).optional(),resources:O({subscribe:Xe().optional(),listChanged:Xe().optional()}).optional(),tools:O({listChanged:Xe().optional()}).optional(),tasks:wI.optional()}),CI=Dt.extend({protocolVersion:P(),capabilities:TI,serverInfo:Hs,instructions:P().optional()}),EI=En.extend({method:C("notifications/initialized"),params:Cn.optional()});var Ir=Lt.extend({method:C("ping"),params:vn.optional()}),AI=O({progress:ge(),total:at(ge()),message:at(P())}),II=O({...Cn.shape,...AI.shape,progressToken:Qw}),ml=En.extend({method:C("notifications/progress"),params:II}),PI=vn.extend({cursor:e_.optional()}),js=Lt.extend({params:PI.optional()}),Us=Dt.extend({nextCursor:e_.optional()}),NI=Jt(["working","input_required","completed","failed","cancelled"]),Zs=O({taskId:P(),status:NI,ttl:Ae([ge(),cd()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:at(ge()),statusMessage:at(P())}),fl=Dt.extend({task:Zs}),zI=Cn.merge(Zs),Ws=En.extend({method:C("notifications/tasks/status"),params:zI}),hl=Lt.extend({method:C("tasks/get"),params:vn.extend({taskId:P()})}),gl=Dt.merge(Zs),vl=Lt.extend({method:C("tasks/result"),params:vn.extend({taskId:P()})}),m2=Dt.loose(),yl=js.extend({method:C("tasks/list")}),bl=Us.extend({tasks:he(Zs)}),xl=Lt.extend({method:C("tasks/cancel"),params:vn.extend({taskId:P()})}),a_=Dt.merge(Zs),c_=O({uri:P(),mimeType:at(P()),_meta:Ze(P(),qe()).optional()}),l_=c_.extend({text:P()}),Dp=P().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),u_=c_.extend({blob:Dp}),qs=Jt(["user","assistant"]),Ii=O({audience:he(qs).optional(),priority:ge().min(0).max(1).optional(),lastModified:od({offset:!0}).optional()}),d_=O({...Ei.shape,...Bs.shape,uri:P(),description:at(P()),mimeType:at(P()),annotations:Ii.optional(),_meta:at(Kt({}))}),RI=O({...Ei.shape,...Bs.shape,uriTemplate:P(),description:at(P()),mimeType:at(P()),annotations:Ii.optional(),_meta:at(Kt({}))}),Fp=js.extend({method:C("resources/list")}),wl=Us.extend({resources:he(d_)}),Bp=js.extend({method:C("resources/templates/list")}),Hp=Us.extend({resourceTemplates:he(RI)}),jp=vn.extend({uri:P()}),MI=jp,Up=Lt.extend({method:C("resources/read"),params:MI}),_l=Dt.extend({contents:he(Ae([l_,u_]))}),Zp=En.extend({method:C("notifications/resources/list_changed"),params:Cn.optional()}),$I=jp,OI=Lt.extend({method:C("resources/subscribe"),params:$I}),LI=jp,DI=Lt.extend({method:C("resources/unsubscribe"),params:LI}),FI=Cn.extend({uri:P()}),BI=En.extend({method:C("notifications/resources/updated"),params:FI}),HI=O({name:P(),description:at(P()),required:at(Xe())}),jI=O({...Ei.shape,...Bs.shape,description:at(P()),arguments:at(he(HI)),_meta:at(Kt({}))}),Wp=js.extend({method:C("prompts/list")}),qp=Us.extend({prompts:he(jI)}),UI=vn.extend({name:P(),arguments:Ze(P(),P()).optional()}),ZI=Lt.extend({method:C("prompts/get"),params:UI}),Gp=O({type:C("text"),text:P(),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),Vp=O({type:C("image"),data:Dp,mimeType:P(),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),Xp=O({type:C("audio"),data:Dp,mimeType:P(),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),WI=O({type:C("tool_use"),name:P(),id:P(),input:Ze(P(),qe()),_meta:Ze(P(),qe()).optional()}),Kp=O({type:C("resource"),resource:Ae([l_,u_]),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),Jp=d_.extend({type:C("resource_link")}),Pi=Ae([Gp,Vp,Xp,Jp,Kp]),qI=O({role:qs,content:Pi}),GI=Dt.extend({description:P().optional(),messages:he(qI)}),Yp=En.extend({method:C("notifications/prompts/list_changed"),params:Cn.optional()}),VI=O({title:P().optional(),readOnlyHint:Xe().optional(),destructiveHint:Xe().optional(),idempotentHint:Xe().optional(),openWorldHint:Xe().optional()}),XI=O({taskSupport:Jt(["required","optional","forbidden"]).optional()}),Sl=O({...Ei.shape,...Bs.shape,description:P().optional(),inputSchema:O({type:C("object"),properties:Ze(P(),Ot).optional(),required:he(P()).optional()}).catchall(qe()),outputSchema:O({type:C("object"),properties:Ze(P(),Ot).optional(),required:he(P()).optional()}).catchall(qe()).optional(),annotations:VI.optional(),execution:XI.optional(),_meta:Ze(P(),qe()).optional()}),kl=js.extend({method:C("tools/list")}),KI=Us.extend({tools:he(Sl)}),Pr=Dt.extend({content:he(Pi).default([]),structuredContent:Ze(P(),qe()).optional(),isError:Xe().optional()}),f2=Pr.or(Dt.extend({toolResult:qe()})),JI=Ds.extend({name:P(),arguments:Ze(P(),qe()).optional()}),Tl=Lt.extend({method:C("tools/call"),params:JI}),Qp=En.extend({method:C("notifications/tools/list_changed"),params:Cn.optional()}),h2=O({autoRefresh:Xe().default(!0),debounceMs:ge().int().nonnegative().default(300)}),p_=Jt(["debug","info","notice","warning","error","critical","alert","emergency"]),YI=vn.extend({level:p_}),QI=Lt.extend({method:C("logging/setLevel"),params:YI}),e1=Cn.extend({level:p_,logger:P().optional(),data:qe()}),em=En.extend({method:C("notifications/message"),params:e1}),t1=O({name:P().optional()}),n1=O({hints:he(t1).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),o1=O({mode:Jt(["auto","required","none"]).optional()}),r1=O({type:C("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:he(Pi).default([]),structuredContent:O({}).loose().optional(),isError:Xe().optional(),_meta:Ze(P(),qe()).optional()}),i1=ud("type",[Gp,Vp,Xp]),ul=ud("type",[Gp,Vp,Xp,WI,r1]),s1=O({role:qs,content:Ae([ul,he(ul)]),_meta:Ze(P(),qe()).optional()}),a1=Ds.extend({messages:he(s1),modelPreferences:n1.optional(),systemPrompt:P().optional(),includeContext:Jt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:he(P()).optional(),metadata:Ot.optional(),tools:he(Sl).optional(),toolChoice:o1.optional()}),c1=Lt.extend({method:C("sampling/createMessage"),params:a1}),l1=Dt.extend({model:P(),stopReason:at(Jt(["endTurn","stopSequence","maxTokens"]).or(P())),role:qs,content:i1}),u1=Dt.extend({model:P(),stopReason:at(Jt(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:qs,content:Ae([ul,he(ul)])}),d1=O({type:C("boolean"),title:P().optional(),description:P().optional(),default:Xe().optional()}),p1=O({type:C("string"),title:P().optional(),description:P().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:Jt(["email","uri","date","date-time"]).optional(),default:P().optional()}),m1=O({type:Jt(["number","integer"]),title:P().optional(),description:P().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),f1=O({type:C("string"),title:P().optional(),description:P().optional(),enum:he(P()),default:P().optional()}),h1=O({type:C("string"),title:P().optional(),description:P().optional(),oneOf:he(O({const:P(),title:P()})),default:P().optional()}),g1=O({type:C("string"),title:P().optional(),description:P().optional(),enum:he(P()),enumNames:he(P()).optional(),default:P().optional()}),v1=Ae([f1,h1]),y1=O({type:C("array"),title:P().optional(),description:P().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:O({type:C("string"),enum:he(P())}),default:he(P()).optional()}),b1=O({type:C("array"),title:P().optional(),description:P().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:O({anyOf:he(O({const:P(),title:P()}))}),default:he(P()).optional()}),x1=Ae([y1,b1]),w1=Ae([g1,v1,x1]),_1=Ae([w1,d1,p1,m1]),S1=Ds.extend({mode:C("form").optional(),message:P(),requestedSchema:O({type:C("object"),properties:Ze(P(),_1),required:he(P()).optional()})}),k1=Ds.extend({mode:C("url"),message:P(),elicitationId:P(),url:P().url()}),T1=Ae([S1,k1]),C1=Lt.extend({method:C("elicitation/create"),params:T1}),E1=Cn.extend({elicitationId:P()}),A1=En.extend({method:C("notifications/elicitation/complete"),params:E1}),I1=Dt.extend({action:Jt(["accept","decline","cancel"]),content:dd((e)=>e===null?void 0:e,Ze(P(),Ae([P(),ge(),Xe(),he(P())])).optional())}),P1=O({type:C("ref/resource"),uri:P()});var N1=O({type:C("ref/prompt"),name:P()}),z1=vn.extend({ref:Ae([N1,P1]),argument:O({name:P(),value:P()}),context:O({arguments:Ze(P(),P()).optional()}).optional()}),R1=Lt.extend({method:C("completion/complete"),params:z1});var M1=Dt.extend({completion:Kt({values:he(P()).max(100),total:at(ge().int()),hasMore:at(Xe())})}),$1=O({uri:P().startsWith("file://"),name:P().optional(),_meta:Ze(P(),qe()).optional()}),O1=Lt.extend({method:C("roots/list"),params:vn.optional()}),L1=Dt.extend({roots:he($1)}),D1=En.extend({method:C("notifications/roots/list_changed"),params:Cn.optional()}),g2=Ae([Ir,kI,R1,QI,ZI,Wp,Fp,Bp,Up,OI,DI,Tl,kl,hl,vl,yl,xl]),v2=Ae([pl,ml,EI,D1,Ws]),y2=Ae([Lp,l1,u1,I1,L1,gl,bl,fl]),b2=Ae([Ir,c1,C1,O1,hl,vl,yl,xl]),x2=Ae([pl,ml,em,BI,Zp,Qp,Yp,Ws,A1]),w2=Ae([Lp,CI,M1,GI,qp,wl,Hp,_l,Pr,KI,gl,bl,fl]);class Re 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===Ue.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new m_(o.elicitations,t)}return new Re(e,t,n)}}class m_ extends Re{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Ue.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Cl(e){return!!e._zod}function El(e,t){if(Cl(e))return is(e,t);return e.safeParse(t)}function f_(e){if(!e)return;let t;if(Cl(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 h_(e){if(Cl(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 Xo(e){return e==="completed"||e==="failed"||e==="cancelled"}var F1=Symbol("Let zodToJsonSchema decide on which parser to use");var mF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function tm(e){let n=f_(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=h_(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function nm(e,t){let n=El(e,t);if(!n.success)throw n.error;return n.data}var W1=60000;class Al{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(pl,(t)=>{this._oncancel(t)}),this.setNotificationHandler(ml,(t)=>{this._onprogress(t)}),this.setRequestHandler(Ir,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(hl,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new Re(Ue.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vl,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 p=c,d=new Re(p.error.code,p.error.message,p.error.data);u(d)}else{let p=a.type==="response"?"Response":"Error";this._onerror(Error(`${p} 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 Re(Ue.InvalidParams,`Task not found: ${r}`);if(!Xo(s.status))return await this._waitForTaskUpdate(r,n.signal),await o();if(Xo(s.status)){let a=await this._taskStore.getTaskResult(r,n.sessionId);return this._clearTaskQueue(r),{...a,_meta:{...a._meta,[Vo]:{taskId:r}}}}return await o()};return await o()}),this.setRequestHandler(yl,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 Re(Ue.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xl,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new Re(Ue.InvalidParams,`Task not found: ${t.params.taskId}`);if(Xo(o.status))throw new Re(Ue.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 Re(Ue.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...r}}catch(o){if(o instanceof Re)throw o;throw new Re(Ue.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),Re.fromError(Ue.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),Fs(r)||i_(r))this._onresponse(r);else if(Mp(r))this._onrequest(r,s);else if(r_(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=Re.fromError(Ue.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?.[Vo]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Ue.MethodNotFound,message:"Method not found"}};if(r&&this._taskMessageQueue)this._enqueueTaskMessage(r,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((p)=>this._onerror(Error(`Failed to enqueue error response: ${p}`)));else o?.send(u).catch((p)=>this._onerror(Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=t_(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 p={relatedRequestId:e.id};if(r)p.relatedTask={taskId:r};await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(s.signal.aborted)throw new Re(Ue.ConnectionClosed,"Request was cancelled");let m={...d,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,p,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 p={result:u,jsonrpc:"2.0",id:e.id};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"response",message:p,timestamp:Date.now()},o?.sessionId);else await o?.send(p)},async(u)=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Ue.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"error",message:p,timestamp:Date.now()},o?.sessionId);else await o?.send(p)}).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),Fs(e))n(e);else{let s=new Re(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(Fs(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(Fs(e))o(e);else{let s=Re.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 Re?s:new Re(Ue.InternalError,String(s))}}return}let r;try{let s=await this.request(e,fl,n);if(s.task)r=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Re(Ue.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:a},Xo(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 Re(Ue.InternalError,`Task ${r} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new Re(Ue.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 Re?s:new Re(Ue.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 p=(g)=>{u(g)};if(!this._transport){p(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(g){p(g);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};if(n?.onprogress)this._progressHandlers.set(d,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}};if(a)m.params={...m.params,task:a};if(c)m.params={...m.params,_meta:{...m.params?._meta||{},[Vo]:c}};let f=(g)=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(g)}},{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let b=g instanceof Re?g:new Re(Ue.RequestTimeout,String(g));u(b)};this._responseHandlers.set(d,(g)=>{if(n?.signal?.aborted)return;if(g instanceof Error)return u(g);try{let b=El(t,g.result);if(!b.success)u(b.error);else l(b.data)}catch(b){u(b)}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??W1,v=()=>f(Re.fromError(Ue.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let g=(b)=>{let I=this._responseHandlers.get(d);if(I)I(b);else this._onerror(Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,g),this._enqueueTaskMessage(x,{type:"request",message:m,timestamp:Date.now()}).catch((b)=>{this._cleanupTimeout(d),u(b)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((g)=>{this._cleanupTimeout(d),u(g)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},gl,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},bl,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},a_,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||{},[Vo]: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||{},[Vo]: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||{},[Vo]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let n=tm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,r)=>{let s=nm(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=tm(e);this._notificationHandlers.set(n,(o)=>{let r=nm(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"&&Mp(o.message)){let r=o.message.id,s=this._requestResolvers.get(r);if(s)s(new Re(Ue.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 Re(Ue.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new Re(Ue.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 Re(Ue.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=Ws.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Xo(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 Re(Ue.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Xo(a.status))throw new Re(Ue.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=Ws.parse({method:"notifications/tasks/status",params:c});if(await this.notification(l),Xo(c.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>n.listTasks(o,t)}}}var y_="2026-01-26";var q1="ui/notifications/tool-input-partial";var G1=Ae([C("light"),C("dark")]).describe("Color theme preference for the host environment."),Vs=Ae([C("inline"),C("fullscreen"),C("pip")]).describe("Display mode for UI presentation."),V1=Ae([C("--color-background-primary"),C("--color-background-secondary"),C("--color-background-tertiary"),C("--color-background-inverse"),C("--color-background-ghost"),C("--color-background-info"),C("--color-background-danger"),C("--color-background-success"),C("--color-background-warning"),C("--color-background-disabled"),C("--color-text-primary"),C("--color-text-secondary"),C("--color-text-tertiary"),C("--color-text-inverse"),C("--color-text-ghost"),C("--color-text-info"),C("--color-text-danger"),C("--color-text-success"),C("--color-text-warning"),C("--color-text-disabled"),C("--color-border-primary"),C("--color-border-secondary"),C("--color-border-tertiary"),C("--color-border-inverse"),C("--color-border-ghost"),C("--color-border-info"),C("--color-border-danger"),C("--color-border-success"),C("--color-border-warning"),C("--color-border-disabled"),C("--color-ring-primary"),C("--color-ring-secondary"),C("--color-ring-inverse"),C("--color-ring-info"),C("--color-ring-danger"),C("--color-ring-success"),C("--color-ring-warning"),C("--font-sans"),C("--font-mono"),C("--font-weight-normal"),C("--font-weight-medium"),C("--font-weight-semibold"),C("--font-weight-bold"),C("--font-text-xs-size"),C("--font-text-sm-size"),C("--font-text-md-size"),C("--font-text-lg-size"),C("--font-heading-xs-size"),C("--font-heading-sm-size"),C("--font-heading-md-size"),C("--font-heading-lg-size"),C("--font-heading-xl-size"),C("--font-heading-2xl-size"),C("--font-heading-3xl-size"),C("--font-text-xs-line-height"),C("--font-text-sm-line-height"),C("--font-text-md-line-height"),C("--font-text-lg-line-height"),C("--font-heading-xs-line-height"),C("--font-heading-sm-line-height"),C("--font-heading-md-line-height"),C("--font-heading-lg-line-height"),C("--font-heading-xl-line-height"),C("--font-heading-2xl-line-height"),C("--font-heading-3xl-line-height"),C("--border-radius-xs"),C("--border-radius-sm"),C("--border-radius-md"),C("--border-radius-lg"),C("--border-radius-xl"),C("--border-radius-full"),C("--border-width-regular"),C("--shadow-hairline"),C("--shadow-sm"),C("--shadow-md"),C("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),X1=Ze(V1.describe(`Style variables for theming MCP apps.
167
+ `+st;if(bn)st=ma(st);return N&&ln?J(st):st},t.setConfig=function(){let V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};cu(V),Gi=!0,to=Z,_o=T},t.clearConfig=function(){Zr=null,Gi=!1,to=null,_o=null,N=k,w=""},t.isValidAttribute=function(V,y,E){if(!Zr)cu({});let U=it(V),te=it(y);return of(U,te,E)},t.addHook=function(V,y){if(typeof y!=="function")return;if(!Et(Me,V))return;vi(Me[V],y)},t.removeHook=function(V,y){if(!Et(Me,V))return;if(y!==void 0){let E=EA(Me[V],y);return E===-1?void 0:AA(Me[V],E,1)[0]}return gw(Me[V])},t.removeHooks=function(V){if(!Et(Me,V))return;Me[V]=[]},t.removeAllHooks=function(){Me=Aw()},t}var zw=Nw();function Qn(e){return zw.sanitize(e,{FORBID_TAGS:["form","svg","math"]})}var vp=null;function JA(){if(vp)return vp;let e=new Is({headingStyle:"atx",codeBlockStyle:"fenced",emDelimiter:"*",bulletListMarker:"-"});return e.use(Rw.gfm),vp=e,e}function Mw({initialHtml:e,className:t,onChange:n,onSave:o}){let r=L(null),s=L(e);H(()=>{let m=r.current;if(!m)return;m.innerHTML=Qn(s.current);for(let f of m.querySelectorAll('input[type="checkbox"][disabled]'))f.removeAttribute("disabled")},[]);let a=j(()=>{let m=r.current;if(!m)return"";return JA().turndown(m.innerHTML)},[]),c=j(()=>{n(a())},[n,a]),l=j(()=>{let m=r.current;if(!m||!m.isConnected||m.innerHTML==="")return;o?.(a())},[o,a]),u=j((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(),Wc(),c()},[c,l]),p=j((m)=>{let f=m.target;if(f instanceof HTMLInputElement&&f.type==="checkbox")f.toggleAttribute("checked",f.checked),c()},[c]),d=j((m)=>{let f=m.clipboardData?.getData("text/plain");if(f==null)return;m.preventDefault(),document.execCommand("insertText",!1,f),c()},[c]);return i(_e,{children:[i("div",{ref:r,class:t,contentEditable:!0,spellcheck:!1,onInput:c,onKeyDown:u,onPaste:d,onClick:p,onBlur:l},void 0,!1,void 0,this),i(mw,{hostRef:r,onChange:c},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yp({html:e,className:t,style:n,onTaskToggle:o}){let r=L(null),s=L(o);return s.current=o,H(()=>{let c=r.current;if(!c)return;if(c.replaceChildren(),!e)return;let l=document.createElement("template");if(l.innerHTML=Qn(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 p=c.target,d=null;if(p instanceof HTMLInputElement&&p.type==="checkbox")d=p;else{let h=p.closest("li")?.querySelector(':scope > input[type="checkbox"]');if(h&&c.clientX<=h.getBoundingClientRect().right+6)d=h}if(!d)return;c.stopPropagation();let m=[...u.querySelectorAll('input[type="checkbox"]')].indexOf(d);if(m>=0)l(m)}:void 0},void 0,!1,void 0,this)}function YA(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 Vc({node:e,expanded:t=!1}){let n=dc(),o=e.data.path,[r,s]=A(""),[a,c]=A(""),[l,u]=A(!1),[p,d]=A(!1),[m,f]=A(!1),[h,v]=A(!1),x=L(null),g=L(null),b=L(""),I=L(null),R=L(!1),M=L({boardId:Oe.value,revision:e.contentRevision??0}),_=L(Promise.resolve()),N=e.data.reviewActive;H(()=>{if(Se()&&R.current)return;M.current={boardId:Oe.value,revision:e.contentRevision??0};let S=!1;return(async()=>{let q;if(o){let ye=await vs(o);if(S)return;q=ye.content}else if(e.data.content)q=e.data.content;else{u(!0);return}s(q);let ie=await Vn(q);if(S||Se()&&R.current)return;c(ie),u(!0),fe(e.id,{content:q,rendered:ie})})(),()=>{S=!0}},[o,e.id,e.data.content]);let w=j(async(S)=>{let q=S.target.value;R.current=!0,b.current=q,s(q),v(!0);let ie=await Vn(q);c(ie)},[]),k=j(async(S)=>{if(Se()){_.current=_.current.then(async()=>{f(!0);let ie=await kt(e.id,{content:S,expectedBoardId:M.current.boardId,expectedContentRevision:M.current.revision});if(f(!1),!ie.ok)return;M.current.revision=ie.contentRevision??M.current.revision;let ye=F.value.get(e.id);if(ye)F.value=new Map(F.value).set(e.id,{...ye,contentRevision:M.current.revision});if(b.current!==S)return;R.current=!1,v(!1);let ue=await Vn(S);c(ue),fe(e.id,{content:S,rendered:ue})}),await _.current;return}if(!o){let ie=await Vn(S);c(ie),v(!1),fe(e.id,{content:S,rendered:ie}),await kt(e.id,{content:S,data:{rendered:ie}});return}f(!0);let q=await mb(o,S);if(f(!1),q.ok){let ie=await Vn(S);c(ie),v(!1),fe(e.id,{content:S,rendered:ie,savedAt:q.updatedAt}),await kt(e.id,{content:S,data:{rendered:ie,savedAt:q.updatedAt}})}},[o,e.id]),z=j(async()=>{if(!h)return;await k(r)},[h,r,k]),X=j((S)=>{if((S.metaKey||S.ctrlKey)&&S.key==="s"){S.preventDefault(),z();return}let q=x.current;if(q&&$x(S,q))return;if(q&&S.key==="Tab")S.preventDefault(),Mx(q,S.shiftKey)},[z]);I.current=k;let W=j((S)=>{if(R.current=!0,s(S),v(!0),b.current=S,g.current!==null)window.clearTimeout(g.current);g.current=window.setTimeout(()=>{g.current=null,k(S)},800)},[k]),J=j((S)=>{if(R.current=!0,s(S),b.current=S,g.current!==null)window.clearTimeout(g.current),g.current=null;k(S)},[k]);H(()=>()=>{if(g.current===null)return;window.clearTimeout(g.current),g.current=null;let S=I.current;if(S)S(b.current)},[e.id]);let G=N?i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-ok) 10%, transparent)",color:"var(--c-ok)",borderBottom:"1px solid color-mix(in srgb, var(--c-ok) 20%, transparent)",textTransform:"uppercase",letterSpacing:"0.05em",fontWeight:600},children:"Review active"},void 0,!1,void 0,this):null;if(p&&t)return i("div",{class:"md-editor-expanded",onKeyDown:X,children:[i("div",{class:"md-editor-toolbar",children:[i("button",{type:"button",class:"md-toolbar-btn",onClick:()=>d(!1),children:[i(sx,{size:14},void 0,!1,void 0,this)," Back to document"]},void 0,!0,void 0,this),i("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[o&&i("span",{class:"md-toolbar-path",children:o.split("/").pop()},void 0,!1,void 0,this),i("button",{type:"button",class:`md-toolbar-btn${h?" md-toolbar-btn-primary":""}`,onClick:z,disabled:!h||m,children:m?"Saving…":h?"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:x,value:r,onInput:w,spellcheck:!1},void 0,!1,void 0,this),i(Jd,{textareaRef:x},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(yp,{html:a,className:"md-preview"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(p)return i("div",{class:"md-editor-split",style:{height:"100%"},onKeyDown:X,children:[i("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[i("textarea",{ref:x,value:r,onInput:w,spellcheck:!1},void 0,!1,void 0,this),i(Jd,{textareaRef:x},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(yp,{html:a,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:z,disabled:!h||m,style:{padding:"4px 10px",fontSize:"11px",background:h?"color-mix(in srgb, var(--c-accent) 25%, transparent)":"var(--c-input-bg)",border:`1px solid ${h?"var(--c-accent)":"var(--c-line)"}`,borderRadius:"6px",color:h?"var(--c-text)":"var(--c-dim)",cursor:h?"pointer":"default"},children:m?"Saving…":h?"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:[G,i("div",{class:"md-reader",children:l?i(Mw,{initialHtml:a||"<p><br></p>",className:"md-reader-content md-reader-editable",onChange:W,onSave:J},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",{class:"md-card-preview",children:[i("div",{class:"md-card-content",children:[G,i(yp,{html:a,style:{padding:a?"0":"12px",color:a?void 0:"var(--c-dim)"},onTaskToggle:(S)=>{let q=YA(r,S);if(q!==r)J(q)}},void 0,!1,void 0,this),!l&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Loading…"},void 0,!1,void 0,this),l&&!a&&i("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Empty node"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.data.source&&typeof e.data.source==="object"&&"attachmentId"in e.data.source&&i("div",{class:"md-import-source",children:["Source material ·"," ",i("a",{href:`/api/canvas/attachments/${encodeURIComponent(String(e.data.source.attachmentId))}/bytes`,target:"_blank",rel:"noopener noreferrer",children:String(e.data.source.filename??"Original")},void 0,!1,void 0,this)," · ",String(e.data.source.reference??"Location not supplied")]},void 0,!0,void 0,this),i("div",{class:"md-card-actions",children:[n&&i("button",{type:"button",class:"md-readme-btn","aria-pressed":n.readmeNodeId===e.id,onClick:()=>void ub(n.id,n.readmeNodeId===e.id?null:e.id),children:n.readmeNodeId===e.id?"README":"Set as README"},void 0,!1,void 0,this),i("button",{type:"button",class:"md-card-edit",onClick:()=>kn(e.id),children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Xc="pmx-canvas-ax",Kc="pmx-canvas-ax-ack",Tn="pmx-canvas-html-node",bp="pmx-canvas-json-state",Jc="pmx-canvas-ext-app-alive",xp="pmx-canvas-ext-app-paint-probe";function $w(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 wp="allow-scripts allow-popups allow-popups-to-escape-sandbox";function bi(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 Rs(e,t={}){let n=new URLSearchParams;if(n.set("theme",t.theme??gt.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 Yc(e){return $w(e.type,e.data)}async function Qc(e){if(Se()){on("context","Open in focus mode","This surface has no public URL. Use Expand to view it here, or export the board to download it.");return}let t=Rs(e.id);if(!(await bb(e.id,t)).opened)window.open(t,"_blank","noopener")}var Ow=30000;var _p=80;var lt=K(new Map),wi=K(null),QA=480,eI=320,tI=650,Ms=new Map,xi=new Map,el=new Map,vo=null;function Sp(e){lt.value=e,nI()}function kp(e){let t=Ms.get(e);if(t)clearTimeout(t),Ms.delete(e)}function Tp(e){let t=xi.get(e);if(t)clearTimeout(t),xi.delete(e)}function Dw(e){if(kp(e.id),Tp(e.id),!lt.value.has(e.id))el.set(e.id,Date.now());let t=new Map(lt.value);t.set(e.id,{...e,phase:"forming"}),Sp(t)}function Er(e){if(kp(e),Tp(e),el.delete(e),!lt.value.has(e))return;let t=new Map(lt.value);t.delete(e),Sp(t)}function Lw(e,t,n,o){let r=lt.value.get(e);if(!r||r.phase===t)return;let s=new Map(lt.value);s.set(e,{...r,phase:t,...o?{settledNodeId:o}:{}}),Sp(s),kp(e),Ms.set(e,setTimeout(()=>Er(e),n+1500))}function Fw(e,t,n,o){Tp(e);let r=Date.now()-(el.get(e)??0),s=Math.max(0,tI-r);if(s===0){Lw(e,t,n,o);return}xi.set(e,setTimeout(()=>{xi.delete(e),Lw(e,t,n,o)},s))}function Bw(e,t){Fw(e,"settling",QA,t)}function Cp(e){Fw(e,"dissolving",eI)}function tl(){for(let e of Ms.values())clearTimeout(e);Ms.clear();for(let e of xi.values())clearTimeout(e);if(xi.clear(),el.clear(),vo)clearInterval(vo),vo=null;wi.value=null,lt.value=new Map}function nI(){if(vo||lt.value.size===0)return;vo=setInterval(()=>{let e=Date.now();for(let t of lt.value.values())if(t.phase==="forming"&&t.expiresAt<=e)Cp(t.id);if(lt.value.size===0&&vo)clearInterval(vo),vo=null},1000),vo.unref?.()}function oI(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 rl=oI("pmx-canvas-human-client",()=>`tab-${Math.random().toString(36).slice(2,8)}`);function rI(){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-${rl.slice(-4)}`}var jw=K(rI()),Uw=K([]),Os=Ge(()=>Uw.value.filter((e)=>e.clientId!==rl)),Ar=K(new Map);function Ep(e){if(!e||!Array.isArray(e.humans))return;Uw.value=e.humans}var _i=K(null),il=null,Zw=0,$s=null;function ol(e){if(Se())return;$n("humanPresence","/api/canvas/human-presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:rl,name:jw.value,...e})})}function Hw(){$s=null,Zw=Date.now(),ol({cursor:il,grabbingNodeId:_i.value})}function sl(e){il=e;let t=Date.now()-Zw;if(t>=_p){if($s)clearTimeout($s);Hw()}else if(!$s)$s=setTimeout(Hw,_p-t)}function Ap(e){_i.value=e,ol({cursor:il,grabbingNodeId:e})}function iI(e,t){let n=new Map(Ar.value);n.set(e,t),Ar.value=n,setTimeout(()=>{let o=new Map(Ar.value);if(o.get(e)===t)o.delete(e),Ar.value=o},6000)}function Ww(e,t){let n=[...lt.value.values()].filter((r)=>r.nodeId===e&&!r.auto&&r.phase==="forming");if(n.length===0)return;let o=jw.value;iI(e,o);for(let r of n)br({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)Er(r.id)});$n("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 nl=null;function qw(){ol({cursor:il,grabbingNodeId:_i.value}),nl=setInterval(()=>ol({grabbingNodeId:_i.value}),3000);let e=()=>{try{navigator.sendBeacon?.("/api/canvas/human-presence",new Blob([JSON.stringify({clientId:rl,left:!0})],{type:"application/json"}))}catch{}};return window.addEventListener("pagehide",e),()=>{if(nl)clearInterval(nl);nl=null,window.removeEventListener("pagehide",e)}}var sI={markdown:{width:360,height:180},board:{width:320,height:140},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 Gw(e){return sI[e]}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 aI(e,t,n,o,r){return o.some((s)=>Vw(e,t,n,s,r))}function al(e,t,n,o,r){return o.find((s)=>Vw(e,t,n,s,r))}function cl(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(!aI(s,t,n,e,o))return s;let a=40,c=80,l=3000,u=c;for(let d=0;d<20;d++){let m=a;while(m+t<l){let v=al({x:m,y:u},t,n,e,o);if(!v)return{x:m,y:u};m=v.position.x+v.size.width+o}u=e.filter((v)=>v.position.y<=u+n+o&&v.position.y+v.size.height+o>u).reduce((v,x)=>Math.max(v,x.position.y+x.size.height),u)+o}let p=e.reduce((d,m)=>Math.max(d,m.position.y+m.size.height),0);return{x:a,y:p+o}}var Si=37,cI=600,lI=1400,uI=24;function dI(e){return e.type==="html"||e.type==="mermaid"||e.type==="json-render"||e.type==="graph"||e.type==="mcp-app"||e.type==="webpage"}function pI(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 Xw(e){return e.collapsed===!0||e.data.strictSize===!0||e.data.userResized===!0||e.type==="group"}function Ip(e){return!Xw(e)&&!dI(e)}function Kw(e,t){if(!Ip(e)||t<=0)return null;let n=Math.min(t+Si,cI),o=Gw(e.type);return o?Math.max(n,o.height):n}function Pp(e){return pI(e)&&!Xw(e)}function Jw(e,t){if(!Pp(e)||!Number.isFinite(t)||t<=0)return null;let n=Math.min(t+Si+uI,lI);return n>e.size.height+8?n:null}function Yw(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=al(r,e.size.width,t,o,24);while(s)r.y=s.position.y+s.size.height+24,s=al(r,e.size.width,t,o,24);return r}function ki(e,t,n){H(()=>{if(!n)return;let o=null,r=null,s=()=>_i.value===e.id||Os.value.some((p)=>p.grabbingNodeId===e.id);function a(){if(o=null,s()||r===null)return;let p=r;r=null;let d=F.value.get(e.id);if(!d)return;let m=Jw(d,p);if(m===null)return;let f=Yw(d,m,Array.from(F.value.values())),h=f.x!==d.position.x||f.y!==d.position.y,v={size:{width:d.size.width,height:m},...h?{position:f}:{}};wt(d.id,v),hc([{id:d.id,...v}],{recordHistory:h})}function c(){if(o!==null)clearTimeout(o);o=r!==null&&!s()?setTimeout(a,300):null}let l=nn(()=>{s(),c()});function u(p){if(p.source!==t.current?.contentWindow)return;let d=p.data;if(!d||d.source!=="pmx-canvas-frame"||d.type!=="content-height"||d.token!==n)return;if(typeof d.height!=="number"||!Number.isFinite(d.height)||d.height<=0)return;r=d.height,c()}return window.addEventListener("message",u),()=>{if(window.removeEventListener("message",u),l(),o!==null)clearTimeout(o)}},[e.id,n])}function mI(e){if(Se())return e.startsWith("/")&&!e.startsWith("//");try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Ti(e){let t=Rt.value,[n,o]=A(null),r=Boolean(e)&&mI(e),s=t==="srcdoc"&&r;if(H(()=>{if(!s)return;let a=!1;return ct(`${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 ll({node:e,expanded:t=!1}){let n=L(null),o=gt.value,r=Be(()=>`theme-${crypto.randomUUID()}`,[]),s=Be(()=>`frame-${crypto.randomUUID()}`,[]),a=typeof e.data.content==="string"?e.data.content:"",c=e.data.fit==="none"?"none":"contain",l=Be(()=>bi(`${c}:${a}`),[a,c]),u=Be(()=>a?Rs(e.id,{theme:o,themeToken:r,v:l,frameToken:s}):"",[a,r,l,e.id,s]),p=Ti(u);ki(e,n,t?"":s);let d=()=>{n.current?.contentWindow?.postMessage({source:Tn,type:"theme-update",token:r,theme:o},"*")};if(H(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",...p,onLoad:d,style:{width:"100%",height:"100%",minHeight:t?"70vh":"0",border:"none",background:"var(--c-bg)",borderRadius:"6px",display:"block"}},void 0,!1,void 0,this)}var Np=["harbor","daylight","high-contrast","midnight","sepia","arctic","ember","forest","volt"];function Ls(e){return typeof e==="string"&&Np.includes(e)}function zp(e,t="harbor"){return Ls(e)?e:t}var Ci={harbor:{label:"Harbor",scheme:"dark",swatchBg:"#081524",swatchAccent:"#4BBCFF"},daylight:{label:"Daylight",scheme:"light",swatchBg:"#F6F7F9",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 Go(e){return Ci[zp(e)].scheme}var Vo="io.modelcontextprotocol/related-task",dl="2.0",Ot=Ey((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),Qw=Ae([P(),ge().int()]),e_=P(),p2=Kt({ttl:Ae([ge(),cd()]).optional(),pollInterval:ge().optional()}),fI=O({ttl:ge().optional()}),hI=O({taskId:P()}),Rp=Kt({progressToken:Qw.optional(),[Vo]:hI.optional()}),vn=O({_meta:Rp.optional()}),Ds=vn.extend({task:fI.optional()}),t_=(e)=>Ds.safeParse(e).success,Lt=O({method:P(),params:vn.loose().optional()}),Cn=O({_meta:Rp.optional()}),En=O({method:P(),params:Cn.loose().optional()}),Dt=Kt({_meta:Rp.optional()}),Ai=Ae([P(),ge().int()]),n_=O({jsonrpc:C(dl),id:Ai,...Lt.shape}).strict(),Mp=(e)=>n_.safeParse(e).success,o_=O({jsonrpc:C(dl),...En.shape}).strict(),r_=(e)=>o_.safeParse(e).success,$p=O({jsonrpc:C(dl),id:Ai,result:Dt}).strict(),Fs=(e)=>$p.safeParse(e).success;var Ue;(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"})(Ue||(Ue={}));var Op=O({jsonrpc:C(dl),id:Ai.optional(),error:O({code:ge().int(),message:P(),data:qe().optional()})}).strict();var i_=(e)=>Op.safeParse(e).success;var s_=Ae([n_,o_,$p,Op]),m2=Ae([$p,Op]),Lp=Dt.strict(),gI=Cn.extend({requestId:Ai.optional(),reason:P().optional()}),pl=En.extend({method:C("notifications/cancelled"),params:gI}),vI=O({src:P(),mimeType:P().optional(),sizes:he(P()).optional(),theme:Jt(["light","dark"]).optional()}),Bs=O({icons:he(vI).optional()}),Ei=O({name:P(),title:P().optional()}),Hs=Ei.extend({...Ei.shape,...Bs.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),yI=Wa(O({applyDefaults:Xe().optional()}),Ze(P(),qe())),bI=dd((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Wa(O({form:yI.optional(),url:Ot.optional()}),Ze(P(),qe()).optional())),xI=Kt({list:Ot.optional(),cancel:Ot.optional(),requests:Kt({sampling:Kt({createMessage:Ot.optional()}).optional(),elicitation:Kt({create:Ot.optional()}).optional()}).optional()}),wI=Kt({list:Ot.optional(),cancel:Ot.optional(),requests:Kt({tools:Kt({call:Ot.optional()}).optional()}).optional()}),_I=O({experimental:Ze(P(),Ot).optional(),sampling:O({context:Ot.optional(),tools:Ot.optional()}).optional(),elicitation:bI.optional(),roots:O({listChanged:Xe().optional()}).optional(),tasks:xI.optional()}),SI=vn.extend({protocolVersion:P(),capabilities:_I,clientInfo:Hs}),kI=Lt.extend({method:C("initialize"),params:SI});var TI=O({experimental:Ze(P(),Ot).optional(),logging:Ot.optional(),completions:Ot.optional(),prompts:O({listChanged:Xe().optional()}).optional(),resources:O({subscribe:Xe().optional(),listChanged:Xe().optional()}).optional(),tools:O({listChanged:Xe().optional()}).optional(),tasks:wI.optional()}),CI=Dt.extend({protocolVersion:P(),capabilities:TI,serverInfo:Hs,instructions:P().optional()}),EI=En.extend({method:C("notifications/initialized"),params:Cn.optional()});var Ir=Lt.extend({method:C("ping"),params:vn.optional()}),AI=O({progress:ge(),total:at(ge()),message:at(P())}),II=O({...Cn.shape,...AI.shape,progressToken:Qw}),ml=En.extend({method:C("notifications/progress"),params:II}),PI=vn.extend({cursor:e_.optional()}),js=Lt.extend({params:PI.optional()}),Us=Dt.extend({nextCursor:e_.optional()}),NI=Jt(["working","input_required","completed","failed","cancelled"]),Zs=O({taskId:P(),status:NI,ttl:Ae([ge(),cd()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:at(ge()),statusMessage:at(P())}),fl=Dt.extend({task:Zs}),zI=Cn.merge(Zs),Ws=En.extend({method:C("notifications/tasks/status"),params:zI}),hl=Lt.extend({method:C("tasks/get"),params:vn.extend({taskId:P()})}),gl=Dt.merge(Zs),vl=Lt.extend({method:C("tasks/result"),params:vn.extend({taskId:P()})}),f2=Dt.loose(),yl=js.extend({method:C("tasks/list")}),bl=Us.extend({tasks:he(Zs)}),xl=Lt.extend({method:C("tasks/cancel"),params:vn.extend({taskId:P()})}),a_=Dt.merge(Zs),c_=O({uri:P(),mimeType:at(P()),_meta:Ze(P(),qe()).optional()}),l_=c_.extend({text:P()}),Dp=P().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),u_=c_.extend({blob:Dp}),qs=Jt(["user","assistant"]),Ii=O({audience:he(qs).optional(),priority:ge().min(0).max(1).optional(),lastModified:od({offset:!0}).optional()}),d_=O({...Ei.shape,...Bs.shape,uri:P(),description:at(P()),mimeType:at(P()),annotations:Ii.optional(),_meta:at(Kt({}))}),RI=O({...Ei.shape,...Bs.shape,uriTemplate:P(),description:at(P()),mimeType:at(P()),annotations:Ii.optional(),_meta:at(Kt({}))}),Fp=js.extend({method:C("resources/list")}),wl=Us.extend({resources:he(d_)}),Bp=js.extend({method:C("resources/templates/list")}),Hp=Us.extend({resourceTemplates:he(RI)}),jp=vn.extend({uri:P()}),MI=jp,Up=Lt.extend({method:C("resources/read"),params:MI}),_l=Dt.extend({contents:he(Ae([l_,u_]))}),Zp=En.extend({method:C("notifications/resources/list_changed"),params:Cn.optional()}),$I=jp,OI=Lt.extend({method:C("resources/subscribe"),params:$I}),LI=jp,DI=Lt.extend({method:C("resources/unsubscribe"),params:LI}),FI=Cn.extend({uri:P()}),BI=En.extend({method:C("notifications/resources/updated"),params:FI}),HI=O({name:P(),description:at(P()),required:at(Xe())}),jI=O({...Ei.shape,...Bs.shape,description:at(P()),arguments:at(he(HI)),_meta:at(Kt({}))}),Wp=js.extend({method:C("prompts/list")}),qp=Us.extend({prompts:he(jI)}),UI=vn.extend({name:P(),arguments:Ze(P(),P()).optional()}),ZI=Lt.extend({method:C("prompts/get"),params:UI}),Gp=O({type:C("text"),text:P(),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),Vp=O({type:C("image"),data:Dp,mimeType:P(),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),Xp=O({type:C("audio"),data:Dp,mimeType:P(),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),WI=O({type:C("tool_use"),name:P(),id:P(),input:Ze(P(),qe()),_meta:Ze(P(),qe()).optional()}),Kp=O({type:C("resource"),resource:Ae([l_,u_]),annotations:Ii.optional(),_meta:Ze(P(),qe()).optional()}),Jp=d_.extend({type:C("resource_link")}),Pi=Ae([Gp,Vp,Xp,Jp,Kp]),qI=O({role:qs,content:Pi}),GI=Dt.extend({description:P().optional(),messages:he(qI)}),Yp=En.extend({method:C("notifications/prompts/list_changed"),params:Cn.optional()}),VI=O({title:P().optional(),readOnlyHint:Xe().optional(),destructiveHint:Xe().optional(),idempotentHint:Xe().optional(),openWorldHint:Xe().optional()}),XI=O({taskSupport:Jt(["required","optional","forbidden"]).optional()}),Sl=O({...Ei.shape,...Bs.shape,description:P().optional(),inputSchema:O({type:C("object"),properties:Ze(P(),Ot).optional(),required:he(P()).optional()}).catchall(qe()),outputSchema:O({type:C("object"),properties:Ze(P(),Ot).optional(),required:he(P()).optional()}).catchall(qe()).optional(),annotations:VI.optional(),execution:XI.optional(),_meta:Ze(P(),qe()).optional()}),kl=js.extend({method:C("tools/list")}),KI=Us.extend({tools:he(Sl)}),Pr=Dt.extend({content:he(Pi).default([]),structuredContent:Ze(P(),qe()).optional(),isError:Xe().optional()}),h2=Pr.or(Dt.extend({toolResult:qe()})),JI=Ds.extend({name:P(),arguments:Ze(P(),qe()).optional()}),Tl=Lt.extend({method:C("tools/call"),params:JI}),Qp=En.extend({method:C("notifications/tools/list_changed"),params:Cn.optional()}),g2=O({autoRefresh:Xe().default(!0),debounceMs:ge().int().nonnegative().default(300)}),p_=Jt(["debug","info","notice","warning","error","critical","alert","emergency"]),YI=vn.extend({level:p_}),QI=Lt.extend({method:C("logging/setLevel"),params:YI}),e1=Cn.extend({level:p_,logger:P().optional(),data:qe()}),em=En.extend({method:C("notifications/message"),params:e1}),t1=O({name:P().optional()}),n1=O({hints:he(t1).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),o1=O({mode:Jt(["auto","required","none"]).optional()}),r1=O({type:C("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:he(Pi).default([]),structuredContent:O({}).loose().optional(),isError:Xe().optional(),_meta:Ze(P(),qe()).optional()}),i1=ud("type",[Gp,Vp,Xp]),ul=ud("type",[Gp,Vp,Xp,WI,r1]),s1=O({role:qs,content:Ae([ul,he(ul)]),_meta:Ze(P(),qe()).optional()}),a1=Ds.extend({messages:he(s1),modelPreferences:n1.optional(),systemPrompt:P().optional(),includeContext:Jt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:he(P()).optional(),metadata:Ot.optional(),tools:he(Sl).optional(),toolChoice:o1.optional()}),c1=Lt.extend({method:C("sampling/createMessage"),params:a1}),l1=Dt.extend({model:P(),stopReason:at(Jt(["endTurn","stopSequence","maxTokens"]).or(P())),role:qs,content:i1}),u1=Dt.extend({model:P(),stopReason:at(Jt(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:qs,content:Ae([ul,he(ul)])}),d1=O({type:C("boolean"),title:P().optional(),description:P().optional(),default:Xe().optional()}),p1=O({type:C("string"),title:P().optional(),description:P().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:Jt(["email","uri","date","date-time"]).optional(),default:P().optional()}),m1=O({type:Jt(["number","integer"]),title:P().optional(),description:P().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),f1=O({type:C("string"),title:P().optional(),description:P().optional(),enum:he(P()),default:P().optional()}),h1=O({type:C("string"),title:P().optional(),description:P().optional(),oneOf:he(O({const:P(),title:P()})),default:P().optional()}),g1=O({type:C("string"),title:P().optional(),description:P().optional(),enum:he(P()),enumNames:he(P()).optional(),default:P().optional()}),v1=Ae([f1,h1]),y1=O({type:C("array"),title:P().optional(),description:P().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:O({type:C("string"),enum:he(P())}),default:he(P()).optional()}),b1=O({type:C("array"),title:P().optional(),description:P().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:O({anyOf:he(O({const:P(),title:P()}))}),default:he(P()).optional()}),x1=Ae([y1,b1]),w1=Ae([g1,v1,x1]),_1=Ae([w1,d1,p1,m1]),S1=Ds.extend({mode:C("form").optional(),message:P(),requestedSchema:O({type:C("object"),properties:Ze(P(),_1),required:he(P()).optional()})}),k1=Ds.extend({mode:C("url"),message:P(),elicitationId:P(),url:P().url()}),T1=Ae([S1,k1]),C1=Lt.extend({method:C("elicitation/create"),params:T1}),E1=Cn.extend({elicitationId:P()}),A1=En.extend({method:C("notifications/elicitation/complete"),params:E1}),I1=Dt.extend({action:Jt(["accept","decline","cancel"]),content:dd((e)=>e===null?void 0:e,Ze(P(),Ae([P(),ge(),Xe(),he(P())])).optional())}),P1=O({type:C("ref/resource"),uri:P()});var N1=O({type:C("ref/prompt"),name:P()}),z1=vn.extend({ref:Ae([N1,P1]),argument:O({name:P(),value:P()}),context:O({arguments:Ze(P(),P()).optional()}).optional()}),R1=Lt.extend({method:C("completion/complete"),params:z1});var M1=Dt.extend({completion:Kt({values:he(P()).max(100),total:at(ge().int()),hasMore:at(Xe())})}),$1=O({uri:P().startsWith("file://"),name:P().optional(),_meta:Ze(P(),qe()).optional()}),O1=Lt.extend({method:C("roots/list"),params:vn.optional()}),L1=Dt.extend({roots:he($1)}),D1=En.extend({method:C("notifications/roots/list_changed"),params:Cn.optional()}),v2=Ae([Ir,kI,R1,QI,ZI,Wp,Fp,Bp,Up,OI,DI,Tl,kl,hl,vl,yl,xl]),y2=Ae([pl,ml,EI,D1,Ws]),b2=Ae([Lp,l1,u1,I1,L1,gl,bl,fl]),x2=Ae([Ir,c1,C1,O1,hl,vl,yl,xl]),w2=Ae([pl,ml,em,BI,Zp,Qp,Yp,Ws,A1]),_2=Ae([Lp,CI,M1,GI,qp,wl,Hp,_l,Pr,KI,gl,bl,fl]);class Re 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===Ue.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new m_(o.elicitations,t)}return new Re(e,t,n)}}class m_ extends Re{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Ue.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Cl(e){return!!e._zod}function El(e,t){if(Cl(e))return is(e,t);return e.safeParse(t)}function f_(e){if(!e)return;let t;if(Cl(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 h_(e){if(Cl(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 Xo(e){return e==="completed"||e==="failed"||e==="cancelled"}var F1=Symbol("Let zodToJsonSchema decide on which parser to use");var fF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function tm(e){let n=f_(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=h_(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function nm(e,t){let n=El(e,t);if(!n.success)throw n.error;return n.data}var W1=60000;class Al{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(pl,(t)=>{this._oncancel(t)}),this.setNotificationHandler(ml,(t)=>{this._onprogress(t)}),this.setRequestHandler(Ir,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(hl,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new Re(Ue.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vl,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 p=c,d=new Re(p.error.code,p.error.message,p.error.data);u(d)}else{let p=a.type==="response"?"Response":"Error";this._onerror(Error(`${p} 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 Re(Ue.InvalidParams,`Task not found: ${r}`);if(!Xo(s.status))return await this._waitForTaskUpdate(r,n.signal),await o();if(Xo(s.status)){let a=await this._taskStore.getTaskResult(r,n.sessionId);return this._clearTaskQueue(r),{...a,_meta:{...a._meta,[Vo]:{taskId:r}}}}return await o()};return await o()}),this.setRequestHandler(yl,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 Re(Ue.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xl,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new Re(Ue.InvalidParams,`Task not found: ${t.params.taskId}`);if(Xo(o.status))throw new Re(Ue.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 Re(Ue.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...r}}catch(o){if(o instanceof Re)throw o;throw new Re(Ue.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),Re.fromError(Ue.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),Fs(r)||i_(r))this._onresponse(r);else if(Mp(r))this._onrequest(r,s);else if(r_(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=Re.fromError(Ue.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?.[Vo]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Ue.MethodNotFound,message:"Method not found"}};if(r&&this._taskMessageQueue)this._enqueueTaskMessage(r,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((p)=>this._onerror(Error(`Failed to enqueue error response: ${p}`)));else o?.send(u).catch((p)=>this._onerror(Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=t_(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 p={relatedRequestId:e.id};if(r)p.relatedTask={taskId:r};await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(s.signal.aborted)throw new Re(Ue.ConnectionClosed,"Request was cancelled");let m={...d,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,p,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 p={result:u,jsonrpc:"2.0",id:e.id};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"response",message:p,timestamp:Date.now()},o?.sessionId);else await o?.send(p)},async(u)=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Ue.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(r&&this._taskMessageQueue)await this._enqueueTaskMessage(r,{type:"error",message:p,timestamp:Date.now()},o?.sessionId);else await o?.send(p)}).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),Fs(e))n(e);else{let s=new Re(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(Fs(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(Fs(e))o(e);else{let s=Re.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 Re?s:new Re(Ue.InternalError,String(s))}}return}let r;try{let s=await this.request(e,fl,n);if(s.task)r=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Re(Ue.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:a},Xo(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 Re(Ue.InternalError,`Task ${r} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new Re(Ue.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 Re?s:new Re(Ue.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 p=(g)=>{u(g)};if(!this._transport){p(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(g){p(g);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};if(n?.onprogress)this._progressHandlers.set(d,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}};if(a)m.params={...m.params,task:a};if(c)m.params={...m.params,_meta:{...m.params?._meta||{},[Vo]:c}};let f=(g)=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(g)}},{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((I)=>this._onerror(Error(`Failed to send cancellation: ${I}`)));let b=g instanceof Re?g:new Re(Ue.RequestTimeout,String(g));u(b)};this._responseHandlers.set(d,(g)=>{if(n?.signal?.aborted)return;if(g instanceof Error)return u(g);try{let b=El(t,g.result);if(!b.success)u(b.error);else l(b.data)}catch(b){u(b)}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??W1,v=()=>f(Re.fromError(Ue.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let g=(b)=>{let I=this._responseHandlers.get(d);if(I)I(b);else this._onerror(Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,g),this._enqueueTaskMessage(x,{type:"request",message:m,timestamp:Date.now()}).catch((b)=>{this._cleanupTimeout(d),u(b)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:r,onresumptiontoken:s}).catch((g)=>{this._cleanupTimeout(d),u(g)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},gl,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},bl,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},a_,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||{},[Vo]: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||{},[Vo]: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||{},[Vo]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let n=tm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,r)=>{let s=nm(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=tm(e);this._notificationHandlers.set(n,(o)=>{let r=nm(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"&&Mp(o.message)){let r=o.message.id,s=this._requestResolvers.get(r);if(s)s(new Re(Ue.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 Re(Ue.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new Re(Ue.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 Re(Ue.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=Ws.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Xo(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 Re(Ue.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Xo(a.status))throw new Re(Ue.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=Ws.parse({method:"notifications/tasks/status",params:c});if(await this.notification(l),Xo(c.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>n.listTasks(o,t)}}}var y_="2026-01-26";var q1="ui/notifications/tool-input-partial";var G1=Ae([C("light"),C("dark")]).describe("Color theme preference for the host environment."),Vs=Ae([C("inline"),C("fullscreen"),C("pip")]).describe("Display mode for UI presentation."),V1=Ae([C("--color-background-primary"),C("--color-background-secondary"),C("--color-background-tertiary"),C("--color-background-inverse"),C("--color-background-ghost"),C("--color-background-info"),C("--color-background-danger"),C("--color-background-success"),C("--color-background-warning"),C("--color-background-disabled"),C("--color-text-primary"),C("--color-text-secondary"),C("--color-text-tertiary"),C("--color-text-inverse"),C("--color-text-ghost"),C("--color-text-info"),C("--color-text-danger"),C("--color-text-success"),C("--color-text-warning"),C("--color-text-disabled"),C("--color-border-primary"),C("--color-border-secondary"),C("--color-border-tertiary"),C("--color-border-inverse"),C("--color-border-ghost"),C("--color-border-info"),C("--color-border-danger"),C("--color-border-success"),C("--color-border-warning"),C("--color-border-disabled"),C("--color-ring-primary"),C("--color-ring-secondary"),C("--color-ring-inverse"),C("--color-ring-info"),C("--color-ring-danger"),C("--color-ring-success"),C("--color-ring-warning"),C("--font-sans"),C("--font-mono"),C("--font-weight-normal"),C("--font-weight-medium"),C("--font-weight-semibold"),C("--font-weight-bold"),C("--font-text-xs-size"),C("--font-text-sm-size"),C("--font-text-md-size"),C("--font-text-lg-size"),C("--font-heading-xs-size"),C("--font-heading-sm-size"),C("--font-heading-md-size"),C("--font-heading-lg-size"),C("--font-heading-xl-size"),C("--font-heading-2xl-size"),C("--font-heading-3xl-size"),C("--font-text-xs-line-height"),C("--font-text-sm-line-height"),C("--font-text-md-line-height"),C("--font-text-lg-line-height"),C("--font-heading-xs-line-height"),C("--font-heading-sm-line-height"),C("--font-heading-md-line-height"),C("--font-heading-lg-line-height"),C("--font-heading-xl-line-height"),C("--font-heading-2xl-line-height"),C("--font-heading-3xl-line-height"),C("--border-radius-xs"),C("--border-radius-sm"),C("--border-radius-md"),C("--border-radius-lg"),C("--border-radius-xl"),C("--border-radius-full"),C("--border-width-regular"),C("--shadow-hairline"),C("--shadow-sm"),C("--shadow-md"),C("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),X1=Ze(V1.describe(`Style variables for theming MCP apps.
168
168
 
169
169
  Individual style keys are optional - hosts may provide any subset of these values.
170
170
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -182,10 +182,10 @@ Individual style keys are optional - hosts may provide any subset of these value
182
182
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
183
183
 
184
184
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
185
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),K1=O({method:C("ui/open-link"),params:O({url:P().describe("URL to open in the host's browser")})}),h5=O({isError:Xe().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),g5=O({isError:Xe().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),v5=O({isError:Xe().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),J1=O({method:C("ui/notifications/sandbox-proxy-ready"),params:O({})}),om=O({connectDomains:he(P()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
185
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),K1=O({method:C("ui/open-link"),params:O({url:P().describe("URL to open in the host's browser")})}),g5=O({isError:Xe().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),v5=O({isError:Xe().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),y5=O({isError:Xe().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),J1=O({method:C("ui/notifications/sandbox-proxy-ready"),params:O({})}),om=O({connectDomains:he(P()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
186
186
 
187
187
  - Maps to CSP \`connect-src\` directive
188
- - Empty or omitted → no network connections (secure default)`),resourceDomains:he(P()).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:he(P()).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:he(P()).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'`)")}),rm=O({camera:O({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:O({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:O({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:O({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Y1=O({method:C("ui/notifications/size-changed"),params:O({width:ge().optional().describe("New width in pixels."),height:ge().optional().describe("New height in pixels.")})}),y5=O({method:C("ui/notifications/tool-input"),params:O({arguments:Ze(P(),qe().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),b5=O({method:C("ui/notifications/tool-input-partial"),params:O({arguments:Ze(P(),qe().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),x5=O({method:C("ui/notifications/tool-cancelled"),params:O({reason:P().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Q1=O({fonts:P().optional()}),eP=O({variables:X1.optional().describe("CSS variables for theming the app."),css:Q1.optional().describe("CSS blocks that apps can inject.")}),w5=O({method:C("ui/resource-teardown"),params:O({})}),tP=Ze(P(),qe()),g_=O({text:O({}).optional().describe("Host supports text content blocks."),image:O({}).optional().describe("Host supports image content blocks."),audio:O({}).optional().describe("Host supports audio content blocks."),resource:O({}).optional().describe("Host supports resource content blocks."),resourceLink:O({}).optional().describe("Host supports resource link content blocks."),structuredContent:O({}).optional().describe("Host supports structured content.")}),nP=O({method:C("ui/notifications/request-teardown"),params:O({}).optional()}),oP=O({experimental:O({}).optional().describe("Experimental features (structure TBD)."),openLinks:O({}).optional().describe("Host supports opening external URLs."),downloadFile:O({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:O({listChanged:Xe().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:O({listChanged:Xe().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:O({}).optional().describe("Host accepts log messages."),sandbox:O({permissions:rm.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:om.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:g_.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:g_.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),rP=O({experimental:O({}).optional().describe("Experimental features (structure TBD)."),tools:O({listChanged:Xe().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:he(Vs).optional().describe("Display modes the app supports.")}),iP=O({method:C("ui/notifications/initialized"),params:O({}).optional()}),_5=O({csp:om.optional().describe("Content Security Policy configuration for UI resources."),permissions:rm.optional().describe("Sandbox permissions requested by the UI resource."),domain:P().optional().describe(`Dedicated origin for view sandbox.
188
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:he(P()).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:he(P()).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:he(P()).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'`)")}),rm=O({camera:O({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:O({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:O({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:O({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Y1=O({method:C("ui/notifications/size-changed"),params:O({width:ge().optional().describe("New width in pixels."),height:ge().optional().describe("New height in pixels.")})}),b5=O({method:C("ui/notifications/tool-input"),params:O({arguments:Ze(P(),qe().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),x5=O({method:C("ui/notifications/tool-input-partial"),params:O({arguments:Ze(P(),qe().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),w5=O({method:C("ui/notifications/tool-cancelled"),params:O({reason:P().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),Q1=O({fonts:P().optional()}),eP=O({variables:X1.optional().describe("CSS variables for theming the app."),css:Q1.optional().describe("CSS blocks that apps can inject.")}),_5=O({method:C("ui/resource-teardown"),params:O({})}),tP=Ze(P(),qe()),g_=O({text:O({}).optional().describe("Host supports text content blocks."),image:O({}).optional().describe("Host supports image content blocks."),audio:O({}).optional().describe("Host supports audio content blocks."),resource:O({}).optional().describe("Host supports resource content blocks."),resourceLink:O({}).optional().describe("Host supports resource link content blocks."),structuredContent:O({}).optional().describe("Host supports structured content.")}),nP=O({method:C("ui/notifications/request-teardown"),params:O({}).optional()}),oP=O({experimental:O({}).optional().describe("Experimental features (structure TBD)."),openLinks:O({}).optional().describe("Host supports opening external URLs."),downloadFile:O({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:O({listChanged:Xe().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:O({listChanged:Xe().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:O({}).optional().describe("Host accepts log messages."),sandbox:O({permissions:rm.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:om.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:g_.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:g_.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),rP=O({experimental:O({}).optional().describe("Experimental features (structure TBD)."),tools:O({listChanged:Xe().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:he(Vs).optional().describe("Display modes the app supports.")}),iP=O({method:C("ui/notifications/initialized"),params:O({}).optional()}),S5=O({csp:om.optional().describe("Content Security Policy configuration for UI resources."),permissions:rm.optional().describe("Sandbox permissions requested by the UI resource."),domain:P().optional().describe(`Dedicated origin for view sandbox.
189
189
 
190
190
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
191
191
 
@@ -199,10 +199,10 @@ Boolean requesting whether a visible border and background is provided by the ho
199
199
 
200
200
  - \`true\`: request visible border + background
201
201
  - \`false\`: request no visible border + background
202
- - omitted: host decides border`)}),v_=O({method:C("ui/request-display-mode"),params:O({mode:Vs.describe("The display mode being requested.")})}),S5=O({mode:Vs.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),sP=Ae([C("model"),C("app")]).describe("Tool visibility scope - who can access the tool."),k5=O({resourceUri:P().optional(),visibility:he(sP).optional().describe(`Who can access this tool. Default: ["model", "app"]
202
+ - omitted: host decides border`)}),v_=O({method:C("ui/request-display-mode"),params:O({mode:Vs.describe("The display mode being requested.")})}),k5=O({mode:Vs.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),sP=Ae([C("model"),C("app")]).describe("Tool visibility scope - who can access the tool."),T5=O({resourceUri:P().optional(),visibility:he(sP).optional().describe(`Who can access this tool. Default: ["model", "app"]
203
203
  - "model": Tool visible to and callable by the agent
204
- - "app": Tool callable by the app from this server only`)}),T5=O({mimeTypes:he(P()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),aP=O({method:C("ui/download-file"),params:O({contents:he(Ae([Kp,Jp])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),cP=O({method:C("ui/message"),params:O({role:C("user").describe('Message role, currently only "user" is supported.'),content:he(Pi).describe("Message content blocks (text, image, etc.).")})}),C5=O({method:C("ui/notifications/sandbox-resource-ready"),params:O({html:P().describe("HTML content to load into the inner iframe."),sandbox:P().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:om.optional().describe("CSP configuration from resource metadata."),permissions:rm.optional().describe("Sandbox permissions from resource metadata.")})}),E5=O({method:C("ui/notifications/tool-result"),params:Pr.describe("Standard MCP tool execution result.")}),b_=O({toolInfo:O({id:Ai.optional().describe("JSON-RPC id of the tools/call request."),tool:Sl.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:G1.optional().describe("Current color theme preference."),styles:eP.optional().describe("Style configuration for theming the app."),displayMode:Vs.optional().describe("How the UI is currently displayed."),availableDisplayModes:he(Vs).optional().describe("Display modes the host supports."),containerDimensions:Ae([O({height:ge().describe("Fixed container height in pixels.")}),O({maxHeight:Ae([ge(),ad()]).optional().describe("Maximum container height in pixels.")})]).and(Ae([O({width:ge().describe("Fixed container width in pixels.")}),O({maxWidth:Ae([ge(),ad()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
205
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:P().optional().describe("User's language and region preference in BCP 47 format."),timeZone:P().optional().describe("User's timezone in IANA format."),userAgent:P().optional().describe("Host application identifier."),platform:Ae([C("web"),C("desktop"),C("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:O({touch:Xe().optional().describe("Whether the device supports touch input."),hover:Xe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:O({top:ge().describe("Top safe area inset in pixels."),right:ge().describe("Right safe area inset in pixels."),bottom:ge().describe("Bottom safe area inset in pixels."),left:ge().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),A5=O({method:C("ui/notifications/host-context-changed"),params:b_.describe("Partial context update containing only changed fields.")}),lP=O({method:C("ui/update-model-context"),params:O({content:he(Pi).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Ze(P(),qe().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),uP=O({method:C("ui/initialize"),params:O({appInfo:Hs.describe("App identification (name and version)."),appCapabilities:rP.describe("Features and capabilities this app provides."),protocolVersion:P().describe("Protocol version this app supports.")})}),I5=O({protocolVersion:P().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Hs.describe("Host application identification and version."),hostCapabilities:oP.describe("Features and capabilities provided by the host."),hostContext:b_.describe("Rich context about the host environment.")}).passthrough();class im{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=s_.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!==q1)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}function x_(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 dP=[y_];class sm extends Al{_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(uP,(r)=>this._oninitialize(r)),this.setRequestHandler(Ir,(r,s)=>(this.onping?.(r.params,s),{})),this.setRequestHandler(v_,(r)=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;set onsizechange(e){this.setNotificationHandler(Y1,(t)=>e(t.params))}set onsandboxready(e){this.setNotificationHandler(J1,(t)=>e(t.params))}set oninitialized(e){this.setNotificationHandler(iP,(t)=>e(t.params))}set onmessage(e){this.setRequestHandler(cP,async(t,n)=>e(t.params,n))}set onopenlink(e){this.setRequestHandler(K1,async(t,n)=>e(t.params,n))}set ondownloadfile(e){this.setRequestHandler(aP,async(t,n)=>e(t.params,n))}set onrequestteardown(e){this.setNotificationHandler(nP,(t)=>e(t.params))}set onrequestdisplaymode(e){this.setRequestHandler(v_,async(t,n)=>e(t.params,n))}set onloggingmessage(e){this.setNotificationHandler(em,async(t)=>{e(t.params)})}set onupdatemodelcontext(e){this.setRequestHandler(lP,async(t,n)=>e(t.params,n))}set oncalltool(e){this.setRequestHandler(Tl,async(t,n)=>e(t.params,n))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}set onlistresources(e){this.setRequestHandler(Fp,async(t,n)=>e(t.params,n))}set onlistresourcetemplates(e){this.setRequestHandler(Bp,async(t,n)=>e(t.params,n))}set onreadresource(e){this.setRequestHandler(Up,async(t,n)=>e(t.params,n))}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}set onlistprompts(e){this.setRequestHandler(Wp,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:dP.includes(t)?t:y_,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(pP(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},tP,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},Pr,{signal:o.signal}),t.tools.listChanged)this._client.setNotificationHandler(Qp,(n)=>this.sendToolListChanged(n.params))}if(t.resources){if(this.onlistresources=async(n,o)=>this._client.request({method:"resources/list",params:n},wl,{signal:o.signal}),this.onlistresourcetemplates=async(n,o)=>this._client.request({method:"resources/templates/list",params:n},Hp,{signal:o.signal}),this.onreadresource=async(n,o)=>this._client.request({method:"resources/read",params:n},_l,{signal:o.signal}),t.resources.listChanged)this._client.setNotificationHandler(Zp,(n)=>this.sendResourceListChanged(n.params))}if(t.prompts){if(this.onlistprompts=async(n,o)=>this._client.request({method:"prompts/list",params:n},qp,{signal:o.signal}),t.prompts.listChanged)this._client.setNotificationHandler(Yp,(n)=>this.sendPromptListChanged(n.params))}}return super.connect(e)}}function pP(e,t){return JSON.stringify(e)===JSON.stringify(t)}function am(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function mP(e){return am(e)&&Array.isArray(e.content)&&e.content.every((t)=>am(t)&&typeof t.type==="string")}function fP(...e){for(let t of e)if(typeof t==="string"){if(t.trim().length>0)return t}return}function hP(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 cm(e){let t=e.success===!1;if(mP(e.result))return{...e.result,isError:e.result.isError===!0||t};let n=am(e.result)?e.result:null,o=fP(e.detailedContent,e.content,n?.detailedContent,n?.content,n?.textResultForLlm,n?.text,n?.message,typeof e.result==="string"?e.result:void 0,e.error)??hP(e.result);return{content:o?[{type:"text",text:o}]:[],isError:t}}function w_(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 __(e){return Boolean(e)&&typeof e==="object"&&e!==null&&!Array.isArray(e)&&"ok"in e&&typeof e.ok==="boolean"}async function gP(e,t){let n=await ct("/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||!__(o)||!o.ok||typeof o.url!=="string"){let r=__(o)&&o.error?o.error:`Frame document request failed with HTTP ${n.status}`;throw Error(r)}return o.url}function S_(e,t){let n=Rt.value,[o,r]=A(null),[s,a]=A(0),c=L(0);H(()=>{if(r(null),!e||n!=="src")return;let u=!1;return c.current=_r.value,gP(e,t).then((p)=>{if(!u)r(p)}).catch((p)=>{console.error("[iframe-document] failed to create frame document:",p)}),()=>{u=!0}},[e,t,n,s]);let l=_r.value;return H(()=>{if(n!=="src"||l===c.current)return;if(!o){a((p)=>p+1);return}let u=!1;return ct(o,{method:"HEAD"}).then((p)=>{if(u)return;if(p.ok){c.current=l;return}a((d)=>d+1)}).catch(()=>{}),()=>{u=!0}},[l,o,n]),Be(()=>{if(n==="srcdoc"&&e)return{attributes:{srcdoc:e},ready:!0,key:`srcdoc-${bi(e)}`};return{attributes:o?{src:o}:{},ready:Boolean(o),key:o??""}},[o,n,e])}function Ni(e){let{enabled:t,token:n,nodeId:o,sourceSurface:r,iframeRef:s}=e;_n(()=>{if(!t||!n)return;function a(c){if(c.source!==s.current?.contentWindow)return;let l=c.data;if(!l||l.source!==Xc||l.token!==n||l.nodeId!==o)return;let u=l.interaction;if(!u||typeof u.type!=="string")return;let p=u.type;vc({type:p,sourceNodeId:o,sourceSurface:r,...u.payload&&typeof u.payload==="object"?{payload:u.payload}:{}}).then((d)=>{if(d.ok)on("context","AX interaction",p,[o]);s.current?.contentWindow?.postMessage({source:Kc,token:n,...l.correlationId?{correlationId:l.correlationId}:{},interaction:{type:p},result:d},"*")})}return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[t,n,o,r])}async function Nr(e,t){let o=await(await ct(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 zr(e){return/AppleWebKit/.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/.test(e)}function vP(e){let{userAgent:t,visibilityState:n,rect:o,viewport:r,alreadyRearmed:s}=e;if(s)return!1;if(!zr(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 N_=1000,k_=7000;function At(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});yP({t:Date.now(),nodeId:e,event:t})}var T_=[],lm=null;function yP(e){if(T_.push({...e,...typeof document<"u"?{visibility:document.visibilityState}:{}}),lm)return;lm=setTimeout(()=>{lm=null;let t=T_.splice(0);if(t.length===0)return;ct("/api/canvas/debug/ext-app-recovery",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:t})}).catch(()=>{})},1500)}var C_=Promise.resolve();function E_(e){C_=C_.then(async()=>{if(!e.remount())return;await e.awaitBoot(),await new Promise((t)=>setTimeout(t,N_))}).catch(()=>{})}function bP(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 xP(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 A_(e,t,n){if(await e.sendToolInput({arguments:t}),n)await e.sendToolResult(n)}function wP(e){return typeof e==="string"&&e.trim().length>0?e.trim():wp}function _P(e,t){return`<script data-pmx-canvas-ax-bridge>
204
+ - "app": Tool callable by the app from this server only`)}),C5=O({mimeTypes:he(P()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),aP=O({method:C("ui/download-file"),params:O({contents:he(Ae([Kp,Jp])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),cP=O({method:C("ui/message"),params:O({role:C("user").describe('Message role, currently only "user" is supported.'),content:he(Pi).describe("Message content blocks (text, image, etc.).")})}),E5=O({method:C("ui/notifications/sandbox-resource-ready"),params:O({html:P().describe("HTML content to load into the inner iframe."),sandbox:P().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:om.optional().describe("CSP configuration from resource metadata."),permissions:rm.optional().describe("Sandbox permissions from resource metadata.")})}),A5=O({method:C("ui/notifications/tool-result"),params:Pr.describe("Standard MCP tool execution result.")}),b_=O({toolInfo:O({id:Ai.optional().describe("JSON-RPC id of the tools/call request."),tool:Sl.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:G1.optional().describe("Current color theme preference."),styles:eP.optional().describe("Style configuration for theming the app."),displayMode:Vs.optional().describe("How the UI is currently displayed."),availableDisplayModes:he(Vs).optional().describe("Display modes the host supports."),containerDimensions:Ae([O({height:ge().describe("Fixed container height in pixels.")}),O({maxHeight:Ae([ge(),ad()]).optional().describe("Maximum container height in pixels.")})]).and(Ae([O({width:ge().describe("Fixed container width in pixels.")}),O({maxWidth:Ae([ge(),ad()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
205
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:P().optional().describe("User's language and region preference in BCP 47 format."),timeZone:P().optional().describe("User's timezone in IANA format."),userAgent:P().optional().describe("Host application identifier."),platform:Ae([C("web"),C("desktop"),C("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:O({touch:Xe().optional().describe("Whether the device supports touch input."),hover:Xe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:O({top:ge().describe("Top safe area inset in pixels."),right:ge().describe("Right safe area inset in pixels."),bottom:ge().describe("Bottom safe area inset in pixels."),left:ge().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),I5=O({method:C("ui/notifications/host-context-changed"),params:b_.describe("Partial context update containing only changed fields.")}),lP=O({method:C("ui/update-model-context"),params:O({content:he(Pi).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Ze(P(),qe().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),uP=O({method:C("ui/initialize"),params:O({appInfo:Hs.describe("App identification (name and version)."),appCapabilities:rP.describe("Features and capabilities this app provides."),protocolVersion:P().describe("Protocol version this app supports.")})}),P5=O({protocolVersion:P().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Hs.describe("Host application identification and version."),hostCapabilities:oP.describe("Features and capabilities provided by the host."),hostContext:b_.describe("Rich context about the host environment.")}).passthrough();class im{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=s_.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!==q1)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}function x_(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 dP=[y_];class sm extends Al{_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(uP,(r)=>this._oninitialize(r)),this.setRequestHandler(Ir,(r,s)=>(this.onping?.(r.params,s),{})),this.setRequestHandler(v_,(r)=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;set onsizechange(e){this.setNotificationHandler(Y1,(t)=>e(t.params))}set onsandboxready(e){this.setNotificationHandler(J1,(t)=>e(t.params))}set oninitialized(e){this.setNotificationHandler(iP,(t)=>e(t.params))}set onmessage(e){this.setRequestHandler(cP,async(t,n)=>e(t.params,n))}set onopenlink(e){this.setRequestHandler(K1,async(t,n)=>e(t.params,n))}set ondownloadfile(e){this.setRequestHandler(aP,async(t,n)=>e(t.params,n))}set onrequestteardown(e){this.setNotificationHandler(nP,(t)=>e(t.params))}set onrequestdisplaymode(e){this.setRequestHandler(v_,async(t,n)=>e(t.params,n))}set onloggingmessage(e){this.setNotificationHandler(em,async(t)=>{e(t.params)})}set onupdatemodelcontext(e){this.setRequestHandler(lP,async(t,n)=>e(t.params,n))}set oncalltool(e){this.setRequestHandler(Tl,async(t,n)=>e(t.params,n))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}set onlistresources(e){this.setRequestHandler(Fp,async(t,n)=>e(t.params,n))}set onlistresourcetemplates(e){this.setRequestHandler(Bp,async(t,n)=>e(t.params,n))}set onreadresource(e){this.setRequestHandler(Up,async(t,n)=>e(t.params,n))}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}set onlistprompts(e){this.setRequestHandler(Wp,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:dP.includes(t)?t:y_,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(pP(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},tP,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},Pr,{signal:o.signal}),t.tools.listChanged)this._client.setNotificationHandler(Qp,(n)=>this.sendToolListChanged(n.params))}if(t.resources){if(this.onlistresources=async(n,o)=>this._client.request({method:"resources/list",params:n},wl,{signal:o.signal}),this.onlistresourcetemplates=async(n,o)=>this._client.request({method:"resources/templates/list",params:n},Hp,{signal:o.signal}),this.onreadresource=async(n,o)=>this._client.request({method:"resources/read",params:n},_l,{signal:o.signal}),t.resources.listChanged)this._client.setNotificationHandler(Zp,(n)=>this.sendResourceListChanged(n.params))}if(t.prompts){if(this.onlistprompts=async(n,o)=>this._client.request({method:"prompts/list",params:n},qp,{signal:o.signal}),t.prompts.listChanged)this._client.setNotificationHandler(Yp,(n)=>this.sendPromptListChanged(n.params))}}return super.connect(e)}}function pP(e,t){return JSON.stringify(e)===JSON.stringify(t)}function am(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function mP(e){return am(e)&&Array.isArray(e.content)&&e.content.every((t)=>am(t)&&typeof t.type==="string")}function fP(...e){for(let t of e)if(typeof t==="string"){if(t.trim().length>0)return t}return}function hP(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 cm(e){let t=e.success===!1;if(mP(e.result))return{...e.result,isError:e.result.isError===!0||t};let n=am(e.result)?e.result:null,o=fP(e.detailedContent,e.content,n?.detailedContent,n?.content,n?.textResultForLlm,n?.text,n?.message,typeof e.result==="string"?e.result:void 0,e.error)??hP(e.result);return{content:o?[{type:"text",text:o}]:[],isError:t}}function w_(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 __(e){return Boolean(e)&&typeof e==="object"&&e!==null&&!Array.isArray(e)&&"ok"in e&&typeof e.ok==="boolean"}async function gP(e,t){let n=await ct("/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||!__(o)||!o.ok||typeof o.url!=="string"){let r=__(o)&&o.error?o.error:`Frame document request failed with HTTP ${n.status}`;throw Error(r)}return o.url}function S_(e,t){let n=Rt.value,[o,r]=A(null),[s,a]=A(0),c=L(0);H(()=>{if(r(null),!e||n!=="src")return;let u=!1;return c.current=_r.value,gP(e,t).then((p)=>{if(!u)r(p)}).catch((p)=>{console.error("[iframe-document] failed to create frame document:",p)}),()=>{u=!0}},[e,t,n,s]);let l=_r.value;return H(()=>{if(n!=="src"||l===c.current)return;if(!o){a((p)=>p+1);return}let u=!1;return ct(o,{method:"HEAD"}).then((p)=>{if(u)return;if(p.ok){c.current=l;return}a((d)=>d+1)}).catch(()=>{}),()=>{u=!0}},[l,o,n]),Be(()=>{if(n==="srcdoc"&&e)return{attributes:{srcdoc:e},ready:!0,key:`srcdoc-${bi(e)}`};return{attributes:o?{src:o}:{},ready:Boolean(o),key:o??""}},[o,n,e])}function Ni(e){let{enabled:t,token:n,nodeId:o,sourceSurface:r,iframeRef:s}=e;_n(()=>{if(!t||!n)return;function a(c){if(c.source!==s.current?.contentWindow)return;let l=c.data;if(!l||l.source!==Xc||l.token!==n||l.nodeId!==o)return;let u=l.interaction;if(!u||typeof u.type!=="string")return;let p=u.type;vc({type:p,sourceNodeId:o,sourceSurface:r,...u.payload&&typeof u.payload==="object"?{payload:u.payload}:{}}).then((d)=>{if(d.ok)on("context","AX interaction",p,[o]);s.current?.contentWindow?.postMessage({source:Kc,token:n,...l.correlationId?{correlationId:l.correlationId}:{},interaction:{type:p},result:d},"*")})}return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[t,n,o,r])}async function Nr(e,t){let o=await(await ct(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 zr(e){return/AppleWebKit/.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/.test(e)}function vP(e){let{userAgent:t,visibilityState:n,rect:o,viewport:r,alreadyRearmed:s}=e;if(s)return!1;if(!zr(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 N_=1000,k_=7000;function At(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});yP({t:Date.now(),nodeId:e,event:t})}var T_=[],lm=null;function yP(e){if(T_.push({...e,...typeof document<"u"?{visibility:document.visibilityState}:{}}),lm)return;lm=setTimeout(()=>{lm=null;let t=T_.splice(0);if(t.length===0)return;ct("/api/canvas/debug/ext-app-recovery",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:t})}).catch(()=>{})},1500)}var C_=Promise.resolve();function E_(e){C_=C_.then(async()=>{if(!e.remount())return;await e.awaitBoot(),await new Promise((t)=>setTimeout(t,N_))}).catch(()=>{})}function bP(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 xP(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 A_(e,t,n){if(await e.sendToolInput({arguments:t}),n)await e.sendToolResult(n)}function wP(e){return typeof e==="string"&&e.trim().length>0?e.trim():wp}function _P(e,t){return`<script data-pmx-canvas-ax-bridge>
206
206
  (function () {
207
207
  const PMX_AX_TOKEN = ${JSON.stringify(e)};
208
208
  const PMX_AX_NODE_ID = ${JSON.stringify(t)};
@@ -327,7 +327,7 @@ container holding the app. Specify either width or maxWidth, and either height o
327
327
  });
328
328
  sendPaintTick();
329
329
  })();
330
- </script>`}function I_(){return"<style data-pmx-canvas-ext-app-base>html, body { background: transparent !important; }</style>"}function P_(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 zi(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 um(e,t){let n=e?.getBoundingClientRect();return{width:zi(e?.clientWidth??0,zi(n?.width??0,t.width)),height:zi(e?.clientHeight??0,zi(n?.height??0,t.height))}}function kP(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0&&!t}function TP(e,t){return Math.max(zi(e,1),zi(t,1))}function z_({node:e,expanded:t=!1}){let n=L(null),o=L(null),r=L(null),s=L(null),a=L({}),c=L(void 0),l=L(!1),u=L(void 0),p=L(null),d=L(!1),m=L(null),f=L(0),h=L([]),v=L(""),x=L(!1),g=L(!1),b=L([]),I=L(!1),R=L(!1),M=L(!1),_=L(!1),[N,w]=A("loading"),[k,z]=A(null),[X,W]=A(0),[J,G]=A(!1),[S,q]=A(!1),[ie,ye]=A(()=>t||typeof navigator>"u"||typeof window>"u"||!zr(navigator.userAgent)),ue=e.data.html,Pe=e.data.serverName,ke=e.data.appSessionId,Me=e.data.toolInput??{},cn=e.data.toolResult,Pn=e.data.toolName??"ext-app",D=e.data.toolDefinition,Y=e.data.toolCallId,Te=typeof Y==="string"||typeof Y==="number"?Y:void 0,de=e.data.resourceMeta,be=e.data.sessionStatus,se=e.data.sessionError,re=e.size.height,Z=e.id,xe=bP(e,X),T=wP(null),pe=e.data.axCapabilities?.enabled===!0&&typeof ue==="string"&&ue.length>0,me=Be(()=>`ax-${crypto.randomUUID()}`,[]),qt=pe?_P(me,Z):"",St=typeof ue==="string"&&ue.length>0?SP(me,Z):"",Gt=S_(P_(ue??"",I_()+St+qt),T);H(()=>{function Q(le){if(le.source!==n.current?.contentWindow)return;let Ce=le.data;if(!Ce||Ce.source!==Jc||Ce.token!==me||Ce.nodeId!==Z)return;if(g.current=!0,Ce.kind==="paint-tick"){let Ie=Ce,Bt={content:Ie.content===!0,detail:typeof Ie.detail==="string"?Ie.detail:""};for(let zn of h.current.splice(0))zn(Bt)}}return window.addEventListener("message",Q),()=>window.removeEventListener("message",Q)},[me,Z]),H(()=>{if(ie)return;E_({remount:()=>{if(_.current)return!1;return At(Z,"mount-slot"),ye(!0),!0},awaitBoot:()=>new Promise((Q)=>{let le=window.setTimeout(Ce,k_);function Ce(){window.clearTimeout(le),Q()}b.current.push(Ce)})})},[]),Ni({enabled:pe,token:me,nodeId:Z,sourceSurface:"mcp-app",iframeRef:n});let yn=3,ar=(Q)=>{if(f.current>=yn)return At(Z,`remount-cap-hit (${Q})`),!1;if(I.current)return!0;return f.current+=1,I.current=!0,At(Z,`remount-queued #${f.current} (${Q})`),E_({remount:()=>{if(I.current=!1,_.current||!t&&ot.value===Z)return At(Z,"remount-skipped"),G(!1),!1;return R.current=typeof document<"u"&&document.visibilityState==="hidden",At(Z,`remount-run #${f.current}`),w("loading"),W((le)=>le+1),!0},awaitBoot:()=>new Promise((le)=>{let Ce=window.setTimeout(Ie,k_);function Ie(){window.clearTimeout(Ce),le()}b.current.push(Ie)})}),!0},da=1500,bn=()=>new Promise((Q)=>{let le=n.current?.contentWindow;if(!le||_.current){Q("timeout");return}let Ce=!1,Ie=window.setTimeout(()=>{if(Ce)return;Ce=!0,Q("timeout")},da);h.current.push((Bt)=>{if(Ce)return;Ce=!0,window.clearTimeout(Ie),v.current=Bt.detail,Q(Bt.content?"content-verified":"tick-no-content")}),le.postMessage({source:xp,token:me},"*")}),Nn=async(Q)=>{let le=Date.now()+Q;while(Date.now()<le&&!_.current){if(await bn()==="content-verified")return!0;await new Promise((Ce)=>window.setTimeout(Ce,400))}return!1},eo=()=>new Promise((Q)=>{let le=n.current;if(!le){Q();return}let Ce=le.style.width,Ie=le.style.height;le.style.width="140%",le.style.height="140%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{le.style.width=Ce,le.style.height=Ie,At(Z,"soft-expand-cycle"),Q()})})}),Gi=600,to=()=>{if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;let Q=n.current;if(!Q||_.current)return;if(!vP({userAgent:navigator.userAgent,visibilityState:document.visibilityState,rect:Q.getBoundingClientRect(),viewport:{width:window.innerWidth,height:window.innerHeight},alreadyRearmed:M.current}))return;M.current=!0,window.setTimeout(()=>{if(_.current||document.visibilityState==="visible")return;f.current=0,q(!1),R.current=!1,At(Z,"assume-visible-rearm"),ar("assume-visible")},Gi)},_o=(Q="")=>{let le=v.current?` [${v.current}]`:"";return typeof document<"u"&&document.visibilityState==="hidden"?`paint-ok (content-verified)${le}${Q} (host hidden)`:`paint-ok (content-verified)${le}${Q}`},Vi=async()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!zr(navigator.userAgent))return;G(!0);let Q=await bn();if(Q==="content-verified"){At(Z,_o()),G(!1),to();return}if(At(Z,Q==="tick-no-content"?`paint-fail (tick without content: ${v.current||"unknown"})`:"paint-fail (no tick)"),await eo(),Q=await bn(),Q==="content-verified"){At(Z,_o(" (after soft-expand)")),G(!1),to();return}if(_.current)return;if(Q==="tick-no-content"&&await Nn(3000)){At(Z,_o(" (after content wait)")),G(!1),to();return}if(_.current)return;if(!ar("paint-fail"))At(Z,"recovery-exhausted"),G(!1),q(!0),to()};H(()=>{if(t)return;if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;if(!zr(navigator.userAgent))return;function Q(){if(document.visibilityState!=="visible")return;if(!R.current||_.current)return;R.current=!1,f.current=0,q(!1),At(Z,"visible-again-rearm"),ar("visible-after-hidden-boot")}return document.addEventListener("visibilitychange",Q),()=>document.removeEventListener("visibilitychange",Q)},[t,Z]);let So=6000;H(()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!zr(navigator.userAgent))return;if(!Gt.ready||!ie)return;let Q=window.setTimeout(()=>{if(x.current||g.current||_.current)return;ar("boot-watchdog")},So);return()=>window.clearTimeout(Q)},[xe,Gt.ready,t,ie]),H(()=>()=>{_.current=!0;for(let Q of b.current.splice(0))Q();for(let Q of h.current.splice(0))Q({content:!1,detail:"unmounted"})},[]);let ko=(Q)=>Go(Q),ln=t||ot.value===Z;a.current=Me,c.current=cn;let cr=be==="error"&&typeof ue==="string"&&ue.length>0,Hr=be==="error"?cr?`Live session unavailable — showing saved content. Reopen the app to restore interactivity.${se?` (${se})`:""}`:se??"Saved app session is unavailable. Reopen the app to restore interactivity.":"Reconnecting saved app session...",jr=(Q)=>{let le=c.current;if(!Q||!d.current||!le)return null;if(u.current===le)return null;if(u.current&&w_(u.current,le))return u.current=le,null;if(p.current)return p.current;let Ce=Q.sendToolResult(le).then(()=>{u.current=le,l.current=!0,w("done")}).catch((Ie)=>{let Bt=Ie instanceof Error?Ie.message:String(Ie);throw z(`Tool result delivery failed: ${Bt}`),Ie}).finally(()=>{p.current=null});return p.current=Ce,Ce};if(H(()=>{if(!ue||!Gt.ready||!ie)return;let Q=n.current;if(!Q)return;let le=!1,Ce=null,Ie=null,Bt=null,zn=null,Un=null;l.current=!1,u.current=void 0,p.current=null,d.current=!1,x.current=!1,g.current=!1;let To=()=>{if(!Ce)return;clearTimeout(Ce),Ce=null};return(async()=>{if(!ue)return;let un=Q.contentWindow;if(!un)throw Error("Ext-app iframe window is unavailable");let xn=(Ee=ot.value===Z?"fullscreen":"inline")=>({theme:ko(gt.value),platform:"web",containerDimensions:um(Q,{width:e.size.width,height:re}),displayMode:Ee,locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,...D?{toolInfo:{id:Te,tool:D}}:{}}),wn=()=>{if(zn!==null)return;zn=requestAnimationFrame(()=>{if(zn=null,le||!d.current)return;Fe.setHostContext?.(xn())})},no=()=>{if(Un!==null)return;Un=requestAnimationFrame(()=>{Un=requestAnimationFrame(()=>{if(Un=null,le||!d.current)return;Fe.sendHostContextChange?.(xn())})})},Ur=()=>{if(!zr(navigator.userAgent))return;if(Ie)clearTimeout(Ie);Ie=setTimeout(()=>{if(Ie=null,le)return;Vi()},N_+200)},Fe=new sm(null,{name:"PMX Canvas",version:"1.0.0"},{openLinks:{},serverTools:{listChanged:!1},serverResources:{listChanged:!1},logging:{},updateModelContext:{text:{},structuredContent:{}}},{hostContext:xn(ln?"fullscreen":"inline")});Fe.onsizechange=async({height:Ee})=>{if(kP(Ee,ot.value===Z)){let ut=um(Q.parentElement??Q,{width:e.size.width,height:re}),Ht=TP(Ee,ut.height);Q.style.height=`${Ht}px`;let oo=F.value.get(Z)?.size??e.size,Co=Math.max(oo.height,Ht+Si);if(Math.abs(Co-oo.height)>8){if(Cc(Z,{width:oo.width,height:Co}),s.current!==null)window.clearTimeout(s.current);s.current=window.setTimeout(()=>{Tt({recordHistory:!1}),s.current=null},0)}}return{}},Fe.onopenlink=async({url:Ee})=>(window.open(Ee,"_blank","noopener"),{}),Fe.onsandboxready=async()=>{await Fe.sendSandboxResourceReady({html:P_(ue,I_()),sandbox:wp,...de?.csp?{csp:de.csp}:{},...de?.permissions?{permissions:de.permissions}:{}})},Fe.onrequestdisplaymode=async({mode:Ee})=>{let{nextMode:ut,shouldExpand:Ht,shouldCollapse:oo}=xP(Ee,ln);if(Ht)kn(Z);else if(oo)ho();return{mode:ut}},Fe.oncalltool=async(Ee)=>{if(!ke)throw Error(Hr);try{let ut=await Nr("/api/ext-app/call-tool",{sessionId:ke,nodeId:Z,serverName:Pe,toolName:Ee.name,arguments:Ee.arguments??{}});return z(null),ut}catch(ut){let Ht=ut instanceof Error?ut.message:String(ut);throw z(`Tool call failed: ${Ht}`),ut}},Fe.setRequestHandler(kl,async()=>{if(!ke)return{tools:[]};return Nr("/api/ext-app/list-tools",{sessionId:ke})}),Fe.onlistresources=async()=>ke?Nr("/api/ext-app/list-resources",{sessionId:ke}):{resources:[]},Fe.onlistresourcetemplates=async()=>ke?Nr("/api/ext-app/list-resource-templates",{sessionId:ke}):{resourceTemplates:[]},Fe.onreadresource=async(Ee)=>{if(!ke)throw Error(Hr);return Nr("/api/ext-app/read-resource",{sessionId:ke,uri:Ee.uri})},Fe.onlistprompts=async()=>ke?Nr("/api/ext-app/list-prompts",{sessionId:ke}):{prompts:[]},Fe.onupdatemodelcontext=async(Ee)=>{if(!ke)return{};return await Nr("/api/ext-app/model-context",{nodeId:Z,...Array.isArray(Ee.content)?{content:Ee.content}:{},...Ee.structuredContent&&typeof Ee.structuredContent==="object"?{structuredContent:Ee.structuredContent}:{}}),{}};let Xi=new im(un,un);if(Fe.oninitialized=()=>{if(le)return;To(),d.current=!0,x.current=!0,At(Z,"initialized"),w("ready"),z(null),Promise.resolve(Fe.sendHostContextChange(xn(ln?"fullscreen":"inline"))).then(()=>A_(Fe,a.current,void 0)).then(()=>jr(Fe)).then(()=>{let Ee=()=>{for(let ut of b.current.splice(0))ut()};if(typeof navigator<"u"&&zr(navigator.userAgent))Nn(4000).then((ut)=>{At(Z,ut?"settled (content-verified)":`settled (content-timeout${v.current?`: ${v.current}`:""})`),Ee()});else At(Z,"settled"),Ee();no(),Ur()}).catch((Ee)=>{let ut=Ee instanceof Error?Ee.message:String(Ee);z(`Bridge bootstrap failed: ${ut}`)})},Ce=setTimeout(()=>{if(le||d.current)return;let Ee=c.current,ut=xn(ln?"fullscreen":"inline");d.current=!0,Fe.setHostContext?.(ut),Promise.resolve(Fe.sendHostContextChange(ut)).then(()=>A_(Fe,a.current,Ee)).then(()=>{if(l.current=Boolean(Ee),Ee)u.current=Ee;if(w(Ee?"done":"ready"),z(null),no(),Ur(),g.current){At(Z,"settled (fallback)");for(let Ht of b.current.splice(0))Ht()}}).catch((Ht)=>{let oo=Ht instanceof Error?Ht.message:String(Ht);z(`Bridge bootstrap fallback failed: ${oo}`)})},1200),await Fe.connect(Xi),le){To(),await Xi.close();return}if(o.current=Fe,r.current=Xi,Bt=new ResizeObserver(wn),Bt.observe(Q),Q.parentElement)Bt.observe(Q.parentElement);let Ki=!0;m.current=gt.subscribe((Ee)=>{if(Ki){Ki=!1;return}if(le)return;Fe.setHostContext?.({...xn(),theme:ko(Ee)}),Fe.sendHostContextChange?.(xn())}),jr(Fe)})().catch((un)=>{To(),console.error("[ext-app] Bridge init failed:",un),z(un?.message??"Bridge initialization failed")}),()=>{if(le=!0,To(),Ie)clearTimeout(Ie),Ie=null;if(Bt?.disconnect(),Bt=null,zn!==null)cancelAnimationFrame(zn),zn=null;if(Un!==null)cancelAnimationFrame(Un),Un=null;if(d.current=!1,p.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((un)=>{console.error("[ext-app] transport close failed:",un)}),r.current=null}},[xe,Gt.key,ie]),H(()=>{if(cn&&o.current&&(N==="ready"||N==="done"))jr(o.current)},[cn,N]),H(()=>{let Q=o.current;if(n.current)n.current.style.height="100%";if(!Q||!d.current)return;let le=null,Ce=null;return le=requestAnimationFrame(()=>{le=null,Ce=requestAnimationFrame(()=>{if(Ce=null,!d.current)return;let Ie={theme:ko(gt.value),platform:"web",containerDimensions:um(n.current,{width:e.size.width,height:re}),displayMode:ln?"fullscreen":"inline",locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone};Q.setHostContext?.(Ie),Q.sendHostContextChange?.(Ie)})}),()=>{if(le!==null)cancelAnimationFrame(le);if(Ce!==null)cancelAnimationFrame(Ce)}},[ln,re]),!ue)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 ",Pn," 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:[be&&be!=="ready"&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:be==="error"&&!cr?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 10%, transparent)",color:be==="error"&&!cr?"var(--c-danger)":"var(--c-warn)",borderBottom:`1px solid ${be==="error"&&!cr?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 15%, transparent)"}`},children:Hr},void 0,!1,void 0,this),k&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:"color-mix(in srgb, var(--c-danger) 12%, transparent)",color:"var(--c-danger)",borderBottom:"1px solid color-mix(in srgb, var(--c-danger) 12%, transparent)",display:"flex",alignItems:"center",gap:"6px"},children:[i("span",{children:"⚠"},void 0,!1,void 0,this),i("span",{style:{flex:1},children:k},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>{z(null),w("loading"),W((Q)=>Q+1)},style:{background:"var(--c-surface-hover)",border:"1px solid color-mix(in srgb, var(--c-danger) 12%, transparent)",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),"aria-label":"Dismiss error",style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:i(Ve,{size:14},void 0,!1,void 0,this)},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:[ie&&i("iframe",{ref:n,...Gt.attributes,sandbox:T,allow:x_(de?.permissions),style:{flex:1,width:"100%",height:"100%",minHeight:0,border:"none",background:"var(--c-panel)",pointerEvents:ln?"auto":"none"},title:`Ext App: ${Pn}`},xe,!1,void 0,this),S&&!k&&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:(Q)=>{Q.stopPropagation(),At(Z,"manual-retry"),f.current=0,q(!1),w("loading"),W((le)=>le+1)},style:{background:"var(--c-surface-hover)",border:"1px solid color-mix(in srgb, var(--c-warn) 15%, transparent)",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),(N==="loading"||J)&&!k&&!S&&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:N==="loading"?`Connecting to ${Pn}...`:"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),!ln&&!(S&&!k)&&i("button",{type:"button",onClick:(Q)=>{Q.stopPropagation(),kn(Z)},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)}var Xs=new Map,R_=!1;function M_(e,t,n){if(!R_)R_=!0,nn(()=>{let s=F.value,a=yr.value;for(let[c,l]of Xs){let u=s.get(c);if(!u||l.epoch!==a||l.version!==u.data.specVersion||l.documentUrl!==u.data.url)Xs.delete(c)}}),window.addEventListener("message",(s)=>{let a=s.data;if(!a||a.source!==bp||a.type!=="snapshot"||typeof a.nodeId!=="string")return;let c=Xs.get(a.nodeId),l=c?.owners.findIndex((d)=>d.token===a.token&&d.source===s.source)??-1;if(!c||l<0)return;if(!a.state||typeof a.state!=="object"||Array.isArray(a.state))return;let{ax:u,...p}=a.state;c.state=p,c.owners=c.owners.slice(l)});let o=F.value.get(e);if(!o)return;let r=Xs.get(e);if(!r)r={epoch:yr.value,version:o.data.specVersion,documentUrl:o.data.url,state:null,owners:[]},Xs.set(e,r);r.owners=[...r.owners.filter((s)=>s.source!==n).slice(-1),{token:t,source:n}],n.postMessage({source:bp,type:"restore",token:t,state:r.state},"*")}function CP(e,t,n,o,r,s,a,c){if(!e)return e;try{let l=Se()&&e.startsWith("/"),u=new URL(e,l?"https://pmx.invalid":window.location.origin);if(u.searchParams.set("theme",Go(gt.value)),t)u.searchParams.set("display","expanded");if(typeof n==="number")u.searchParams.set("v",String(n));if(o)u.searchParams.set("axToken",o);if(r)u.searchParams.set("axNodeId",r);if(s)u.searchParams.set("frameToken",s);if(a)u.searchParams.set("fit","content");if(c)u.searchParams.set("stateToken",c);return l?`${u.pathname}${u.search}`:u.toString()}catch{return e}}function EP(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 dm({source:e,iframeRef:t,onLoad:n,onDocumentLoad:o,title:r,className:s="mcp-app-frame",sandbox:a="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",allow:c="clipboard-read; clipboard-write",tabIndex:l}){let u=e.src??e.srcdoc??"",[p,d]=A({key:u,source:e}),[m,f]=A(null),h=L(0);H(()=>{if(h.current+=1,!u||u===p.key){f(null);return}if(!p.key){d({key:u,source:e});return}f({key:u,source:e})},[u,p.key]),H(()=>()=>{h.current+=1},[]);let v=(x,g)=>i("iframe",{ref:g?void 0:t,...x.source,class:s,sandbox:a,allow:c,tabIndex:l,loading:Rt.value==="srcdoc"?void 0:"lazy",onLoad:(b)=>{if(o?.(b.currentTarget),!g){n();return}let I=++h.current,R=b.currentTarget;requestAnimationFrame(()=>requestAnimationFrame(()=>{if(h.current!==I)return;t.current=R,d(x),f(null),n()}))},style:{position:"absolute",inset:0,width:"100%",height:"100%",visibility:g?"hidden":"visible",background:"var(--c-panel-soft)"},title:r},x.key,!1,void 0,this);return i("div",{class:"mcp-app-frame-stack",children:[v(p,!1),m&&v(m,!0)]},void 0,!0,void 0,this)}function Ko({node:e,expanded:t=!1}){if(e.data.mode==="ext-app")return i(z_,{node:e,expanded:t},void 0,!1,void 0,this);return i(AP,{node:e,expanded:t},void 0,!1,void 0,this)}function AP({node:e,expanded:t}){let n=L(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=Be(()=>c?`ax-${crypto.randomUUID()}`:"",[c]),p=Pp(e)&&!t,d=Be(()=>p?`frame-${crypto.randomUUID()}`:"",[p]);ki(e,n,d),Ni({enabled:c&&Boolean(u),token:u,nodeId:e.id,sourceSurface:l,iframeRef:n});let m=Dn.value,f=()=>{if(!c||!u||m==null)return;n.current?.contentWindow?.postMessage({source:Tn,type:"ax-update",token:u,state:m},"*")};H(f,[c,u,m]);let h=typeof e.data.specVersion==="number"?e.data.specVersion:void 0,v=Be(()=>r?`ui-${crypto.randomUUID()}`:"",[r,h,e.data.url]),x=CP(e.data.url||"",t,h,u||void 0,c?e.id:void 0,d||void 0,p,v||void 0),g=Ti(x),b=e.data.sourceServer||"",I=e.data.hostMode||"hosted",R=e.data.fallbackReason,M=e.data.trustedDomain===!0||EP(x);if(I==="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),R&&i("div",{style:{color:"var(--c-muted)",fontSize:"11px"},children:["Reason: ",R]},void 0,!0,void 0,this),i("a",{href:x,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all"},children:x},void 0,!1,void 0,this),b&&i("div",{style:{color:"var(--c-dim)",fontSize:"10px"},children:["Source: ",b]},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:[!M&&i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-warn) 10%, transparent)",color:"var(--c-warn)",borderBottom:"1px solid color-mix(in srgb, var(--c-warn) 15%, transparent)"},children:"Unverified domain"},void 0,!1,void 0,this),i(dm,{source:g,iframeRef:n,onDocumentLoad:(_)=>{if(v&&_.contentWindow)M_(e.id,v,_.contentWindow)},onLoad:f,title:`MCP App: ${b}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var IP=null;function Ri(){IP=null}var $_={idle:"var(--c-muted)",running:"var(--c-accent)",planning:"var(--c-agent)",thinking:"var(--c-agent)",drafting:"var(--c-accent)",tooling:"var(--c-accent)",review:"var(--c-ok)","waiting-approval":"var(--c-warn)",waiting:"var(--c-warn)"};function PP(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 Il({node:e}){let t=PP(e),n=e.data.detail||"",o=e.data.message||"",r=e.data.level||"ok",s=e.data.activeTool,a=e.data.subagent,c=$_[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-agent)"},children:[i("span",{style:{fontSize:"10px"},children:"⚙"},void 0,!1,void 0,this),i("span",{style:{fontFamily:"var(--font-code)",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 Mi(e){return typeof e==="string"&&e.trim().length>0?e.trim():null}function O_(e){if(typeof e==="string"){let r=Mi(e);return r?{title:"Evidence warning",detail:r}:null}if(!e||typeof e!=="object")return null;let t=e,n=Mi(t.title)??"Evidence warning",o=Mi(t.detail);return o?{title:n,detail:o}:null}function NP(e){let t=[],n=O_(e.data.warning);if(n)t.push(n);let o=e.data.warnings;if(Array.isArray(o))for(let s of o){let a=O_(s);if(a)t.push(a)}let r=Mi(e.data.validationStatus)?.toLowerCase();if(r==="failed"||r==="invalid")t.push({title:"Image failed validation",detail:Mi(e.data.validationMessage)??"Review this image before using it as evidence."});return t}function zP(e){let t=[e.data.title,e.data.caption,e.data.alt,e.data.src,e.data.path].map((n)=>Mi(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 L_(e){let t=NP(e);if(t.length>0)return t;if(zP(e))return[{title:"Captured login page",detail:"This image looks like an auth screen. Treat it as environment context, not product evidence."}];return[]}function Pl({node:e,expanded:t=!1}){let n=e.data.src||"",o=e.data.alt||e.data.title||"Image",r=e.data.caption||"",s=L_(e),a=hi(n.startsWith("data:")||n.startsWith("http://")||n.startsWith("https://")?n:`/api/canvas/image/${e.id}`),[c,l]=A(!1),[u,p]=A(!1),[d,m]=A(1),[f,h]=A({x:0,y:0}),[v,x]=A({w:0,h:0}),g=L(null),b=L(!1),I=L({x:0,y:0}),R=j((J)=>{let G=J.target;x({w:G.naturalWidth,h:G.naturalHeight}),l(!0),p(!1)},[]),M=j(()=>{p(!0),l(!1)},[]);H(()=>{m(1),h({x:0,y:0})},[n]);let _=j((J)=>{J.preventDefault(),J.stopPropagation();let G=J.deltaY>0?0.9:1.1;m((S)=>Math.max(0.25,Math.min(10,S*G)))},[]),N=j((J)=>{if(d<=1)return;J.stopPropagation(),b.current=!0,I.current={x:J.clientX,y:J.clientY},J.target.setPointerCapture(J.pointerId)},[d]),w=j((J)=>{if(!b.current)return;let G=J.clientX-I.current.x,S=J.clientY-I.current.y;I.current={x:J.clientX,y:J.clientY},h((q)=>({x:q.x+G,y:q.y+S}))},[]),k=j(()=>{b.current=!1},[]),z=j(()=>{m(1),h({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 X=v.w>0?`${v.w}×${v.h}`:"",W=Math.round(d*100);return i("div",{class:`image-node ${t?"image-node-expanded":""}`,ref:g,children:[s.length>0&&i("div",{class:"image-node-warning-stack",children:s.map((J)=>i("div",{class:"image-node-warning",children:[i("span",{class:"image-node-warning-title",children:J.title},void 0,!1,void 0,this),i("span",{class:"image-node-warning-detail",children:J.detail},void 0,!1,void 0,this)]},`${J.title}-${J.detail}`,!0,void 0,this))},void 0,!1,void 0,this),i("div",{class:"image-node-viewport",onWheel:_,onPointerDown:N,onPointerMove:w,onPointerUp:k,style:{cursor:d>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:R,onError:M,draggable:!1,style:{transform:`translate(${f.x}px, ${f.y}px) scale(${d})`,opacity:c?1:0,display:u?"none":"block"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(r||X||d!==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:[X&&i("span",{children:X},void 0,!1,void 0,this),d!==1&&i("button",{type:"button",class:"image-node-zoom-reset",onClick:z,title:"Reset zoom",children:[W,"% ",i(Pc,{size:14},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 D_({node:e}){if((e.data.children??[]).filter((o)=>F.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 RP(e){try{return new URL(e).host}catch{return e}}function MP(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Nl({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=MP(typeof e.data.fetchedAt==="string"?e.data.fetchedAt:void 0),u=typeof e.data.statusCode==="number"?e.data.statusCode:null,p=typeof e.data.imageUrl==="string"?e.data.imageUrl:"",d=e.data.frameBlocked===!0,m=typeof e.data.frameBlockedReason==="string"?e.data.frameBlockedReason:"",[f,h]=A(!1),[v,x]=A(t);H(()=>{if(t)x(!0)},[t]);let g=j(async()=>{if(!n||f)return;h(!0);try{await gc(e.id)}finally{h(!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 b=a==="ready"?"var(--c-ok)":a==="error"?"var(--c-danger)":"var(--c-muted)";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:RP(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:b,fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.04em",flexShrink:0},children:[i("span",{style:{width:"7px",height:"7px",borderRadius:"999px",background:b}},void 0,!1,void 0,this),a]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(r||p)&&i("div",{style:{display:"grid",gridTemplateColumns:p&&t?"160px 1fr":"1fr",gap:"12px",alignItems:"start"},children:[p&&t&&i("img",{src:p,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:g,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&&!d&&i("button",{type:"button",onClick:()=>x((I)=>!I),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:v?"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&&d&&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&&v&&!d&&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),d&&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 F_(e){return e.type==="html"&&e.data.presentation===!0}function Ks({node:e,expanded:t=!1,presentation:n=!1,presentationExitToken:o,autoFocus:r=!1}){let s=L(null),a=gt.value,c=Be(()=>`theme-${crypto.randomUUID()}`,[]),l=Be(()=>`ax-${crypto.randomUUID()}`,[]),u=Be(()=>`frame-${crypto.randomUUID()}`,[]),p=typeof e.data.html==="string"?e.data.html:typeof e.data.content==="string"?e.data.content:"",d=Be(()=>bi(p),[p]),m=Be(()=>p?Rs(e.id,{theme:a,themeToken:c,present:n,presentToken:o,v:d,axToken:l,frameToken:u}):"",[p,n,o,c,d,e.id,l,u]),f=Ti(m);ki(e,s,t?"":u),Ni({enabled:!0,token:l,nodeId:e.id,sourceSurface:"html-node",iframeRef:s}),H(()=>{if(s.current?.contentWindow?.postMessage({source:Tn,type:"theme-update",token:c,theme:a},"*"),r)s.current?.focus()},[a,c]);let h=e.data.axCapabilities,v=h?.enabled===!0&&(!Array.isArray(h.allowed)||h.allowed.length>0),x=Dn.value;H(()=>{if(!v||x==null)return;s.current?.contentWindow?.postMessage({source:Tn,type:"ax-update",token:l,state:x},"*")},[v,x,l]),H(()=>{if(!r)return;let b=window.setTimeout(()=>s.current?.focus(),0);return()=>window.clearTimeout(b)},[r,m]);let g=()=>{if(s.current?.contentWindow?.postMessage({source:Tn,type:"theme-update",token:c,theme:a},"*"),v&&Dn.value!=null)s.current?.contentWindow?.postMessage({source:Tn,type:"ax-update",token:l,state:Dn.value},"*");if(r)s.current?.focus()};if(!p)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(dm,{source:f,iframeRef:s,className:n?"html-node-frame html-node-frame-presentation":t?"html-node-frame html-node-frame-expanded":"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"HTML node",sandbox:"allow-scripts",allow:"",tabIndex:r?0:void 0,onLoad:g},void 0,!1,void 0,this)}var pm=null;async function B_(){if(!pm)pm=await hb();return pm}function H_(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 $P({html:e}){let t=L(null);return H(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=Qn(e),n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function OP(e,t){return`${e.role}:${e.status??"none"}:${t}:${e.text}`}function j_({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 U_({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,"aria-label":"Dismiss error",style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zl({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",p=a==="answered",[d,m]=A(""),[f,h]=A(""),[v,x]=A(null),[g,b]=A(new Map),I=L(null),R=L(null),M=n[n.length-1],_=`${n.length}:${M?.role??""}:${M?.status??""}:${Math.floor((M?.text?.length??0)/200)}`;H(()=>{if(t&&c&&I.current)I.current.focus()},[t,c]),H(()=>{if(!_)return;if(R.current)R.current.scrollTo({top:R.current.scrollHeight,behavior:"smooth"})},[_]);let N=L(null),w=L(n);w.current=n,H(()=>{let G=n.some((q)=>q.role==="assistant"&&q.status==="streaming"),S=()=>{let q=!1,ye=w.current.map((ue,Pe)=>({turn:ue,index:Pe})).filter(({turn:ue})=>ue.role==="assistant"&&ue.text);if(ye.length===0)return;return Promise.all(ye.map(async({turn:ue,index:Pe})=>{let ke=await Vn(ue.text);return{index:Pe,html:Qn(ke)}})).then((ue)=>{if(q)return;let Pe=new Map;for(let ke of ue)Pe.set(ke.index,ke.html);b(Pe)}),()=>{q=!0}};if(!G){if(N.current)clearTimeout(N.current),N.current=null;return S()}if(N.current)clearTimeout(N.current);return N.current=setTimeout(()=>{N.current=null,S()},400),()=>{if(N.current)clearTimeout(N.current),N.current=null}},[n]);let k=j(async()=>{let G=d.trim();if(!G)return;let S=d;x(null),fe(e.id,{turns:[{role:"user",text:G,status:"pending"}],threadStatus:"pending",text:G}),m("");let q=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds:void 0;if(!(await ys(G,e.position,e.id,q,e.id)).ok)fe(e.id,{turns:[],threadStatus:"draft",text:"",status:"draft"}),m(S),x("Failed to send prompt. Your draft has been restored.")},[d,e.id,e.position,e.data.contextNodeIds]),z=j(async()=>{let G=f.trim();if(!G)return;let S=f;x(null);let q=Array.isArray(e.data.turns)?[...e.data.turns]:[];if(q.push({role:"user",text:G,status:"pending"}),fe(e.id,{turns:q,threadStatus:"pending"}),h(""),!(await gb(e.id,G)).ok)q.pop(),fe(e.id,{turns:q,threadStatus:"answered"}),h(S),x("Failed to send reply. Your draft has been restored.")},[f,e.id,e.data.turns]),X=j((G)=>{if(G.key==="Enter"&&(G.metaKey||G.ctrlKey)){G.preventDefault(),k();return}if(G.key==="Tab"&&d.startsWith("/")){G.preventDefault();let S=d.slice(1).split(/\s/)[0];if(S)B_().then((q)=>{let ie=H_(S,q);if(ie)m(`/${ie}`)})}},[k,d]),W=j((G)=>{if(G.key==="Enter"&&(G.metaKey||G.ctrlKey)){G.preventDefault(),z();return}if(G.key==="Tab"&&f.startsWith("/")){G.preventDefault();let S=f.slice(1).split(/\s/)[0];if(S)B_().then((q)=>{let ie=H_(S,q);if(ie)h(`/${ie}`)})}},[z,f]),J=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(j_,{count:J},void 0,!1,void 0,this),i(U_,{message:v,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("textarea",{ref:I,value:d,onInput:(G)=>m(G.target.value),onKeyDown:X,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-ui)",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:k,disabled:!d.trim(),style:{padding:"5px 14px",fontSize:"12px",fontWeight:600,background:d.trim()?"var(--c-accent)":"var(--c-line)",color:d.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:d.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)":p?"var(--c-ok)":"var(--c-muted)"},children:l?"Sending…":p?"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(j_,{count:J},void 0,!1,void 0,this),i(U_,{message:v,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("div",{ref:R,style:{flex:1,overflow:"auto",minHeight:0},children:n.map((G,S)=>i("div",{children:[S>0&&i("div",{class:"thread-turn-divider"},void 0,!1,void 0,this),G.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:G.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${G.status==="streaming"?" pulsing":""}`},void 0,!1,void 0,this),"PMX"]},void 0,!0,void 0,this),G.status==="streaming"&&!G.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:G.text?1:0.4},children:g.get(S)?i(_e,{children:[i($P,{html:g.get(S)??""},void 0,!1,void 0,this),G.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:G.status==="streaming"?"Waiting for response…":G.text||"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},OP(G,S),!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:p?"6px":0},children:[i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:u?"var(--c-accent)":l?"var(--c-warn)":p?"var(--c-ok)":"var(--c-muted)"},children:u?"Streaming…":l?"Sending…":p?"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),p&&i("div",{class:"thread-reply-area",children:[i("textarea",{value:f,onInput:(G)=>h(G.target.value),onKeyDown:W,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-ui)",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 LP({html:e}){let t=L(null);return H(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=Qn(e),n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function Rl({node:e,expanded:t=!1}){let n=e.data.content||"",o=e.data.status||"streaming",[r,s]=A(""),a=o==="streaming",c=o==="complete";H(()=>{if(!n){s("");return}let u=!1;return Vn(n).then((p)=>{if(!u)s(Qn(p))}),()=>{u=!0}},[n]);let l=j(()=>{ys("",{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(LP,{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 Z_(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 W_={mcp:"var(--c-muted)",file:"var(--c-muted)",subagent:"var(--c-subagent)",other:"var(--c-muted)"},DP={running:"⠋",success:"✓",failed:"✕"},FP={running:"var(--c-accent)",success:"var(--c-ok)",failed:"var(--c-danger)"};function Ml({node:e}){let{toolName:t,category:n,status:o,duration:r,resultSummary:s,error:a}=Z_(e.data),c=W_[n]??W_.other,l=DP[o]??"◌",u=FP[o]??"var(--c-muted)",p=o==="running",d=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:p?"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(--font-code)",fontSize:"11px",fontWeight:600,color:c,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t},void 0,!1,void 0,this),d&&i("div",{style:{fontSize:"10px",color:a?"var(--c-danger)":"var(--c-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1.3},children:d},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)}var BP=new Set(["png","jpg","jpeg","gif","svg","webp","bmp","ico","avif"]),HP=new Set(["md","mdx","markdown"]);function jP(e){let t=e.split(".").pop()?.toLowerCase()??"";if(BP.has(t))return"image";if(HP.has(t))return"markdown";return"file"}async function $i(e,t,n){let o=Oe.value,r=400,s=300,a=20,c=Math.ceil(Math.sqrt(e.length));for(let l=0;l<e.length;l++){let u=e[l],p=l%c,d=Math.floor(l/c),m=t-c*420/2+p*420,f=n-150+d*320,h=jP(u.name),v=u.name;if(/\.(pdf|pptx?|xlsx?|docx?|od[pts])$/i.test(v)){if(!o||u.size===0||u.size>20971520){on("remove","File not attached","Open a board and choose a nonempty file under 20 MiB.");continue}let x=new URLSearchParams({boardId:o,name:v,mime:u.type,x:String(m),y:String(f)});on("context","Attaching document",v),await ne("attachDocument",`/api/canvas/attachments?${x}`,null,{method:"POST",body:u});continue}if(Oe.value!==o)return;if(h==="image"){let x=new FileReader,g=await new Promise((b)=>{x.onload=()=>b(x.result),x.readAsDataURL(u)});if(Oe.value!==o)return;await On({type:"image",title:v,content:g,x:m,y:f,width:400,height:300,...o?{boardId:o}:{}})}else{let x=await u.text();if(Oe.value!==o)return;let g=h==="markdown"||h==="file";await On({type:h,title:v,content:x,x:m,y:f,width:g?720:400,height:g?500:300,...o?{boardId:o}:{}})}}}var q_={width:260,height:150},UP={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 fm(e){return!!e&&e in Nt}function bo(e){if(!e)return null;let t=F.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 mm(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Js(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 G_(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 hm({intent:e}){let t=fm(e.nodeType)?Bn(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:()=>wi.value=e.id,onMouseLeave:()=>{if(wi.value===e.id)wi.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(),br(e)},children:i(Ve,{size:14},void 0,!1,void 0,this)},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 V_({intent:e,rect:t}){let n=fm(e.nodeType)?Bn(e.nodeType):null,o=fm(e.nodeType)?Nt[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:Js(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(hm,{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:Js(e)},children:[n==="edit"&&i("div",{class:"intent-edit-bar"},void 0,!1,void 0,this),i(hm,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ZP(e){let t=e.phase==="settling"?bo(e.settledNodeId):null;switch(e.kind){case"create":{if(!e.position)return null;let n=e.nodeType&&UP[e.nodeType]||q_,o=t??{left:e.position.x,top:e.position.y,...n};return i(V_,{intent:e,rect:o},e.id,!1,void 0,this)}case"move":{if(!e.position)return null;let o=bo(e.nodeId)??q_,r=t??{left:e.position.x,top:e.position.y,width:o.width,height:o.height};return i(V_,{intent:e,rect:r},e.id,!1,void 0,this)}case"remove":{let n=t??bo(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??bo(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=bo(e.edge.from),o=bo(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:Js(e)},children:i(hm,{intent:e},void 0,!1,void 0,this)},e.id,!1,void 0,this)}default:return null}}function K_(){let e=Array.from(lt.value.values());if(H(()=>{function t(n){if(n.key!=="Escape")return;let o=wi.value;if(!o)return;let r=lt.value.get(o);if(!r||r.phase!=="forming")return;n.stopImmediatePropagation(),n.preventDefault(),br(r)}return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[]),e.length===0)return null;return i("div",{class:"intent-layer",onAnimationEnd:(t)=>{if(t.animationName!=="intent-settle"&&t.animationName!=="intent-dissolve")return;let n=t.target.dataset.intentId;if(n&&lt.value.get(n)?.phase!=="forming")Er(n)},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=bo(t.edge.from),o=bo(t.edge.to);if(!n||!o)return null;return i("path",{d:G_(mm(n),mm(o)),class:`intent-edge type-${t.edge.type}`,style:{opacity:Js(t)}},`line-${t.id}`,!1,void 0,this)}if(t.kind==="move"&&t.position){let n=bo(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:G_(mm(n),r),class:"intent-trail",markerEnd:"url(#intent-arrow)",style:{opacity:Js(t)}},`line-${t.id}`,!1,void 0,this)}return null})]},void 0,!0,void 0,this),e.map(ZP)]},void 0,!0,void 0,this)}var J_=32000;var $l="Agent session";function Y_(e){return e.some((t)=>t.attached)}function Q_(e){return e.filter((t)=>!t.attached)}function Jo(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"}}var It=K([]),gm=K({used:0,total:J_}),Yo=K([]),Rr=K(!1),Oi=K(!1),vm=K(null);function An(e){return It.value.find((n)=>n.sessionId===e)?.parentAgentId?"var(--c-subagent)":"var(--c-agent)"}function eS(e){return(e.trim().replace(/^[^a-z0-9]+/i,"").charAt(0)||e.trim().charAt(0)||"?").toUpperCase()}function Ol(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 _t=Ge(()=>Y_(It.value)),ym=Ge(()=>Q_(It.value)),tS=Ge(()=>{let e=new Set;return[...It.value].filter((t)=>t.label!==$l).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))}),nS=Ge(()=>It.value.filter((e)=>e.attached)),Li=Ge(()=>It.value.find((e)=>e.attached)??null);function WP(e){let t=new Set;for(let n of e)if(n.nodeId&&n.kind!=="create")t.add(n.nodeId);return t}var Ll=Ge(()=>WP(lt.value.values()));function Dl(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 bm(e){if(!e)return;if(Array.isArray(e.presences))It.value=e.presences;if(e.budget&&Number.isFinite(e.budget.used)&&Number.isFinite(e.budget.total))gm.value={used:e.budget.used,total:e.budget.total};if(Array.isArray(e.activity))Yo.value=e.activity}function oS(){let e=L(new Map),t=oe.value.scale,n=F.value,o=1/Math.max(0.05,t),r=It.value.map((s)=>{let a=Dl(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.cursor?" has-explicit-cursor":""}${s.attached?"":" is-external"}${s.parentAgentId?" is-worker":""}`,"data-session-id":s.sessionId,style:{transform:`translate(${a.x}px, ${a.y}px)`,"--identity-color":An(s.sessionId)},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:Jo(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 xo(e=1000){let[t,n]=A(()=>Date.now());return H(()=>{if(e<=0)return;n(Date.now());let o=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(o)},[e]),t}function rS(){let e=xo(Os.value.length>0?5000:0),t=Os.value.filter((o)=>o.cursor!==null&&(!o.lastSeenAt||e-Date.parse(o.lastSeenAt)<Ow+5000));if(t.length===0)return null;let n=1/Math.max(0.05,oe.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 Fl(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 wm(){let e=Dn.value;return e&&typeof e==="object"?e:{}}var iS=Ge(()=>wm().workItems??[]),_m=Ge(()=>wm().approvalGates??[]),Mr=Ge(()=>_m.value.filter((e)=>e.status==="pending")),Qo=Ge(()=>{let e=wm().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 sS(e){return(await mn("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 aS=Ge(()=>_m.value.filter((e)=>e.status==="held")),cS=Ge(()=>_m.value.filter((e)=>e.status==="approved"||e.status==="rejected")),lS=K({events:[],evidence:[],steering:[]}),$r=K("all");function Sm(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 qP=new Set(["api","mcp","sdk","cli"]);function xm(e,t){if(e?.trim())return e.trim();let n=t?.trim();if(n&&!qP.has(n))return n;return null}var GP=/^(node|edge|group|annotation|jsonrender|graph|render)\.|^arrange$|^canvas\.clear$|^snapshot\.restore$/,uS=K(null),ea=K(new Set),VP={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 XP(e,t=40,n=[],o=null,r="all"){let s=n.find((l)=>GP.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,...!Se()&&o?.actor==="agent"&&s?.id===l.id?{undoable:!0}:{}})),...e.events.map((l)=>({id:`event-${l.id}`,kind:l.kind,label:VP[l.kind]??l.kind,body:l.detail?`${l.summary} — ${l.detail}`:l.summary,createdAt:l.createdAt,who:xm(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:xm(l.agentId,l.source)})),...e.steering.map((l)=>{let u=l.agentId??(l.source&&l.source!=="browser"?l.source:null),p=l.target?`→ ${l.target} · `:u?"→ all · ":"",d=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} `:""}${p}${l.message}${d}`,createdAt:l.createdAt,who:xm(l.agentId,l.source)}})],c=r==="all"?a:a.filter((l)=>Sm(l.kind)===r);return c.sort((l,u)=>l.createdAt<u.createdAt?1:l.createdAt>u.createdAt?-1:0),c.slice(0,t)}var dS=Ge(()=>XP(lS.value,40,Yo.value,uS.value,$r.value));async function er(){let[e,t]=await Promise.all([ne("refreshTimeline","/api/canvas/ax/timeline?limit=40",null),ne("refreshHistoryTop","/api/canvas/history",null)]);if(t)uS.value=t.top??null;if(!e)return;lS.value={events:Array.isArray(e.events)?e.events:[],evidence:Array.isArray(e.evidence)?e.evidence:[],steering:Array.isArray(e.steering)?e.steering:[]}}async function km(e){if(!(await mn("undoAgentEdit","/api/canvas/undo",{method:"POST"})).ok)return!1;return ea.value=new Set([...ea.value,e.id]),await $n("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"})}),er(),!0}async function Tm(e=!1){if(Se())return on("remove","Undo / redo unavailable","Open the local PMX workbench to use shared history."),!1;let t=await mn(e?"redo":"undo",e?"/api/canvas/redo":"/api/canvas/undo",{method:"POST"});if(t.ok)er();return t.ok}async function pS(e,t){if(!(await mn("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 $n("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 mS(e){return(await mn("reopenGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/reopen`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser"})})).ok}async function fS(e,t){return(await mn("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 tr(){return(await mn("startSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser",label:$l,attached:!0,phase:"idle"})})).ok}async function Bl(e){return(await mn("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}function Ys(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let n=t;if(typeof n.id!=="string"||typeof n.title!=="string")return[];return[{id:n.id,title:n.title,...typeof n.reason==="string"?{reason:n.reason}:{}}]})}var nr=K(null);function Cm(e){let t=Di.value?.context;nr.value=e&&t?new Set([...t.read,...t.pinned,...t.created,...t.edited].map((n)=>n.id)):null}var Di=K(null);function Qs(e,t){let n=new Set(e.map((o)=>o.id));return[...e,...t.filter((o)=>!n.has(o.id))]}function KP(e,t){return{labels:[...new Set([...e.labels,...t.labels])],sessions:e.sessions+1,endedAt:t.endedAt,endedBy:e.endedBy===t.endedBy?t.endedBy:void 0,counts:t.counts,snapshot:null,context:{read:Qs(e.context.read,t.context.read),pinned:Qs(e.context.pinned,t.context.pinned),created:Qs(e.context.created,t.context.created),edited:Qs(e.context.edited,t.context.edited),changedSinceRead:Qs(e.context.changedSinceRead,t.context.changedSinceRead)}}}function hS(e){let{counts:t,snapshot:n,context:o}=e;if(typeof e.label!=="string"||typeof e.endedAt!=="string")return;if(e.unchanged===!0||typeof e.parentAgentId==="string")return;let r={labels:[e.label],sessions:1,endedAt:e.endedAt,endedBy:e.endedBy==="human"||e.endedBy==="agent"||e.endedBy==="idle-timeout"?e.endedBy:void 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,context:{read:Ys(o?.read),pinned:Ys(o?.pinned),created:Ys(o?.created),edited:Ys(o?.edited),changedSinceRead:Ys(o?.changedSinceRead)}},s=Di.value;if(Di.value=s?KP(s,r):r,s&&nr.value)Cm(!0)}function Hl(){Di.value=null,nr.value=null}function gS(){if(!_t.value)return null;let e=Qo.value;if(!e)return null;let t=F.value,n=e.nodeIds.map((s)=>t.get(s)).filter((s)=>s!==void 0),o=Fl(n,e.padding);if(!o)return null;let r=1/Math.max(0.05,oe.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 vS=K(new Map),ta=K({});function Em(e){vS.value=new Map((e.nodes??[]).map((t)=>[t.nodeId,t])),ta.value=e.pins??{}}async function jl(){let e=await ne("fetchContextStatus","/api/canvas/ax/context-status",{});if(e.ok&&e.boardId===Oe.value)Em(e)}function yS(e,t){let n=vS.value.get(e),o=ta.value[e]?.pinnedAt;if(!n||o&&n.lastReadAt<o)return{kind:"not-read"};if(t>n.readRevision)return{kind:"changed",by:n.lastReadBy,at:n.lastReadAt};return{kind:"read",by:n.lastReadBy,at:n.lastReadAt,count:n.readCount}}function Ul(e){return e.agentId?.trim()||e.source}var bS="",xS=new Map,wS=Ge(()=>{let e=Le.value,t=new Map;if(e.size>0){let o=new Map;for(let r of wd([...F.value.values()],e)){let s=r.pinnedNodeTitle??r.pinnedNodeId;for(let a of r.neighbors){let c=o.get(a.id)??[];c.push({pinNodeId:r.pinnedNodeId,pinTitle:s,distance:a.distance}),o.set(a.id,c)}}for(let[r,s]of o)s.sort((a,c)=>a.distance-c.distance),t.set(r,s.map(({pinNodeId:a,pinTitle:c})=>({pinNodeId:a,pinTitle:c})))}let n=[...t].sort(([o],[r])=>o.localeCompare(r)).map(([o,r])=>`${o}:${r.map((s)=>`${s.pinNodeId}=${s.pinTitle}`).join(",")}`).join("|");if(n===bS)return xS;return bS=n,xS=t,t});function Qe({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)}var Zl={eye:"M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12zM12 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5",eyeOff:"M3 3l18 18M10.6 6.1A10 10 0 0 1 12 6c6.5 0 10 6 10 6a17 17 0 0 1-3 3.6M6.6 6.6C3.8 8.3 2 12 2 12s3.5 6 10 6a9.6 9.6 0 0 0 4.4-1",spark:"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z",pen:"M4 20l4.2-1L19 8.2 15.8 5 5 15.8z",warn:"M12 4l9 16H3zM12 10v4M12 17v.5"};function _S(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function JP(e,t){if(t){let n=ta.value[e.id],o=n?.pinnedBy.actor==="agent"?` Pinned by ${Ul(n.pinnedBy)}${n.reason?`: ${n.reason}`:""}.`:"",r=yS(e.id,e.contentRevision??0);if(r.kind==="not-read")return{tone:"muted",glyph:"eyeOff",word:"not read",label:"Not read yet",body:`In context, but no agent has loaded it since it was pinned.${o}`};if(r.kind==="changed")return{tone:"warn",glyph:"warn",word:"changed since read",label:"The agent's copy is out of date",body:`Changed after ${r.by} read it at ${_S(r.at)}.${o}`};return{tone:"agent",glyph:"eye",word:"read",label:"Read by the agent",body:`${r.count>1?`Read ${r.count} times · last`:"Read"} ${_S(r.at)} by ${r.by}.${o}`}}if(e.lastEditedBy?.actor==="human")return null;if(e.createdBy?.actor==="agent"){let n=Ul(e.createdBy);return{tone:"agent",glyph:"spark",word:`by ${n}`,label:`Created by ${n}`,body:"The byline stays until you edit the node."}}if(e.lastEditedBy?.actor==="agent")return{tone:"agent",glyph:"pen",word:"edited",label:`Edited by ${Ul(e.lastEditedBy)}`,body:"The mark stays until you edit the node."};return null}function SS({node:e,pinned:t}){let n=JP(e,t);if(!n)return null;return i(Qe,{label:n.label,body:n.body,align:"end",tapToOpen:!0,children:i("span",{class:`node-context-mark is-${n.tone}`,"data-mark":n.word,children:[i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:i("path",{d:Zl[n.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),n.word]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function kS(e){return ta.value[e]?.pinnedBy.actor==="agent"}function TS({node:e,pinned:t}){let[n,o]=A(!1),r=t?void 0:wS.value.get(e.id);if(!r||r.length===0)return null;let s=r.length>1?`near ${r.length}`:"near",a=n?r.map((c)=>{let l=F.value.get(c.pinNodeId);return l?`“${c.pinTitle}” (${Math.round(xd(e,l))} px)`:`“${c.pinTitle}”`}).join(", "):"";return i(Qe,{label:n?`Near ${a}`:"Near a pin",body:"The agent gets its title and a short summary, not its full content. Pin it to send its content.",align:"end",tapToOpen:!0,children:i("span",{class:"node-near-mark","data-near":r.map((c)=>c.pinNodeId).join(" "),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocusIn:()=>o(!0),onFocusOut:()=>o(!1),children:[i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[i("circle",{cx:"12",cy:"12",r:"8",class:"node-near-ring"},void 0,!1,void 0,this),i("circle",{cx:"12",cy:"12",r:"2.2",class:"node-near-dot"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function YP(e){let t=typeof e==="number"&&Number.isFinite(e)?Math.floor(e):1;return Math.max(1,Math.min(20,t))}function Wl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function na(e){return typeof e==="string"&&e.length>0}function CS(e){let t=e.axStep;if(!Wl(t))return null;if(!na(t.flowId)||!na(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 ES(e){let t=e.axFlow;if(!Wl(t)||!na(t.flowId)||!Array.isArray(t.steps))return null;let n=[];for(let r of t.steps){if(!Wl(r)||!na(r.nodeId)||!na(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=Wl(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:YP(o.maxRuns)}}}var QP={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)"},IS={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},PS={fontSize:"10px",color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginRight:"auto"},NS={...Tr,background:"color-mix(in srgb, var(--c-accent) 25%, transparent)",color:"var(--c-text)"},eN=[{status:"in-progress",label:"Start",toast:"Step started"},{status:"done",label:"Done",toast:"Step done"},{status:"blocked",label:"Blocked",toast:"Step blocked"}];async function AS(e,t,n){let o={...t,loop:n};fe(e.id,{axFlow:o}),await kt(e.id,{data:{axFlow:o}})}function zS(e){return typeof e?.axWorkStatus==="string"?e.axWorkStatus:"todo"}function tN({node:e,flow:t}){let[n,o]=A(""),{running:r,run:s,maxRuns:a}=t.loop,c=async()=>{await AS(e,t,{running:!0,run:s>=a?0:s,maxRuns:a});let u=t.steps.find((d)=>zS(F.value.get(d.nodeId)?.data)!=="done"),p=u??t.steps[t.steps.length-1];await Uo(e,"ax.work.update",{id:p.workItemId,status:u?"in-progress":"done"},"Loop running")},l=async()=>{let u=n.trim();if(!u)return;await Uo(e,"ax.steer",{message:u},"Steering sent"),o("")};return i("div",{class:"ax-flow-controls",style:{...IS,marginTop:"6px",rowGap:"4px"},children:[i("span",{class:"ax-flow-runs",style:PS,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:NS,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(),AS(e,t,{...t.loop,running:!1})},children:"Stop"},void 0,!1,void 0,this):i("button",{type:"button",class:"ax-node-action",style:Tr,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:Tr,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 ql({node:e}){let t=CS(e.data);if(!t)return null;let n=ES(e.data),o=zS(e.data);return i("div",{class:"ax-step-dock",style:QP,children:[i("div",{class:"ax-step-controls",style:IS,children:[i("span",{class:"ax-step-position",style:PS,children:["Step ",t.index,"/",t.total]},void 0,!0,void 0,this),eN.map((r)=>i("button",{type:"button",class:"ax-node-action","aria-pressed":o===r.status,style:o===r.status?NS:Tr,title:`Set this step's work item to "${r.status}".`,onClick:(s)=>{s.stopPropagation(),Uo(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(tN,{node:e,flow:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Fi=8,Or=K(null),Bi=[],Hi=[],$S=null;function RS(e){let t=e?.data.parentGroup;return typeof t==="string"&&t.length>0?t:null}function MS(e){if(!e||!Array.isArray(e.data.children))return[];return e.data.children.filter((t)=>typeof t==="string")}function nN(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=RS(r);while(s&&!o.has(s))o.add(s),s=RS(n.get(s));if(r.type!=="group")return o;let a=[...MS(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(...MS(l))}return o}function OS(e,t){Bi=[],Hi=[],$S=e;let n=Array.from(t),o=nN(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,p=r.position.y+r.size.height/2;Bi.push({val:s,minY:l,maxY:u}),Bi.push({val:a,minY:l,maxY:u}),Bi.push({val:c,minY:l,maxY:u}),Hi.push({val:l,minX:s,maxX:a}),Hi.push({val:u,minX:s,maxX:a}),Hi.push({val:p,minX:s,maxX:a})}}function LS(){Bi=[],Hi=[],$S=null}function DS(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=Fi+1,p=null;for(let v=0;v<3;v++){let x=r[v];for(let g of Bi){let b=Math.abs(x-g.val);if(b<u)u=b,l=g.val-a[v],p={axis:"x",pos:g.val,from:Math.min(g.minY,t),to:Math.max(g.maxY,t+o)}}}let d=null,m=Fi+1,f=null;for(let v=0;v<3;v++){let x=s[v];for(let g of Hi){let b=Math.abs(x-g.val);if(b<m)m=b,d=g.val-c[v],f={axis:"y",pos:g.val,from:Math.min(g.minX,e),to:Math.max(g.maxX,e+n)}}}let h=[];if(p&&u<=Fi)h.push(p);if(f&&m<=Fi)h.push(f);return{x:l!==null&&u<=Fi?l:e,y:d!==null&&m<=Fi?d:t,guides:h}}function FS({nodeId:e,viewport:t,onMove:n,onDragEnd:o,onClick:r}){let s=L(!1),a=L({x:0,y:0}),c=L({x:0,y:0});return j((u,p,d)=>{u.stopPropagation(),u.preventDefault(),s.current=!0,document.documentElement.classList.add("is-node-dragging"),window.getSelection()?.removeAllRanges(),a.current={x:u.clientX,y:u.clientY},c.current={x:p,y:d};let m=null,f=null,h=!1,v=()=>{if(f=null,!s.current||!m)return;let b=m;m=null;let I=t.value.scale,R=(b.x-a.current.x)/I,M=(b.y-a.current.y)/I;n(e,c.current.x+R,c.current.y+M)},x=(b)=>{if(!s.current)return;if(!h&&Math.hypot(b.clientX-u.clientX,b.clientY-u.clientY)<4)return;if(h=!0,m={x:b.clientX,y:b.clientY},f!==null)return;f=window.requestAnimationFrame(v)},g=(b)=>{if(f!==null)window.cancelAnimationFrame(f),v();if(s.current=!1,document.documentElement.classList.remove("is-node-dragging"),document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",g),document.removeEventListener("pointercancel",g),o(),!h&&b.type==="pointerup")r?.()};document.addEventListener("pointermove",x),document.addEventListener("pointerup",g),document.addEventListener("pointercancel",g)},[e,t,n,o,r])}var oN=200,rN=100;function BS({nodeId:e,viewport:t,onResize:n,onResizeEnd:o}){let r=L(!1),s=L({x:0,y:0}),a=L({w:0,h:0});return j((l,u,p)=>{l.stopPropagation(),l.preventDefault(),r.current=!0,s.current={x:l.clientX,y:l.clientY},a.current={w:u,h:p},document.documentElement.classList.add("is-node-resizing");let d=null,m=null,f=()=>{if(m=null,!r.current||!d)return;let x=d;d=null;let g=t.value.scale,b=(x.x-s.current.x)/g,I=(x.y-s.current.y)/g;n(e,Math.max(oN,a.current.w+b),Math.max(rN,a.current.h+I))},h=(x)=>{if(!r.current)return;if(d={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(f)},v=()=>{if(m!==null)window.cancelAnimationFrame(m),f();r.current=!1,document.documentElement.classList.remove("is-node-resizing"),document.removeEventListener("pointermove",h),document.removeEventListener("pointerup",v),document.removeEventListener("pointercancel",v),o()};document.addEventListener("pointermove",h),document.addEventListener("pointerup",v),document.addEventListener("pointercancel",v)},[e,t,n,o])}var iN={ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1}};function sN(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,p=l*t.dx+u*t.dy;if(p<=0)continue;let d=Math.abs(l*t.dy)+Math.abs(u*t.dx);if(d>p)continue;let m=p+d*2;if(m<a)a=m,s=c}return s}var aN=0.4,cN=0.55,lN=175;function uN(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*aN/Si);if(Number.isFinite(n)&&n>0)r=Math.min(r,n*cN/lN);return Math.max(1,r)}function HS({node:e,children:t,onContextMenu:n}){let o=je.value===e.id,r=Ne.value.has(e.id),s=Le.value.has(e.id),a=oc.value.has(e.id),c=!o&&zb.value.has(e.id),l=uo.value,u=l!==null&&l.has(e.id),p=l!==null&&!l.has(e.id),[d,m]=A(!1),f=L(null),h=j((T,ce,pe)=>{let me=DS(ce,pe,e.size.width,e.size.height),qt=F.value.get(T);if(qt?.position.x===me.x&&qt.position.y===me.y){Or.value=me.guides.length>0?me.guides:null;return}wt(T,{position:{x:me.x,y:me.y}}),Or.value=me.guides.length>0?me.guides:null,Lb(T)},[e.size.width,e.size.height]),v=L(null),x=j(()=>{if(LS(),Or.value=null,Ap(null),v.current)document.removeEventListener("keydown",v.current),v.current=null;Tt();let T=Xn.value;if(Ob(),!T||T.nodeId!==e.id)return;if(T.mode==="add")$d(T.groupId,[e.id]);else{let ce=F.value.get(T.groupId),pe=Array.isArray(ce?.data.children)?ce.data.children.filter((me)=>typeof me==="string"&&me!==e.id):[];yc(T.groupId,pe)}},[e.id]),g=FS({nodeId:e.id,viewport:oe,onMove:h,onDragEnd:x,onClick:()=>{Ne.value=new Set([e.id])}}),b=j((T,ce,pe)=>{let me=F.value.get(T);if(me?.size.width===ce&&me.size.height===pe)return;wt(T,{size:{width:ce,height:pe}})},[]),I=j(()=>{fe(e.id,{userResized:!0}),kt(e.id,{data:{userResized:!0}}),Tt()},[e.id]),R=BS({nodeId:e.id,viewport:oe,onResize:b,onResizeEnd:I}),M=j((T)=>{T.stopPropagation(),T.preventDefault(),Ye.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]),_=j((T)=>{if(T.button!==0)return;if(d)return;if(T.target instanceof Element&&T.target.closest("button, input")){T.stopPropagation();return}if(Qt.value==="connect"){M(T);return}if(T.shiftKey){T.stopPropagation(),Dd(e.id);return}if(mo(e.id),Ap(e.id),Ww(e.id,typeof e.data.title==="string"&&e.data.title?e.data.title:e.type),OS(e.id,F.value.values()),e.type!=="group"){let ce=(pe)=>{if(pe.key==="Escape")$b()};v.current=ce,document.addEventListener("keydown",ce)}g(T,e.position.x,e.position.y)},[e.id,e.type,e.data.title,e.position.x,e.position.y,g,d,M]),N=j((T)=>{if(T.button!==0)return;if(T.stopPropagation(),Qt.value==="connect"){M(T);return}if(T.shiftKey){Dd(e.id);return}mo(e.id)},[e.id,M]),w=j((T)=>{if((T.target instanceof Element?T.target:null)?.closest('button, input, textarea, select, a, [contenteditable="true"]'))return;if(n)n(T,e.id)},[n,e.id]),k=j((T)=>{let ce=T.target;if(ce&&ce!==T.currentTarget&&ce.closest('input, textarea, [contenteditable="true"]'))return;let pe=iN[T.key];if(pe){T.preventDefault();let me=sN(e,pe,F.value.values());if(!me)return;mo(me.id),requestAnimationFrame(()=>{document.querySelector(`.canvas-node[data-node-id="${CSS.escape(me.id)}"]`)?.focus()})}else if(T.key==="Enter"&&T.target===T.currentTarget&&ms.has(e.type))T.preventDefault(),kn(e.id)},[e]),z=e.data.title||(e.type==="file"?(e.data.path||e.data.content||"").split(/[\\/]/).pop()??"":"")||Nt[e.type],X=j((T)=>{let ce=T.trim();if(ce&&ce!==z)fe(e.id,{title:ce}),kt(e.id,{title:ce});m(!1)},[e.id,z]),W=L(null),J=L(!1),G=L(null);H(()=>{if(J.current||!Ip(e))return;let T=W.current;if(!T)return;let ce=new ResizeObserver(()=>{if(J.current){ce.disconnect();return}let pe=T.scrollHeight,me=Kw(e,pe);if(me===null)return;if(Math.abs(me-e.size.height)>8){if(Cc(e.id,{width:e.size.width,height:me}),G.current!==null)window.clearTimeout(G.current);G.current=window.setTimeout(()=>{Tt({recordHistory:!1}),G.current=null},0)}J.current=!0,ce.disconnect()});return ce.observe(T),()=>{if(ce.disconnect(),G.current!==null)window.clearTimeout(G.current),G.current=null}},[e.id,e.type,e.data.mode,e.data.strictSize,e.collapsed,e.size.width,e.size.height]);let S=e.pinned,q=e.type==="trace",ie=q&&e.data.status==="running",ye=e.type==="group",ue=e.data.strictSize===!0,Pe=Math.max(oe.value.scale,0.01),ke=uN(Pe,e.collapsed?0:e.size.height,e.size.width),Me=ye&&e.data.color?e.data.color:void 0,cn={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":ke.toFixed(3),"--node-port-scale":(1/Pe).toFixed(3),...Me?{"--group-color":Me}:{}},Pn=_t.value&&Ll.value.has(e.id),D=["canvas-node",o?"active":"",c?"neighbor":"",u?"search-match":"",p?"search-dimmed":"",r?"selected":"",s?"context-pinned":"",a?"attention-pulse":"",S?"pinned":"",q?"trace-node":"",ie?"trace-running":"",ye?"group-node":"",ue?"strict-size":"",Pn?"agent-mutating":"",nr.value&&!nr.value.has(e.id)?"lens-dimmed":""].filter(Boolean).join(" "),Y=ye?(Array.isArray(e.data.children)?e.data.children:[]).filter((T)=>typeof T==="string"&&F.value.has(T)):[],[Te,de]=A(!1),be=Xn.value,se=ye&&be?.groupId===e.id&&be.mode==="add",re=ye&&be?.groupId===e.id&&be.mode==="remove",Z=Ye.value?.targetId===e.id,xe=ye?[...new Set(Y.map((T)=>F.value.get(T)?.type).filter((T)=>!!T))].slice(0,4):[];if(ye&&e.collapsed)return i("div",{class:`${D} group-chip`,"data-node-type":e.type,style:{...cn,width:"auto",height:"auto"},onPointerDown:N,onDblClick:w,title:"Expand group","data-testid":"group-chip",children:i("div",{class:"node-titlebar group-chip-inner",onPointerDown:_,children:[i("button",{type:"button",class:"group-chip-expand","aria-label":`Expand group ${z}`,onClick:(T)=>{T.stopPropagation(),Ss(e.id)},children:i(ks,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"group-chip-text",children:[i("div",{class:"group-chip-name",children:z},void 0,!1,void 0,this),i("div",{class:"group-chip-meta",children:[xe.map((T)=>i("span",{class:"group-kind-dot","aria-hidden":"true"},T,!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:`${D}${se?" is-drop-target":""}${re?" is-drop-source":""}${Z?" is-edge-target":""}${ye&&Te?" group-menu-open":""}`,"data-node-type":e.type,"data-node-id":e.id,style:cn,tabIndex:o?0:-1,onKeyDown:k,onPointerDown:N,onMouseDown:(T)=>{if(T.shiftKey)T.preventDefault()},onDblClick:w,children:[i("div",{class:"node-content",children:[ye&&i("div",{class:"node-titlebar group-edge-row",onPointerDown:_,children:[i("span",{class:"group-name-pill",children:[d?i("input",{ref:f,class:"node-title-input group-title-input",value:z,onBlur:(T)=>X(T.target.value),onKeyDown:(T)=>{if(T.key==="Enter")X(T.target.value);if(T.key==="Escape")m(!1)},onClick:(T)=>T.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"group-name",title:z,children:z},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":`${z} actions`,children:[i("button",{type:"button",class:"group-action",title:"Auto-arrange children","aria-label":"Auto-arrange children",disabled:Y.length===0,onClick:(T)=>{T.stopPropagation(),$d(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:(T)=>{T.stopPropagation(),Ss(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":Te,onClick:(T)=>{T.stopPropagation(),de((ce)=>!ce)},children:i(qd,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),Te&&i("div",{class:"group-menu",role:"menu",onPointerDown:(T)=>T.stopPropagation(),children:[i("button",{type:"button",role:"menuitem",onClick:(T)=>{T.stopPropagation(),de(!1),m(!0),requestAnimationFrame(()=>f.current?.focus())},children:"Rename"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",onClick:(T)=>{T.stopPropagation(),de(!1),Do(e.id),si(e.id)},children:"Ungroup"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",disabled:Y.length===0,onClick:(T)=>{T.stopPropagation(),de(!1),Sc(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),!ye&&i("div",{class:"node-titlebar",onPointerDown:_,children:[i("span",{class:"node-type-icon","aria-hidden":"true",children:(()=>{let T=Bn(e.type);return i(T,{size:Math.round(14*ke)},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),d?i("input",{ref:f,class:"node-title-input",value:z,onBlur:(T)=>X(T.target.value),onKeyDown:(T)=>{if(T.key==="Enter")X(T.target.value);if(T.key==="Escape")m(!1)},onClick:(T)=>T.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"node-title",title:z,children:z},void 0,!1,void 0,this),i(TS,{node:e,pinned:s},void 0,!1,void 0,this),i(SS,{node:e,pinned:s},void 0,!1,void 0,this),i("div",{class:"node-controls",children:[S&&i("span",{class:"pin-indicator",title:"Pinned",children:"⊙"},void 0,!1,void 0,this),ms.has(e.type)&&i("button",{type:"button",onClick:(T)=>{T.stopPropagation(),kn(e.id)},title:"Expand (focus mode)",children:i(ix,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:`ctx-pin-btn${s?" ctx-pin-active":""}`,onClick:(T)=>{T.stopPropagation(),Jn(e.id)},title:s?"Remove from context":"Add to context","aria-label":s?"Remove from context":"Add to context","aria-pressed":s,children:i("span",{class:"ctx-pin-mark",children:[i($c,{},void 0,!1,void 0,this),s&&kS(e.id)&&i("span",{class:"ctx-pin-agent-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"node-hover-control",onClick:(T)=>{T.stopPropagation(),n?.(T,e.id)},title:"More actions","aria-label":"More actions",children:i(qd,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"node-hover-control",onClick:(T)=>{T.stopPropagation(),Oo(e.id)},title:"Close",children:i(Ve,{size:14},void 0,!1,void 0,this)},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(ql,{node:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&i("div",{class:"node-resize-handle",onPointerDown:(T)=>R(T,e.size.width,e.size.height)},void 0,!1,void 0,this),r&&["tl","tr","bl","br"].map((T)=>i("span",{class:`node-selection-handle is-${T}`,"aria-hidden":"true"},T,!1,void 0,this)),Ar.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),Ar.value.get(e.id)," took over — agent yielded"]},void 0,!0,void 0,this),!ye&&["top","right","bottom","left"].map((T)=>i("div",{class:`node-port node-port-${T}`,onPointerDown:(ce)=>{if(ce.button!==0)return;ce.stopPropagation(),ce.preventDefault(),ce.currentTarget.setPointerCapture(ce.pointerId);let pe=e.position.x+e.size.width/2,me=e.position.y+e.size.height/2,qt=e.size.width/2,St=e.size.height/2,Gt,yn;switch(T){case"top":Gt=pe,yn=me-St;break;case"bottom":Gt=pe,yn=me+St;break;case"left":Gt=pe-qt,yn=me;break;case"right":Gt=pe+qt,yn=me;break}Ye.value={fromId:e.id,fromX:Gt,fromY:yn,cursorX:Gt,cursorY:yn}}},T,!1,void 0,this))]},void 0,!0,void 0,this)}function Gl({node:e}){let t=typeof e.data.boardId==="string"?e.data.boardId:"",n=rn.value.find((o)=>o.id===t);return i("div",{class:"board-node",children:[i("div",{class:"board-node-content",children:[i("div",{class:"board-node-label",children:"Linked board"},void 0,!1,void 0,this),i("strong",{class:"board-node-title",children:n?.name??"Missing board"},void 0,!1,void 0,this),i("div",{class:"board-node-meta",children:n?`${n.nodeCount} nodes`:t||"No target id"},void 0,!1,void 0,this),n?.summary&&i("p",{class:"board-node-summary",children:n.summary},void 0,!1,void 0,this),!!n?.pinnedTitles?.length&&i("p",{class:"board-node-meta",children:["Pinned: ",n.pinnedTitles.map((o)=>o.title).join(", ")]},void 0,!0,void 0,this),!!n?.backlinks?.length&&i("p",{class:"board-node-meta",children:["Linked from: ",[...new Set(n.backlinks.map((o)=>o.title))].join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("button",{class:"board-node-open",type:"button",disabled:!n,onClick:()=>n&&void sn(n.id),children:[n?"Open board":"Target unavailable",n&&i(jo,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var dN={relation:"var(--c-muted)","depends-on":"var(--c-rel-informs)",flow:"var(--c-accent)",references:"var(--c-muted)"},pN=new Set(["depends-on","flow"]);function mN(e){if(!Number.isFinite(e)||e<=0)return 1;return e<1?1/e:1}function fN(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 Vl(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,p=Math.abs(c/(a||0.001)),d=u/(l||0.001);if(p>d){let f=c>0?1:-1;return{x:n+u/p*(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+p*l*(c>0?1:-1),side:m>0?"right":"left"}}function Xl(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 hN(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 gN({edge:e,fromNode:t,toNode:n,focused:o,dimmed:r,selected:s,scale:a,onContextMenu:c}){let l=Vl(t,n),u=Vl(n,t),p=u.x-l.x,d=u.y-l.y,m=Math.sqrt(p*p+d*d),f=Math.min(Math.max(m*0.35,32),160),h=Xl(l,f),v=Xl(u,f),x=`M ${l.x} ${l.y} C ${h.x} ${h.y}, ${v.x} ${v.y}, ${u.x} ${u.y}`,g=dN[e.type],b=pN.has(e.type),I=fN(e,a),R=Math.min(a,2.2),M=e.label&&a<=3.4?hN(l.x,l.y,h.x,h.y,v.x,v.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:(N)=>{N.stopPropagation(),Kn.value=e.id},onDblClick:c?(N)=>c(N,e.id):void 0},void 0,!1,void 0,this),(o||s)&&i("path",{d:x,fill:"none",stroke:g,"stroke-width":6*a,"stroke-dasharray":I,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:g,"stroke-width":(s?3:o?2.5:1.5)*a,"stroke-dasharray":I,"marker-end":b?"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:g,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),M&&e.label&&i("g",{transform:`translate(${M.x}, ${M.y})`,children:[i("rect",{class:"edge-label-bg",x:-(e.label.length*3.5+8)*R,y:-10*R,width:(e.label.length*7+16)*R,height:20*R,rx:4*R},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 jS({nodes:e,edges:t,onEdgeContextMenu:n}){let o=e.value,r=Array.from(t.value.values()),s=je.value,a=s!==null,c=uo.value,l=c!==null,u=mN(oe.value.scale);if(r.length===0&&!Ye.value)return null;let p=96,d=Array.from(o.values());if(d.length===0)return null;let m=Math.min(...d.map((b)=>b.position.x))-p,f=Math.min(...d.map((b)=>b.position.y))-p,h=Math.max(...d.map((b)=>b.position.x+b.size.width))+p,v=Math.max(...d.map((b)=>b.position.y+b.size.height))+p,x=Math.max(1,h-m),g=Math.max(1,v-f);return i("svg",{"aria-label":"Canvas connections",role:"img",viewBox:`${m} ${f} ${x} ${g}`,width:x,height:g,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((b)=>{let I=_c(b.from),R=_c(b.to);if(!I||!R||I.id===R.id)return null;let M=a&&(b.from===s||b.to===s),_=l&&!(c.has(b.from)||c.has(b.to));return i(gN,{edge:b,fromNode:I,toNode:R,focused:M,dimmed:a&&!M||_,selected:Kn.value===b.id,scale:u,onContextMenu:n},b.id,!1,void 0,this)}),Ye.value&&(()=>{let b=Ye.value,I=_c(b.fromId),R={position:{x:b.cursorX,y:b.cursorY},size:{width:1,height:1}},M;if(I){let _=Vl(I,R),N=Vl(R,I),w=N.x-_.x,k=N.y-_.y,z=Math.sqrt(w*w+k*k),X=Math.min(Math.max(z*0.35,32),160),W=Xl(_,X),J=Xl(N,X);M=`M ${_.x} ${_.y} C ${W.x} ${W.y}, ${J.x} ${J.y}, ${N.x} ${N.y}`}else{let _=b.cursorX-b.fromX,N=b.cursorY-b.fromY,w=Math.sqrt(_*_+N*N),k=Math.min(w*0.25,80),z=_/(w||1),X=N/(w||1);M=`M ${b.fromX} ${b.fromY} C ${b.fromX+z*k} ${b.fromY+X*k}, ${b.cursorX-z*k} ${b.cursorY-X*k}, ${b.cursorX} ${b.cursorY}`}return i("g",{children:[i("path",{d:M,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:M,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:b.cursorX,cy:b.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 vN(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 Am({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-ui)","font-weight":"700",opacity:"0.95",children:t.text},t.id,!1,void 0,this)}return i("path",{d:vN(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)}function yN(e){switch(e.type){case"markdown":return i(Vc,{node:e},void 0,!1,void 0,this);case"mcp-app":return i(Ko,{node:e},void 0,!1,void 0,this);case"webpage":return i(Nl,{node:e},void 0,!1,void 0,this);case"json-render":return i(Ko,{node:e},void 0,!1,void 0,this);case"graph":return i(Ko,{node:e},void 0,!1,void 0,this);case"board":return i(Gl,{node:e},void 0,!1,void 0,this);case"prompt":return i(zl,{node:e},void 0,!1,void 0,this);case"response":return i(Rl,{node:e},void 0,!1,void 0,this);case"status":return i(Il,{node:e},void 0,!1,void 0,this);case"context":return i(Lc,{node:e},void 0,!1,void 0,this);case"ledger":return i(Hc,{node:e},void 0,!1,void 0,this);case"trace":return i(Ml,{node:e},void 0,!1,void 0,this);case"file":return i(Bc,{node:e},void 0,!1,void 0,this);case"diff":return i(Dc,{node:e},void 0,!1,void 0,this);case"mermaid":return i(ll,{node:e},void 0,!1,void 0,this);case"image":return i(Pl,{node:e},void 0,!1,void 0,this);case"html":return i(Ks,{node:e},void 0,!1,void 0,this);case"group":return i(D_,{node:e},void 0,!1,void 0,this);default:return i("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function bN(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 xN(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&&bN(t,c,l)<=n+r.width/2)return r}}return null}var Im="currentColor",US=4,ZS=24,wN=14,WS={width:520,height:420};function _N(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 Nm(e){let t=e.trim();if(!t)return[];let n=t.includes(`
331
- `)?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=_N(a);if(!c||o.has(c))continue;o.add(c),r.push(c)}return r}function SN(e){let t=Nm(e.getData("text/uri-list"));if(t.length>0)return t;return Nm(e.getData("text/plain"))}function kN(e){if(!e)return!1;return e.types.includes("text/uri-list")||e.types.includes("text/plain")}function Pm(e){if(!(e instanceof HTMLElement))return!1;return Boolean(e.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}function TN(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 qS({onNodeContextMenu:e,onEdgeContextMenu:t,onCanvasContextMenu:n,annotationMode:o=!1,annotationTool:r=null}){let s=oe.value,a=L(!1),c=L(null),l=L(!1),u=L([]),[p,d]=A(null),[m,f]=A(null),[h,v]=A(null),x=L(null),[g,b]=A(!1),I=L(0),R=L(null),M=L(null);H(()=>{let D=null,Y=nn(()=>{oe.value;let Te=M.current;if(!Te)return;if(Te.style.willChange="transform",D)clearTimeout(D);D=setTimeout(()=>{Te.style.willChange="auto"},180)});return()=>{if(D)clearTimeout(D);Y()}},[]);let _=Ic({viewport:oe,disabled:o,onViewportChange:(D)=>{if(a.current||o)return;fo(),Wb(D)},onViewportCommit:(D)=>{if(a.current||o)return;fo(),Gb(D)}}),N=j((D)=>{x.current=D,v(D)},[]),w=j(async(D,Y,Te)=>{if(D.length===0)return;let{width:de,height:be}=WS,se=24,re=Math.ceil(Math.sqrt(D.length)),Z=Math.ceil(D.length/re),xe=re*de+Math.max(0,re-1)*se,T=Z*be+Math.max(0,Z-1)*se;for(let ce=0;ce<D.length;ce++){let pe=ce%re,me=Math.floor(ce/re),qt=Y-xe/2+pe*(de+se),St=Te-T/2+me*(be+se);await On({type:"webpage",content:D[ce],x:qt,y:St,width:de,height:be})}},[]),k=j((D)=>{let Y=_.current;if(!Y)return;if(r==="eraser"){if((D.target instanceof Element?D.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;D.preventDefault(),D.stopPropagation();let Z=Y.getBoundingClientRect(),xe=oe.value,T={x:(D.clientX-Z.left-xe.x)/xe.scale,y:(D.clientY-Z.top-xe.y)/xe.scale},ce=xN(Array.from(ci.value.values()),T,wN/xe.scale);if(ce)Zb(ce.id);return}if(r==="text"){if((D.target instanceof Element?D.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;D.preventDefault(),D.stopPropagation(),je.value=null,Ut();let Z=Y.getBoundingClientRect(),xe=oe.value;N({x:(D.clientX-Z.left-xe.x)/xe.scale,y:(D.clientY-Z.top-xe.y)/xe.scale,value:""});return}if(r==="pen"){if((D.target instanceof Element?D.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;D.preventDefault(),D.stopPropagation(),je.value=null,Ut(),l.current=!0;let Z=Y.getBoundingClientRect(),xe=oe.value,T={x:(D.clientX-Z.left-xe.x)/xe.scale,y:(D.clientY-Z.top-xe.y)/xe.scale};u.current=[T],f({id:"draft-annotation",type:"freehand",points:[T],bounds:{x:0,y:0,width:0,height:0},color:Im,width:US,createdAt:""}),Y.setPointerCapture(D.pointerId);return}if(D.target!==Y)return;if(ui()||D.button===1||D.button===2){if(!D.shiftKey&&!R.current)je.value=null,Ut();return}D.preventDefault(),D.stopPropagation(),a.current=!0;let Te=Y.getBoundingClientRect(),de=D.clientX-Te.left,be=D.clientY-Te.top,se={startX:de,startY:be,currentX:de,currentY:be};R.current=se,d(se),Y.setPointerCapture(D.pointerId)},[r,_]);H(()=>nn(()=>{let D=oe.value,Y=c.current,Te=_.current;if(!Y||!Te)return;let de=Te.getBoundingClientRect();sl({x:(Y.x-de.left-D.x)/D.scale,y:(Y.y-de.top-D.y)/D.scale})}),[]);let z=j((D)=>{{let de=_.current;if(de){c.current={x:D.clientX,y:D.clientY};let be=de.getBoundingClientRect(),se=oe.value;sl({x:(D.clientX-be.left-se.x)/se.scale,y:(D.clientY-be.top-se.y)/se.scale})}}if(l.current){let de=_.current;if(!de)return;let be=de.getBoundingClientRect(),se=oe.value,re={x:(D.clientX-be.left-se.x)/se.scale,y:(D.clientY-be.top-se.y)/se.scale},Z=u.current.at(-1);if(Z&&Math.hypot(re.x-Z.x,re.y-Z.y)<2)return;u.current=[...u.current,re],f((xe)=>xe?{...xe,points:u.current}:null);return}if(!a.current||!R.current)return;let Y=_.current?.getBoundingClientRect();if(!Y)return;let Te={...R.current,currentX:D.clientX-Y.left,currentY:D.clientY-Y.top};R.current=Te,d(Te)},[_]),X=j((D)=>{if(l.current){l.current=!1;let re=u.current;if(u.current=[],f(null),re.length>=2)jd({points:re,color:Im,width:US});let Z=_.current;if(Z?.hasPointerCapture(D.pointerId))Z.releasePointerCapture(D.pointerId);return}let Y=R.current;if(!a.current||!Y)return;a.current=!1,R.current=null;let Te=Math.min(Y.startX,Y.currentX),de=Math.max(Y.startX,Y.currentX),be=Math.min(Y.startY,Y.currentY),se=Math.max(Y.startY,Y.currentY);if(de-Te<=5&&se-be<=5)je.value=null,Ut();if(de-Te>5||se-be>5){let re=oe.value,Z=(Te-re.x)/re.scale,xe=(de-re.x)/re.scale,T=(be-re.y)/re.scale,ce=(se-re.y)/re.scale,pe=[];for(let me of F.value.values()){let qt=me.position.x,St=me.position.y;if(qt+me.size.width>Z&&qt<xe&&St+me.size.height>T&&St<ce)pe.push(me.id)}if(pe.length>0)Rb(pe)}d(null)},[]);H(()=>{if(o)return;if(!l.current&&!m&&!h)return;l.current=!1,u.current=[],f(null),N(null)},[o,m,N,h]);let W=j(()=>{let D=x.current;if(!D)return;let Y=D.value.trim();if(N(null),!Y)return;let Te={x:D.x,y:D.y};jd({type:"text",points:[Te],color:Im,width:ZS,text:Y})},[N]);H(()=>{if(r!=="text"&&h)N(null)},[r,N,h]),H(()=>{let D=(se,re,Z)=>{let xe=null;for(let T of F.value.values()){if(T.id===Z||T.type==="group")continue;if(se>=T.position.x&&se<=T.position.x+T.size.width&&re>=T.position.y&&re<=T.position.y+T.size.height)xe=T.id}return xe};function Y(se){if(!Ye.value)return;let re=_.current;if(!re)return;let Z=re.getBoundingClientRect(),xe=oe.value,T=(se.clientX-Z.left-xe.x)/xe.scale,ce=(se.clientY-Z.top-xe.y)/xe.scale;Ye.value={...Ye.value,cursorX:T,cursorY:ce,targetId:D(T,ce,Ye.value.fromId)}}function Te(){let se=Ye.value;if(!se)return;Ye.value=null;let re=se.targetId;if(!re)return;if(se.withLabel){hn("Edge label","label text").then((Z)=>{xr(se.fromId,re,"relation",Z??void 0)});return}xr(se.fromId,re,"relation",void 0)}function de(se){let re=Ye.value;if(!re)return;if(se.key==="Escape")se.preventDefault(),Ye.value=null;else if(se.key==="l"||se.key==="L")se.preventDefault(),Ye.value={...re,withLabel:!re.withLabel}}function be(){Ye.value=null}return document.addEventListener("pointermove",Y),document.addEventListener("pointerup",Te),document.addEventListener("pointercancel",be),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",Te),document.removeEventListener("pointercancel",be),document.removeEventListener("keydown",de)}},[_]);let J=j((D)=>{if(o)return;let Y=_.current;if(!Y||D.target!==Y||!n)return;let Te=Y.getBoundingClientRect(),de=oe.value,be=(D.clientX-Te.left-de.x)/de.scale,se=(D.clientY-Te.top-de.y)/de.scale;n(D,be,se)},[o,_,n]),G=j((D)=>{D.preventDefault()},[]),S=j((D)=>{if(Pm(D.target instanceof Element?D.target:null))return;D.preventDefault()},[]),q=j((D)=>{if(D.preventDefault(),I.current++,D.dataTransfer?.types.includes("Files")||kN(D.dataTransfer))b(!0)},[]),ie=j((D)=>{if(D.preventDefault(),D.dataTransfer)D.dataTransfer.dropEffect="copy"},[]),ye=j((D)=>{if(D.preventDefault(),I.current--,I.current<=0)I.current=0,b(!1)},[]),ue=j(async(D)=>{D.preventDefault(),b(!1),I.current=0;let Y=_.current;if(!Y||!D.dataTransfer)return;let Te=Y.getBoundingClientRect(),de=oe.value,be=(D.clientX-Te.left-de.x)/de.scale,se=(D.clientY-Te.top-de.y)/de.scale,re=Array.from(D.dataTransfer.files);if(re.length===0){let Z=SN(D.dataTransfer);await w(Z,be,se);return}await $i(re,be,se)},[_,w]);H(()=>{let D=async(Y)=>{if(Y.defaultPrevented)return;if(Pm(Y.target instanceof Element?Y.target:null))return;if(Pm(document.activeElement))return;let Te=Y.clipboardData?.getData("text/plain")??"",de=Nm(Te);if(de.length===0)return;let be=_.current;if(!be)return;Y.preventDefault();let se=be.getBoundingClientRect(),re=oe.value,Z=(se.width/2-re.x)/re.scale,xe=(se.height/2-re.y)/re.scale;await w(de,Z,xe)};return document.addEventListener("paste",D),()=>{document.removeEventListener("paste",D)}},[_,w]);let Pe=TN(F.value.values(),ot.value,new Set(Fd.value.keys())),ke=Xn.value,Me=ke?F.value.get(ke.groupId):void 0,cn=ke?F.value.get(ke.nodeId):void 0,Pn=null;if(p){let D=Math.min(p.startX,p.currentX),Y=Math.min(p.startY,p.currentY),Te=Math.abs(p.currentX-p.startX),de=Math.abs(p.currentY-p.startY);Pn={position:"absolute",left:`${D}px`,top:`${Y}px`,width:`${Te}px`,height:`${de}px`,pointerEvents:"none"}}return i("div",{class:`canvas-viewport${ui()?" pan-mode":""}`,ref:_,tabIndex:0,onPointerDown:k,onPointerMove:z,onPointerLeave:()=>{c.current=null,sl(null)},onPointerUp:X,onContextMenu:G,onDblClick:J,onDragStart:S,onDragEnter:q,onDragOver:ie,onDragLeave:ye,onDrop:ue,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden",cursor:r==="eraser"?"cell":r==="text"?"text":o||Ye.value||a.current||Qt.value==="connect"?"crosshair":ui()?"grab":"default"},children:[i("div",{ref:M,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(gS,{},void 0,!1,void 0,this),i(K_,{},void 0,!1,void 0,this),i(oS,{},void 0,!1,void 0,this),i(rS,{},void 0,!1,void 0,this),i(jS,{nodes:F,edges:Je,onEdgeContextMenu:t},void 0,!1,void 0,this),Ye.value&&i("div",{class:"edge-hint-pill","data-testid":"edge-hint",style:{left:`${Ye.value.cursorX+14}px`,top:`${Ye.value.cursorY+14}px`},children:[i("span",{class:"edge-hint-main",children:Ye.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",Ye.value.withLabel?" · label on":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),ke&&Me&&cn&&i("div",{class:"drop-pill","data-testid":"drop-pill",style:{left:`${cn.position.x}px`,top:`${cn.position.y+cn.size.height+10}px`},children:[i("span",{class:"drop-pill-text",children:ke.mode==="add"?`release to add to ${String(Me.data.title??"group")}`:`release to remove from ${String(Me.data.title??"group")}`},void 0,!1,void 0,this),i("span",{class:"drop-pill-hint",children:ke.mode==="add"?"esc keeps it out":"esc keeps it in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Am,{annotations:Array.from(ci.value.values())},void 0,!1,void 0,this),m&&m.points.length>=2&&i(Am,{annotations:[m]},void 0,!1,void 0,this),Pe.map((D)=>i(HS,{node:D,onContextMenu:e,children:yN(D)},D.id,!1,void 0,this)),Or.value&&i("svg",{class:"snap-guides-svg",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"visible"},children:Or.value.map((D,Y)=>D.axis==="x"?i("line",{x1:D.pos,y1:D.from-20,x2:D.pos,y2:D.to+20,class:"snap-guide-line"},Y,!1,void 0,this):i("line",{x1:D.from-20,y1:D.pos,x2:D.to+20,y2:D.pos,class:"snap-guide-line"},Y,!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),h&&i("input",{class:"annotation-text-input",value:h.value,autoFocus:!0,style:{left:`${h.x*s.scale+s.x}px`,top:`${h.y*s.scale+s.y}px`,fontSize:`${ZS*s.scale}px`},onInput:(D)=>N({...h,value:D.target.value}),onBlur:W,onPointerDown:(D)=>D.stopPropagation(),onKeyDown:(D)=>{if(D.key==="Enter")D.preventDefault(),W();if(D.key==="Escape")D.preventDefault(),N(null)}},void 0,!1,void 0,this),Pn&&i("div",{class:"lasso-rect",style:Pn},void 0,!1,void 0,this),g&&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 Kl({label:e,value:t,options:n,onChange:o,className:r="",above:s=!1}){let[a,c]=A(!1),l=L(null),u=L(null),p=L(null),d=()=>{c(!1),u.current?.focus()};return _n(()=>{if(!a)return;(p.current?.querySelector('[aria-checked="true"]:not(:disabled)')??p.current?.querySelector("button:not(:disabled)"))?.focus();let f=(h)=>{if(h.target instanceof Node&&!l.current?.contains(h.target))c(!1)};return document.addEventListener("pointerdown",f),()=>document.removeEventListener("pointerdown",f)},[a]),i("div",{ref:l,class:`choice-menu ${r}`,onBlur:(m)=>{if(m.relatedTarget instanceof Node&&!l.current?.contains(m.relatedTarget))c(!1)},onKeyDown:(m)=>{if(m.key!=="Tab"&&(m.key!=="Escape"||a))m.stopPropagation();if(m.key==="Escape"&&a)m.preventDefault(),m.stopPropagation(),d();if(["ArrowDown","ArrowUp","Home","End"].includes(m.key)){if(m.preventDefault(),m.stopPropagation(),!a){c(!0);return}let f=[...p.current?.querySelectorAll("button:not(:disabled)")??[]];if(!f.length)return;let h=f.findIndex((x)=>x===document.activeElement),v=m.key==="Home"?0:m.key==="End"?f.length-1:(h+(m.key==="ArrowUp"?-1:1)+f.length)%f.length;f[v]?.focus()}},children:[i("button",{ref:u,type:"button",class:"choice-menu-trigger","aria-label":e,"aria-haspopup":"menu","aria-expanded":a,onClick:()=>c(!a),children:[i("span",{children:n.find((m)=>m.value===t)?.label??e},void 0,!1,void 0,this),i(Nc,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a&&i("div",{ref:p,role:"menu","aria-label":e,class:`toolbar-menu choice-menu-options${s?" opens-above":""}`,children:n.map((m)=>i("button",{type:"button",role:"menuitemradio",class:`toolbar-menu-item${m.value===t?" active":""}`,"aria-checked":m.value===t,disabled:m.disabled,tabIndex:-1,"data-value":m.value,onClick:()=>{o(m.value),d()},children:[i("span",{children:m.label},void 0,!1,void 0,this),m.value===t&&i("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},m.value,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function GS(){let e=[...Le.value],t=F.value,[n,o]=A(""),[r,s]=A(!1),a=tS.value,[c,l]=A(null),u=a.length>=2,p=!u&&a.length===1&&a[0].steerable?a[0]:null,d=u?c?a.find((h)=>h.value===c&&h.steerable)??null:null:p,m=d?.value??null,f=async()=>{let h=n.trim();if(!h||r)return;s(!0);let v=await fS(h,m);if(s(!1),v)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((h)=>{let v=t.get(h),x=typeof v?.data.title==="string"&&v.data.title.trim()?v.data.title:v?.type??h;return i("span",{class:"command-bar-chip","data-node-id":h,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:()=>Jn(h),children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},h,!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(fi,{size:15,class:"command-bar-icon"},void 0,!1,void 0,this),u&&i(Kl,{className:"command-bar-target",label:"Steer which agent",value:m??"",above:!0,onChange:(h)=>l(h||null),options:[{value:"",label:"All agents"},...a.map((h)=>{let v=h.pendingSteers&&h.pendingSteers>0?` · ${h.pendingSteers} queued`:"",x=h.polling?" · polling":"";return{value:h.value,disabled:!h.steerable,label:h.attached?`${h.label}${x}${v}`:h.steerable?`${h.label} · writer${x}${v}`:`${h.label} · no inbox`}})]},void 0,!1,void 0,this),i("input",{class:"command-bar-input",type:"text",value:n,placeholder:`Steer ${d?.label??"the agent"}, or ${rt("K")} to search the board…`,"aria-label":"Steer the agent",disabled:r,onInput:(h)=>o(h.target.value),onKeyDown:(h)=>{if(h.key==="Enter")h.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 zm=Ge(()=>{if(fn.value==="disconnected")return"reconnecting";if(fn.value==="connected"&&!Yt.value&&_r.value>1)return"resyncing";return null});function VS(){let e=zm.value;if(!e)return null;if(e==="reconnecting"){let t=Sr.value,n=kr.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 CN={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 In(e){if(e.x!==void 0&&e.y!==void 0)return On(e);let t=CN[e.type]??{width:360,height:200},n=e.width??t.width,o=e.height??t.height,r=Ro(),s=oe.value,a=await On({...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)pt(a.id);return a}var Jl=!1,XS=!1,Lr=null,ji=null;function Rm(){return Jl}function Yl(){Jl=!1,XS=!0,KS()}function KS(){if(Lr&&ji)Lr.removeEventListener("change",ji);Lr=null,ji=null}function EN(){if(typeof window>"u"||!window.location)return null;let e=new URLSearchParams(window.location.search).get("theme");if(e==="auto")return"auto";return Ls(e)?e:null}function JS(e){if(XS)return;let t=EN();if(!t)return;if(KS(),Jl=!0,t!=="auto"){e(t);return}Lr=window.matchMedia("(prefers-color-scheme: light)"),ji=()=>{if(Jl&&Lr)e(Lr.matches?"daylight":"harbor")},ji(),Lr.addEventListener("change",ji)}var AN='a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';function an(e,t,n={}){H(()=>{if(!t)return;let o=e.current;if(!o)return;let r=document.activeElement,s=n.restoreTo,a=()=>Array.from(o.querySelectorAll(AN)),c=n.initial?.current??a()[0];if(c&&!o.contains(document.activeElement))c.focus();let l=(u)=>{if(u.key!=="Tab")return;let p=a();if(p.length===0)return;let d=p[0],m=p[p.length-1],f=document.activeElement;if(u.shiftKey&&(f===d||!o.contains(f)))u.preventDefault(),m.focus();else if(!u.shiftKey&&f===m)u.preventDefault(),d.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 IN(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 PN(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 Mm={md:"markdown",app:"mcp-app",web:"webpage",ui:"json-render",chart:"graph",ctx:"context",log:"ledger"};function NN(e){let t=e.toLowerCase().trim();if(t.startsWith("type:")){let n=t.slice(5).trim(),r=Object.keys(Nt).find((a)=>a.startsWith(n));if(r)return{typeFilter:r,remaining:""};let s=Mm[n];if(s)return{typeFilter:s,remaining:""}}if(Mm[t])return{typeFilter:Mm[t],remaining:""};return{typeFilter:null,remaining:e}}function YS({onClose:e,onToggleMinimap:t}){let[n,o]=A(""),[r,s]=A(0),[a,c]=A([]),[l,u]=A("idle"),p=L(null),d=L(null),m=L(null);an(m,!0,{initial:p}),H(()=>{setTimeout(()=>p.current?.focus(),30)},[]),H(()=>{let _=n.trim();if(_.length<2){c([]),u("idle");return}let N=!0;u("loading");let w=window.setTimeout(()=>void ne("paletteLibrarySearch",`/api/canvas/search?q=${encodeURIComponent(_)}&scope=library&limit=12`,null).then((k)=>{if(!N)return;if(!k){c([]),u("error");return}c(k.results??[]),u("idle")}),150);return()=>{N=!1,window.clearTimeout(w)}},[n]);let f=j(()=>{let _=[];for(let w of F.value.values()){let k=w.data.title||Nt[w.type],z=w.data.content||w.data.path||"",X=w.type==="group"&&Array.isArray(w.data.children)?w.data.children.length:0;_.push({id:`node:${w.id}`,kind:"node",label:k,description:w.type==="group"?`group · ${X} node${X===1?"":"s"}`:z.length>60?`${Nt[w.type].toLowerCase()} · ${z.slice(0,60)}…`:z?`${Nt[w.type].toLowerCase()} · ${z}`:Nt[w.type].toLowerCase(),icon:Bn(w.type),nodeType:w.type,action:()=>{pt(w.id),e()}})}let N=[{label:"New markdown note",shortcut:"M",icon:Ho,iconTone:"accent",action:()=>{In({type:"markdown",title:"New note",width:520,height:360}),e()}},{label:"Link to board…",icon:Bn("board"),iconTone:"accent",action:()=>{window.dispatchEvent(new CustomEvent("pmx-open-board-link")),e()}},..._t.value?[]:[{label:"Start agent session",icon:fi,iconTone:"purple",action:()=>{tr(),e()}}],{label:"Fit view",shortcut:"F",icon:zc,iconTone:"muted",action:()=>{pi(bt().width,bt().height),e()}},{label:"Auto-arrange (grid)",icon:go,iconTone:"muted",action:()=>{Ec(),e()}},{label:"Auto-arrange (graph-aware)",icon:go,iconTone:"muted",action:()=>{Ac(),e()}},{label:"Toggle minimap",icon:Rc,iconTone:"muted",action:()=>{t(),e()}},{label:"Toggle theme (Harbor/Daylight)",icon:Mc,iconTone:"muted",action:()=>{let w=Go(gt.value)==="dark"?"daylight":"harbor";Yl(),document.documentElement.setAttribute("data-theme",w),Ri(),gt.value=w,fc(w),e()}}];for(let w of N)_.push({id:`action:${w.label}`,kind:"action",label:w.label,...w.shortcut?{shortcut:w.shortcut}:{},icon:w.icon,...w.iconTone?{iconTone:w.iconTone}:{},action:w.action});return _},[e,t]),{typeFilter:h,remaining:v}=NN(n),x=f(),g;if(!n.trim())g=x.map((_)=>({..._,score:0,indices:[]}));else{g=[];for(let _ of x){if(h){if(_.kind!=="node"||_.nodeType!==h)continue;if(!v){g.push({..._,score:0,indices:[]});continue}}let N=IN(v||n,_.label);if(N.match)g.push({..._,score:N.score,indices:N.indices})}g.sort((_,N)=>N.score-_.score)}for(let _ of a)g.push({id:`library:${_.boardId}:${_.cardId}`,kind:"library",label:_.title||_.boardTitle,description:`${_.boardTitle} · ${_.snippet}`,icon:Bn("board"),score:0,indices:[],action:()=>{(async()=>{if(await sn(_.boardId),Oe.value!==_.boardId)return;for(let N=0;N<40&&Oe.value===_.boardId;N++){if(F.value.has(_.cardId)){pt(_.cardId),e();return}await new Promise((w)=>window.setTimeout(w,25))}})()}});g=[...g.filter((_)=>_.kind==="action"),...g.filter((_)=>_.kind==="node"),...g.filter((_)=>_.kind==="library")];let b=g.findIndex((_)=>_.kind==="node"),I=g.findIndex((_)=>_.kind==="library");H(()=>{if(!n.trim()){uo.value=null;return}let _=new Set;for(let N of g)if(N.kind==="node")_.add(N.id.slice(5));uo.value=_.size>0?_:null},[n,g]),H(()=>()=>{uo.value=null},[]);let R=Math.min(r,Math.max(0,g.length-1)),M=j((_)=>{if(_.key==="ArrowDown")_.preventDefault(),s((N)=>Math.min(N+1,g.length-1));else if(_.key==="ArrowUp")_.preventDefault(),s((N)=>Math.max(N-1,0));else if(_.key==="Enter"){if(_.preventDefault(),g[R])g[R].action()}else if(_.key==="Escape")_.preventDefault(),_.stopPropagation(),e()},[g,R,e]);return H(()=>{let _=d.current;if(!_)return;_.children[R]?.scrollIntoView({block:"nearest"})},[R]),H(()=>{s(0)},[n]),i("div",{class:"command-palette-backdrop",onMouseDown:e,children:i("div",{ref:m,class:"command-palette",role:"dialog","aria-modal":"true","aria-label":"Search and commands",onMouseDown:(_)=>_.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:p,type:"text",class:"command-palette-input",value:n,onInput:(_)=>o(_.target.value),onKeyDown:M,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:d,children:[l==="loading"&&i("div",{class:"command-palette-empty",role:"status",children:"Searching all boards…"},void 0,!1,void 0,this),l==="error"&&i("div",{class:"command-palette-empty",role:"alert",children:"Library search is unavailable."},void 0,!1,void 0,this),g.length===0&&l!=="loading"&&i("div",{class:"command-palette-empty",children:"No matching nodes, boards, or actions"},void 0,!1,void 0,this),g.map((_,N)=>{let w=_.icon,k=N===0&&_.kind==="action"?"Actions":N===b?"Jump to":N===I?"Across boards":null;return i("div",{class:"command-palette-row",children:[k&&i("div",{class:"command-palette-group",children:k},void 0,!1,void 0,this),i("button",{type:"button",class:`command-palette-item${N===R?" selected":""}`,onMouseEnter:()=>s(N),onClick:()=>_.action(),children:[i("span",{class:`command-palette-icon tone-${_.iconTone??"kind"}`,"aria-hidden":"true",children:i(w,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"command-palette-label",children:[_.indices.length>0?PN(_.label,_.indices):_.label,_.description&&i("span",{class:"command-palette-desc",children:[" — ",_.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_.shortcut&&i("kbd",{class:"command-palette-kbd",children:_.shortcut},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},_.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:rt("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 QS({onClose:e}){let t=L(null),n=L(null),[o,r]=A(""),[s,a]=A("");an(t,!0,{initial:n});let c=rn.value.filter((u)=>u.id!==Oe.value&&u.name.toLowerCase().includes(o.trim().toLowerCase())),l=async(u)=>{let p=rn.value.find((h)=>h.id===u);if(!p)return a("That board is no longer available.");let d=Ro(),m=oe.value;if(!(await ne("createBoardLink","/api/canvas/node",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"board",title:p.name,x:Math.round((d.x-m.x)/m.scale-180),y:Math.round((d.y-m.y)/m.scale-100),width:360,height:200,data:{boardId:u}})})).ok)return a("Could not create the board link.");e()};return i("div",{class:"text-prompt-backdrop",onMouseDown:e,children:i("div",{ref:t,class:"text-prompt board-link-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-link-title",onMouseDown:(u)=>u.stopPropagation(),children:[i("h2",{id:"board-link-title",children:"Link to a board"},void 0,!1,void 0,this),i("input",{ref:n,type:"search",class:"text-prompt-input","aria-label":"Find a board to link",placeholder:"Find a board…",value:o,onInput:(u)=>r(u.currentTarget.value)},void 0,!1,void 0,this),s&&i("div",{role:"alert",class:"board-copy-error",children:s},void 0,!1,void 0,this),i("ul",{class:"board-link-results",children:[c.map((u)=>i("li",{children:i("button",{type:"button",onClick:()=>void l(u.id),children:[i("span",{children:u.name},void 0,!1,void 0,this),i("small",{children:[u.nodeCount," nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},u.id,!1,void 0,this)),c.length===0&&i("li",{class:"board-copy-status",children:rn.value.length<=1?"Create another board first, then link it here.":"No boards match your search."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"text-prompt-actions",children:i("button",{type:"button",onClick:e,children:"Cancel"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function ek(){let[e,t]=A(null),n=j((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"node",x:a.clientX,y:a.clientY,nodeId:c})},[]),o=j((a,c,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"canvas",x:a.clientX,y:a.clientY,canvasX:c,canvasY:l})},[]),r=j((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"edge",x:a.clientX,y:a.clientY,edgeId:c})},[]),s=j(()=>t(null),[]);return H(()=>{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 zN="#4bbcFF",RN=[{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 tk({menu:e,onClose:t}){let n;if(e.kind==="node"){let c=F.value.get(e.nodeId);if(!c)return null;n=FN(c)}else if(e.kind==="edge"){let c=e.edgeId,l=Je.value.get(c);n=[{label:l?.label?`Edit label “${l.label.slice(0,18)}${l.label.length>18?"…":""}”`:"Add label…",action:()=>{hn("Edge label (empty clears it)","label text",{initial:l?.label??"",allowEmpty:!0,confirm:"Save"}).then((u)=>{if(u===null)return;bc(c,{label:u})})}},{separator:!0},...["flow","depends-on","relation","references"].map((u)=>({label:`${l?.type===u?"✓":" "} ${u}`,action:()=>void bc(c,{type:u})})),{separator:!0},...["solid","dashed","dotted"].map((u)=>({label:`${(l?.style??"solid")===u?"✓":" "} ${u}`,action:()=>void bc(c,{style:u})})),{separator:!0},{label:"Delete edge",danger:!0,action:()=>void xc(c)}]}else n=DN(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 p=`${l}:${u}`;if(c.separator)return i("div",{class:"context-menu-separator"},p,!1,void 0,this);if(c.render)return i("div",{class:"context-menu-custom",children:c.render(t)},p,!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)]},p,!0,void 0,this)})},void 0,!1,void 0,this)}function MN(e){return(typeof e.data.path==="string"?e.data.path.trim():"")||null}function Ql(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 nk(e){if(typeof e.data.color!=="string"||!e.data.color.trim())return null;return Ql(e.data.color)}function $N(e){let t=nk(e);return t&&/^#[0-9a-f]{6}$/.test(t)?t:Ql(zN)}function $m(e,t){let n=t?Ql(t):null;wt(e.id,{data:{...e.data,color:n}}),kt(e.id,{data:{color:n}})}function ON(e,t){let n=nk(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:()=>{$m(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:RN.map((o)=>{let r=Ql(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:()=>{$m(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:$N(e),onClick:(o)=>o.stopPropagation(),onInput:(o)=>{$m(e,o.currentTarget.value),t()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Lm(e,t,n,o){return{x:e-n/2,y:t-o/2}}function LN(e,t){return e.trim().replace(/[?#].*$/,"").split("/").filter(Boolean).at(-1)||t}async function Om(e){let t=await hn(e.promptLabel,e.placeholder??"");if(!t)return;let n=t.trim();if(!n)return;let o=Lm(e.canvasX,e.canvasY,e.width,e.height);if(!(await On({type:e.type,...e.type!=="webpage"?{title:LN(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 DN(e,t){return[{label:"New note",action:()=>{let r=Lm(e,t,520,360);On({type:"markdown",title:"New note",x:r.x,y:r.y,width:520,height:360})}},{label:"Open webpage...",action:()=>{Om({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:()=>{Om({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:()=>{Om({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."})}},{label:"Link to board…",action:()=>window.dispatchEvent(new CustomEvent("pmx-open-board-link"))},{separator:!0},{label:"New group",action:()=>{let r=Lm(e,t,600,400);ii({title:"Group",x:r.x,y:r.y,width:600,height:400})}}]}function FN(e){let t=[],n=MN(e);if(t.push({label:"Focus",action:()=>pt(e.id)}),t.push({label:"Rename…",action:()=>{hn("Rename node","Node title",{initial:typeof e.data.title==="string"?e.data.title:"",confirm:"Save"}).then((l)=>{if(!l?.trim())return;kt(e.id,{title:l.trim()})})}}),ms.has(e.type))t.push({label:"Expand",shortcut:"⤢",action:()=>kn(e.id)});if(t.push({label:e.collapsed?"Expand":"Collapse",action:()=>Ss(e.id)}),Yc(e))t.push({label:"Open in new tab",action:()=>void Qc(e)});let o=Le.value.has(e.id);t.push({label:o?"Unpin from context":"Pin as context",action:()=>Jn(e.id)}),t.push({label:e.pinned?"Unlock position":"Lock position (no auto-arrange)",action:()=>{let l=!e.pinned;wt(e.id,{pinned:l}),kt(e.id,{pinned:l}),Tt()}});let r=ws.value;if(r&&r.from!==e.id){let l=F.value.get(r.from),u=l?(l.data.title||l.id).slice(0,20):r.from;t.push({label:`Connect from "${u}"`,action:()=>{xr(r.from,e.id,"relation"),ws.value=null}})}t.push({label:r?"Connect from here (replace)":"Connect from here",action:()=>{ws.value={from:e.id}}});let s=Array.from(Je.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:()=>pb("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:()=>{gc(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)=>ON(e,u)}),l.length>0)t.push({label:`Ungroup (${l.length} node${l.length!==1?"s":""})`,action:()=>{Do(e.id),si(e.id)}})}let a=typeof e.data.parentGroup==="string"?e.data.parentGroup:null,c=a?F.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((p)=>p!==e.id):[];t.push({label:`Remove from “${l}”`,action:()=>{yc(c.id,u)}})}return t.push({separator:!0}),t.push({label:e.type==="group"?"Delete frame (children stay)":"Delete",danger:!0,action:()=>{Oo(e.id)}}),t}function ok(){let e=Le.value.size;if(e===0||Gn.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:Hb,title:"Clear all context pins","aria-label":"Clear all context pins",children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function rk({onClose:e}){let t=L(null),[n,o]=A("Bug report"),[r,s]=A(""),[a,c]=A("");return an(t,!0),i("div",{class:"text-prompt-backdrop feedback-backdrop",onPointerDown:e,children:i("form",{ref:t,class:"text-prompt feedback-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"feedback-title","aria-describedby":"feedback-privacy",action:"https://github.com/pskoett/pmx-canvas/issues/new",method:"get",target:"_blank",rel:"noopener noreferrer",onPointerDown:(l)=>l.stopPropagation(),onKeyDown:(l)=>{if(l.stopPropagation(),l.key==="Escape")l.preventDefault(),e()},children:[i("div",{id:"feedback-title",class:"text-prompt-title",children:"Bug and feedback"},void 0,!1,void 0,this),i("p",{id:"feedback-privacy",class:"feedback-note",children:"Opens a draft issue in pskoett/pmx-canvas. Review and submit it on GitHub using your account. Issues are public. Only what you enter below is included; no board contents, workspace paths, screenshots, or logs are attached."},void 0,!1,void 0,this),i("div",{class:"feedback-field",children:[i("span",{children:"Feedback type"},void 0,!1,void 0,this),i(Kl,{label:"Feedback type",value:n,onChange:o,options:["Bug report","Feature request","General feedback"].map((l)=>({value:l,label:l}))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("label",{children:["Title",i("input",{class:"text-prompt-input",name:"title",required:!0,maxLength:120,value:r,onInput:(l)=>s(l.currentTarget.value),placeholder:"A short summary"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("label",{children:["Description",i("textarea",{class:"text-prompt-input",required:!0,maxLength:1200,rows:6,value:a,onInput:(l)=>c(l.currentTarget.value),placeholder:"What happened, what you expected, and steps to reproduce — or describe your idea."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("input",{type:"hidden",name:"body",value:`## ${n}
330
+ </script>`}function I_(){return"<style data-pmx-canvas-ext-app-base>html, body { background: transparent !important; }</style>"}function P_(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 zi(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 um(e,t){let n=e?.getBoundingClientRect();return{width:zi(e?.clientWidth??0,zi(n?.width??0,t.width)),height:zi(e?.clientHeight??0,zi(n?.height??0,t.height))}}function kP(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0&&!t}function TP(e,t){return Math.max(zi(e,1),zi(t,1))}function z_({node:e,expanded:t=!1}){let n=L(null),o=L(null),r=L(null),s=L(null),a=L({}),c=L(void 0),l=L(!1),u=L(void 0),p=L(null),d=L(!1),m=L(null),f=L(0),h=L([]),v=L(""),x=L(!1),g=L(!1),b=L([]),I=L(!1),R=L(!1),M=L(!1),_=L(!1),[N,w]=A("loading"),[k,z]=A(null),[X,W]=A(0),[J,G]=A(!1),[S,q]=A(!1),[ie,ye]=A(()=>t||typeof navigator>"u"||typeof window>"u"||!zr(navigator.userAgent)),ue=e.data.html,Pe=e.data.serverName,ke=e.data.appSessionId,Me=e.data.toolInput??{},cn=e.data.toolResult,Pn=e.data.toolName??"ext-app",D=e.data.toolDefinition,Y=e.data.toolCallId,Te=typeof Y==="string"||typeof Y==="number"?Y:void 0,de=e.data.resourceMeta,be=e.data.sessionStatus,se=e.data.sessionError,re=e.size.height,Z=e.id,xe=bP(e,X),T=wP(null),pe=e.data.axCapabilities?.enabled===!0&&typeof ue==="string"&&ue.length>0,me=Be(()=>`ax-${crypto.randomUUID()}`,[]),qt=pe?_P(me,Z):"",St=typeof ue==="string"&&ue.length>0?SP(me,Z):"",Gt=S_(P_(ue??"",I_()+St+qt),T);H(()=>{function Q(le){if(le.source!==n.current?.contentWindow)return;let Ce=le.data;if(!Ce||Ce.source!==Jc||Ce.token!==me||Ce.nodeId!==Z)return;if(g.current=!0,Ce.kind==="paint-tick"){let Ie=Ce,Bt={content:Ie.content===!0,detail:typeof Ie.detail==="string"?Ie.detail:""};for(let zn of h.current.splice(0))zn(Bt)}}return window.addEventListener("message",Q),()=>window.removeEventListener("message",Q)},[me,Z]),H(()=>{if(ie)return;E_({remount:()=>{if(_.current)return!1;return At(Z,"mount-slot"),ye(!0),!0},awaitBoot:()=>new Promise((Q)=>{let le=window.setTimeout(Ce,k_);function Ce(){window.clearTimeout(le),Q()}b.current.push(Ce)})})},[]),Ni({enabled:pe,token:me,nodeId:Z,sourceSurface:"mcp-app",iframeRef:n});let yn=3,ar=(Q)=>{if(f.current>=yn)return At(Z,`remount-cap-hit (${Q})`),!1;if(I.current)return!0;return f.current+=1,I.current=!0,At(Z,`remount-queued #${f.current} (${Q})`),E_({remount:()=>{if(I.current=!1,_.current||!t&&ot.value===Z)return At(Z,"remount-skipped"),G(!1),!1;return R.current=typeof document<"u"&&document.visibilityState==="hidden",At(Z,`remount-run #${f.current}`),w("loading"),W((le)=>le+1),!0},awaitBoot:()=>new Promise((le)=>{let Ce=window.setTimeout(Ie,k_);function Ie(){window.clearTimeout(Ce),le()}b.current.push(Ie)})}),!0},da=1500,bn=()=>new Promise((Q)=>{let le=n.current?.contentWindow;if(!le||_.current){Q("timeout");return}let Ce=!1,Ie=window.setTimeout(()=>{if(Ce)return;Ce=!0,Q("timeout")},da);h.current.push((Bt)=>{if(Ce)return;Ce=!0,window.clearTimeout(Ie),v.current=Bt.detail,Q(Bt.content?"content-verified":"tick-no-content")}),le.postMessage({source:xp,token:me},"*")}),Nn=async(Q)=>{let le=Date.now()+Q;while(Date.now()<le&&!_.current){if(await bn()==="content-verified")return!0;await new Promise((Ce)=>window.setTimeout(Ce,400))}return!1},eo=()=>new Promise((Q)=>{let le=n.current;if(!le){Q();return}let Ce=le.style.width,Ie=le.style.height;le.style.width="140%",le.style.height="140%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{le.style.width=Ce,le.style.height=Ie,At(Z,"soft-expand-cycle"),Q()})})}),Gi=600,to=()=>{if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;let Q=n.current;if(!Q||_.current)return;if(!vP({userAgent:navigator.userAgent,visibilityState:document.visibilityState,rect:Q.getBoundingClientRect(),viewport:{width:window.innerWidth,height:window.innerHeight},alreadyRearmed:M.current}))return;M.current=!0,window.setTimeout(()=>{if(_.current||document.visibilityState==="visible")return;f.current=0,q(!1),R.current=!1,At(Z,"assume-visible-rearm"),ar("assume-visible")},Gi)},_o=(Q="")=>{let le=v.current?` [${v.current}]`:"";return typeof document<"u"&&document.visibilityState==="hidden"?`paint-ok (content-verified)${le}${Q} (host hidden)`:`paint-ok (content-verified)${le}${Q}`},Vi=async()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!zr(navigator.userAgent))return;G(!0);let Q=await bn();if(Q==="content-verified"){At(Z,_o()),G(!1),to();return}if(At(Z,Q==="tick-no-content"?`paint-fail (tick without content: ${v.current||"unknown"})`:"paint-fail (no tick)"),await eo(),Q=await bn(),Q==="content-verified"){At(Z,_o(" (after soft-expand)")),G(!1),to();return}if(_.current)return;if(Q==="tick-no-content"&&await Nn(3000)){At(Z,_o(" (after content wait)")),G(!1),to();return}if(_.current)return;if(!ar("paint-fail"))At(Z,"recovery-exhausted"),G(!1),q(!0),to()};H(()=>{if(t)return;if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;if(!zr(navigator.userAgent))return;function Q(){if(document.visibilityState!=="visible")return;if(!R.current||_.current)return;R.current=!1,f.current=0,q(!1),At(Z,"visible-again-rearm"),ar("visible-after-hidden-boot")}return document.addEventListener("visibilitychange",Q),()=>document.removeEventListener("visibilitychange",Q)},[t,Z]);let So=6000;H(()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!zr(navigator.userAgent))return;if(!Gt.ready||!ie)return;let Q=window.setTimeout(()=>{if(x.current||g.current||_.current)return;ar("boot-watchdog")},So);return()=>window.clearTimeout(Q)},[xe,Gt.ready,t,ie]),H(()=>()=>{_.current=!0;for(let Q of b.current.splice(0))Q();for(let Q of h.current.splice(0))Q({content:!1,detail:"unmounted"})},[]);let ko=(Q)=>Go(Q),ln=t||ot.value===Z;a.current=Me,c.current=cn;let cr=be==="error"&&typeof ue==="string"&&ue.length>0,Hr=be==="error"?cr?`Live session unavailable — showing saved content. Reopen the app to restore interactivity.${se?` (${se})`:""}`:se??"Saved app session is unavailable. Reopen the app to restore interactivity.":"Reconnecting saved app session...",jr=(Q)=>{let le=c.current;if(!Q||!d.current||!le)return null;if(u.current===le)return null;if(u.current&&w_(u.current,le))return u.current=le,null;if(p.current)return p.current;let Ce=Q.sendToolResult(le).then(()=>{u.current=le,l.current=!0,w("done")}).catch((Ie)=>{let Bt=Ie instanceof Error?Ie.message:String(Ie);throw z(`Tool result delivery failed: ${Bt}`),Ie}).finally(()=>{p.current=null});return p.current=Ce,Ce};if(H(()=>{if(!ue||!Gt.ready||!ie)return;let Q=n.current;if(!Q)return;let le=!1,Ce=null,Ie=null,Bt=null,zn=null,Un=null;l.current=!1,u.current=void 0,p.current=null,d.current=!1,x.current=!1,g.current=!1;let To=()=>{if(!Ce)return;clearTimeout(Ce),Ce=null};return(async()=>{if(!ue)return;let un=Q.contentWindow;if(!un)throw Error("Ext-app iframe window is unavailable");let xn=(Ee=ot.value===Z?"fullscreen":"inline")=>({theme:ko(gt.value),platform:"web",containerDimensions:um(Q,{width:e.size.width,height:re}),displayMode:Ee,locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,...D?{toolInfo:{id:Te,tool:D}}:{}}),wn=()=>{if(zn!==null)return;zn=requestAnimationFrame(()=>{if(zn=null,le||!d.current)return;Fe.setHostContext?.(xn())})},no=()=>{if(Un!==null)return;Un=requestAnimationFrame(()=>{Un=requestAnimationFrame(()=>{if(Un=null,le||!d.current)return;Fe.sendHostContextChange?.(xn())})})},Ur=()=>{if(!zr(navigator.userAgent))return;if(Ie)clearTimeout(Ie);Ie=setTimeout(()=>{if(Ie=null,le)return;Vi()},N_+200)},Fe=new sm(null,{name:"PMX Canvas",version:"1.0.0"},{openLinks:{},serverTools:{listChanged:!1},serverResources:{listChanged:!1},logging:{},updateModelContext:{text:{},structuredContent:{}}},{hostContext:xn(ln?"fullscreen":"inline")});Fe.onsizechange=async({height:Ee})=>{if(kP(Ee,ot.value===Z)){let ut=um(Q.parentElement??Q,{width:e.size.width,height:re}),Ht=TP(Ee,ut.height);Q.style.height=`${Ht}px`;let oo=F.value.get(Z)?.size??e.size,Co=Math.max(oo.height,Ht+Si);if(Math.abs(Co-oo.height)>8){if(Cc(Z,{width:oo.width,height:Co}),s.current!==null)window.clearTimeout(s.current);s.current=window.setTimeout(()=>{Tt({recordHistory:!1}),s.current=null},0)}}return{}},Fe.onopenlink=async({url:Ee})=>(window.open(Ee,"_blank","noopener"),{}),Fe.onsandboxready=async()=>{await Fe.sendSandboxResourceReady({html:P_(ue,I_()),sandbox:wp,...de?.csp?{csp:de.csp}:{},...de?.permissions?{permissions:de.permissions}:{}})},Fe.onrequestdisplaymode=async({mode:Ee})=>{let{nextMode:ut,shouldExpand:Ht,shouldCollapse:oo}=xP(Ee,ln);if(Ht)kn(Z);else if(oo)ho();return{mode:ut}},Fe.oncalltool=async(Ee)=>{if(!ke)throw Error(Hr);try{let ut=await Nr("/api/ext-app/call-tool",{sessionId:ke,nodeId:Z,serverName:Pe,toolName:Ee.name,arguments:Ee.arguments??{}});return z(null),ut}catch(ut){let Ht=ut instanceof Error?ut.message:String(ut);throw z(`Tool call failed: ${Ht}`),ut}},Fe.setRequestHandler(kl,async()=>{if(!ke)return{tools:[]};return Nr("/api/ext-app/list-tools",{sessionId:ke})}),Fe.onlistresources=async()=>ke?Nr("/api/ext-app/list-resources",{sessionId:ke}):{resources:[]},Fe.onlistresourcetemplates=async()=>ke?Nr("/api/ext-app/list-resource-templates",{sessionId:ke}):{resourceTemplates:[]},Fe.onreadresource=async(Ee)=>{if(!ke)throw Error(Hr);return Nr("/api/ext-app/read-resource",{sessionId:ke,uri:Ee.uri})},Fe.onlistprompts=async()=>ke?Nr("/api/ext-app/list-prompts",{sessionId:ke}):{prompts:[]},Fe.onupdatemodelcontext=async(Ee)=>{if(!ke)return{};return await Nr("/api/ext-app/model-context",{nodeId:Z,...Array.isArray(Ee.content)?{content:Ee.content}:{},...Ee.structuredContent&&typeof Ee.structuredContent==="object"?{structuredContent:Ee.structuredContent}:{}}),{}};let Xi=new im(un,un);if(Fe.oninitialized=()=>{if(le)return;To(),d.current=!0,x.current=!0,At(Z,"initialized"),w("ready"),z(null),Promise.resolve(Fe.sendHostContextChange(xn(ln?"fullscreen":"inline"))).then(()=>A_(Fe,a.current,void 0)).then(()=>jr(Fe)).then(()=>{let Ee=()=>{for(let ut of b.current.splice(0))ut()};if(typeof navigator<"u"&&zr(navigator.userAgent))Nn(4000).then((ut)=>{At(Z,ut?"settled (content-verified)":`settled (content-timeout${v.current?`: ${v.current}`:""})`),Ee()});else At(Z,"settled"),Ee();no(),Ur()}).catch((Ee)=>{let ut=Ee instanceof Error?Ee.message:String(Ee);z(`Bridge bootstrap failed: ${ut}`)})},Ce=setTimeout(()=>{if(le||d.current)return;let Ee=c.current,ut=xn(ln?"fullscreen":"inline");d.current=!0,Fe.setHostContext?.(ut),Promise.resolve(Fe.sendHostContextChange(ut)).then(()=>A_(Fe,a.current,Ee)).then(()=>{if(l.current=Boolean(Ee),Ee)u.current=Ee;if(w(Ee?"done":"ready"),z(null),no(),Ur(),g.current){At(Z,"settled (fallback)");for(let Ht of b.current.splice(0))Ht()}}).catch((Ht)=>{let oo=Ht instanceof Error?Ht.message:String(Ht);z(`Bridge bootstrap fallback failed: ${oo}`)})},1200),await Fe.connect(Xi),le){To(),await Xi.close();return}if(o.current=Fe,r.current=Xi,Bt=new ResizeObserver(wn),Bt.observe(Q),Q.parentElement)Bt.observe(Q.parentElement);let Ki=!0;m.current=gt.subscribe((Ee)=>{if(Ki){Ki=!1;return}if(le)return;Fe.setHostContext?.({...xn(),theme:ko(Ee)}),Fe.sendHostContextChange?.(xn())}),jr(Fe)})().catch((un)=>{To(),console.error("[ext-app] Bridge init failed:",un),z(un?.message??"Bridge initialization failed")}),()=>{if(le=!0,To(),Ie)clearTimeout(Ie),Ie=null;if(Bt?.disconnect(),Bt=null,zn!==null)cancelAnimationFrame(zn),zn=null;if(Un!==null)cancelAnimationFrame(Un),Un=null;if(d.current=!1,p.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((un)=>{console.error("[ext-app] transport close failed:",un)}),r.current=null}},[xe,Gt.key,ie]),H(()=>{if(cn&&o.current&&(N==="ready"||N==="done"))jr(o.current)},[cn,N]),H(()=>{let Q=o.current;if(n.current)n.current.style.height="100%";if(!Q||!d.current)return;let le=null,Ce=null;return le=requestAnimationFrame(()=>{le=null,Ce=requestAnimationFrame(()=>{if(Ce=null,!d.current)return;let Ie={theme:ko(gt.value),platform:"web",containerDimensions:um(n.current,{width:e.size.width,height:re}),displayMode:ln?"fullscreen":"inline",locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone};Q.setHostContext?.(Ie),Q.sendHostContextChange?.(Ie)})}),()=>{if(le!==null)cancelAnimationFrame(le);if(Ce!==null)cancelAnimationFrame(Ce)}},[ln,re]),!ue)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 ",Pn," 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:[be&&be!=="ready"&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:be==="error"&&!cr?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 10%, transparent)",color:be==="error"&&!cr?"var(--c-danger)":"var(--c-warn)",borderBottom:`1px solid ${be==="error"&&!cr?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 15%, transparent)"}`},children:Hr},void 0,!1,void 0,this),k&&i("div",{style:{padding:"6px 10px",fontSize:"11px",background:"color-mix(in srgb, var(--c-danger) 12%, transparent)",color:"var(--c-danger)",borderBottom:"1px solid color-mix(in srgb, var(--c-danger) 12%, transparent)",display:"flex",alignItems:"center",gap:"6px"},children:[i("span",{children:"⚠"},void 0,!1,void 0,this),i("span",{style:{flex:1},children:k},void 0,!1,void 0,this),i("button",{type:"button",onClick:()=>{z(null),w("loading"),W((Q)=>Q+1)},style:{background:"var(--c-surface-hover)",border:"1px solid color-mix(in srgb, var(--c-danger) 12%, transparent)",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),"aria-label":"Dismiss error",style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:i(Ve,{size:14},void 0,!1,void 0,this)},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:[ie&&i("iframe",{ref:n,...Gt.attributes,sandbox:T,allow:x_(de?.permissions),style:{flex:1,width:"100%",height:"100%",minHeight:0,border:"none",background:"var(--c-panel)",pointerEvents:ln?"auto":"none"},title:`Ext App: ${Pn}`},xe,!1,void 0,this),S&&!k&&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:(Q)=>{Q.stopPropagation(),At(Z,"manual-retry"),f.current=0,q(!1),w("loading"),W((le)=>le+1)},style:{background:"var(--c-surface-hover)",border:"1px solid color-mix(in srgb, var(--c-warn) 15%, transparent)",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),(N==="loading"||J)&&!k&&!S&&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:N==="loading"?`Connecting to ${Pn}...`:"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),!ln&&!(S&&!k)&&i("button",{type:"button",onClick:(Q)=>{Q.stopPropagation(),kn(Z)},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)}var Xs=new Map,R_=!1;function M_(e,t,n){if(!R_)R_=!0,nn(()=>{let s=F.value,a=yr.value;for(let[c,l]of Xs){let u=s.get(c);if(!u||l.epoch!==a||l.version!==u.data.specVersion||l.documentUrl!==u.data.url)Xs.delete(c)}}),window.addEventListener("message",(s)=>{let a=s.data;if(!a||a.source!==bp||a.type!=="snapshot"||typeof a.nodeId!=="string")return;let c=Xs.get(a.nodeId),l=c?.owners.findIndex((d)=>d.token===a.token&&d.source===s.source)??-1;if(!c||l<0)return;if(!a.state||typeof a.state!=="object"||Array.isArray(a.state))return;let{ax:u,...p}=a.state;c.state=p,c.owners=c.owners.slice(l)});let o=F.value.get(e);if(!o)return;let r=Xs.get(e);if(!r)r={epoch:yr.value,version:o.data.specVersion,documentUrl:o.data.url,state:null,owners:[]},Xs.set(e,r);r.owners=[...r.owners.filter((s)=>s.source!==n).slice(-1),{token:t,source:n}],n.postMessage({source:bp,type:"restore",token:t,state:r.state},"*")}function CP(e,t,n,o,r,s,a,c){if(!e)return e;try{let l=Se()&&e.startsWith("/"),u=new URL(e,l?"https://pmx.invalid":window.location.origin);if(u.searchParams.set("theme",Go(gt.value)),t)u.searchParams.set("display","expanded");if(typeof n==="number")u.searchParams.set("v",String(n));if(o)u.searchParams.set("axToken",o);if(r)u.searchParams.set("axNodeId",r);if(s)u.searchParams.set("frameToken",s);if(a)u.searchParams.set("fit","content");if(c)u.searchParams.set("stateToken",c);return l?`${u.pathname}${u.search}`:u.toString()}catch{return e}}function EP(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 dm({source:e,iframeRef:t,onLoad:n,onDocumentLoad:o,title:r,className:s="mcp-app-frame",sandbox:a="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",allow:c="clipboard-read; clipboard-write",tabIndex:l}){let u=e.src??e.srcdoc??"",[p,d]=A({key:u,source:e}),[m,f]=A(null),h=L(0);H(()=>{if(h.current+=1,!u||u===p.key){f(null);return}if(!p.key){d({key:u,source:e});return}f({key:u,source:e})},[u,p.key]),H(()=>()=>{h.current+=1},[]);let v=(x,g)=>i("iframe",{ref:g?void 0:t,...x.source,class:s,sandbox:a,allow:c,tabIndex:l,loading:Rt.value==="srcdoc"?void 0:"lazy",onLoad:(b)=>{if(o?.(b.currentTarget),!g){n();return}let I=++h.current,R=b.currentTarget;requestAnimationFrame(()=>requestAnimationFrame(()=>{if(h.current!==I)return;t.current=R,d(x),f(null),n()}))},style:{position:"absolute",inset:0,width:"100%",height:"100%",visibility:g?"hidden":"visible",background:"var(--c-panel-soft)"},title:r},x.key,!1,void 0,this);return i("div",{class:"mcp-app-frame-stack",children:[v(p,!1),m&&v(m,!0)]},void 0,!0,void 0,this)}function Ko({node:e,expanded:t=!1}){if(e.data.mode==="ext-app")return i(z_,{node:e,expanded:t},void 0,!1,void 0,this);return i(AP,{node:e,expanded:t},void 0,!1,void 0,this)}function AP({node:e,expanded:t}){let n=L(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=Be(()=>c?`ax-${crypto.randomUUID()}`:"",[c]),p=Pp(e)&&!t,d=Be(()=>p?`frame-${crypto.randomUUID()}`:"",[p]);ki(e,n,d),Ni({enabled:c&&Boolean(u),token:u,nodeId:e.id,sourceSurface:l,iframeRef:n});let m=Dn.value,f=()=>{if(!c||!u||m==null)return;n.current?.contentWindow?.postMessage({source:Tn,type:"ax-update",token:u,state:m},"*")};H(f,[c,u,m]);let h=typeof e.data.specVersion==="number"?e.data.specVersion:void 0,v=Be(()=>r?`ui-${crypto.randomUUID()}`:"",[r,h,e.data.url]),x=CP(e.data.url||"",t,h,u||void 0,c?e.id:void 0,d||void 0,p,v||void 0),g=Ti(x),b=e.data.sourceServer||"",I=e.data.hostMode||"hosted",R=e.data.fallbackReason,M=e.data.trustedDomain===!0||EP(x);if(I==="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),R&&i("div",{style:{color:"var(--c-muted)",fontSize:"11px"},children:["Reason: ",R]},void 0,!0,void 0,this),i("a",{href:x,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all"},children:x},void 0,!1,void 0,this),b&&i("div",{style:{color:"var(--c-dim)",fontSize:"10px"},children:["Source: ",b]},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:[!M&&i("div",{style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-warn) 10%, transparent)",color:"var(--c-warn)",borderBottom:"1px solid color-mix(in srgb, var(--c-warn) 15%, transparent)"},children:"Unverified domain"},void 0,!1,void 0,this),i(dm,{source:g,iframeRef:n,onDocumentLoad:(_)=>{if(v&&_.contentWindow)M_(e.id,v,_.contentWindow)},onLoad:f,title:`MCP App: ${b}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var IP=null;function Ri(){IP=null}var $_={idle:"var(--c-muted)",running:"var(--c-accent)",planning:"var(--c-agent)",thinking:"var(--c-agent)",drafting:"var(--c-accent)",tooling:"var(--c-accent)",review:"var(--c-ok)","waiting-approval":"var(--c-warn)",waiting:"var(--c-warn)"};function PP(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 Il({node:e}){let t=PP(e),n=e.data.detail||"",o=e.data.message||"",r=e.data.level||"ok",s=e.data.activeTool,a=e.data.subagent,c=$_[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-agent)"},children:[i("span",{style:{fontSize:"10px"},children:"⚙"},void 0,!1,void 0,this),i("span",{style:{fontFamily:"var(--font-code)",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 Mi(e){return typeof e==="string"&&e.trim().length>0?e.trim():null}function O_(e){if(typeof e==="string"){let r=Mi(e);return r?{title:"Evidence warning",detail:r}:null}if(!e||typeof e!=="object")return null;let t=e,n=Mi(t.title)??"Evidence warning",o=Mi(t.detail);return o?{title:n,detail:o}:null}function NP(e){let t=[],n=O_(e.data.warning);if(n)t.push(n);let o=e.data.warnings;if(Array.isArray(o))for(let s of o){let a=O_(s);if(a)t.push(a)}let r=Mi(e.data.validationStatus)?.toLowerCase();if(r==="failed"||r==="invalid")t.push({title:"Image failed validation",detail:Mi(e.data.validationMessage)??"Review this image before using it as evidence."});return t}function zP(e){let t=[e.data.title,e.data.caption,e.data.alt,e.data.src,e.data.path].map((n)=>Mi(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 L_(e){let t=NP(e);if(t.length>0)return t;if(zP(e))return[{title:"Captured login page",detail:"This image looks like an auth screen. Treat it as environment context, not product evidence."}];return[]}function Pl({node:e,expanded:t=!1}){let n=e.data.src||"",o=e.data.alt||e.data.title||"Image",r=e.data.caption||"",s=L_(e),a=hi(n.startsWith("data:")||n.startsWith("http://")||n.startsWith("https://")?n:`/api/canvas/image/${e.id}`),[c,l]=A(!1),[u,p]=A(!1),[d,m]=A(1),[f,h]=A({x:0,y:0}),[v,x]=A({w:0,h:0}),g=L(null),b=L(!1),I=L({x:0,y:0}),R=j((J)=>{let G=J.target;x({w:G.naturalWidth,h:G.naturalHeight}),l(!0),p(!1)},[]),M=j(()=>{p(!0),l(!1)},[]);H(()=>{m(1),h({x:0,y:0})},[n]);let _=j((J)=>{J.preventDefault(),J.stopPropagation();let G=J.deltaY>0?0.9:1.1;m((S)=>Math.max(0.25,Math.min(10,S*G)))},[]),N=j((J)=>{if(d<=1)return;J.stopPropagation(),b.current=!0,I.current={x:J.clientX,y:J.clientY},J.target.setPointerCapture(J.pointerId)},[d]),w=j((J)=>{if(!b.current)return;let G=J.clientX-I.current.x,S=J.clientY-I.current.y;I.current={x:J.clientX,y:J.clientY},h((q)=>({x:q.x+G,y:q.y+S}))},[]),k=j(()=>{b.current=!1},[]),z=j(()=>{m(1),h({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 X=v.w>0?`${v.w}×${v.h}`:"",W=Math.round(d*100);return i("div",{class:`image-node ${t?"image-node-expanded":""}`,ref:g,children:[s.length>0&&i("div",{class:"image-node-warning-stack",children:s.map((J)=>i("div",{class:"image-node-warning",children:[i("span",{class:"image-node-warning-title",children:J.title},void 0,!1,void 0,this),i("span",{class:"image-node-warning-detail",children:J.detail},void 0,!1,void 0,this)]},`${J.title}-${J.detail}`,!0,void 0,this))},void 0,!1,void 0,this),i("div",{class:"image-node-viewport",onWheel:_,onPointerDown:N,onPointerMove:w,onPointerUp:k,style:{cursor:d>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:R,onError:M,draggable:!1,style:{transform:`translate(${f.x}px, ${f.y}px) scale(${d})`,opacity:c?1:0,display:u?"none":"block"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(r||X||d!==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:[X&&i("span",{children:X},void 0,!1,void 0,this),d!==1&&i("button",{type:"button",class:"image-node-zoom-reset",onClick:z,title:"Reset zoom",children:[W,"% ",i(Pc,{size:14},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 D_({node:e}){if((e.data.children??[]).filter((o)=>F.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 RP(e){try{return new URL(e).host}catch{return e}}function MP(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Nl({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=MP(typeof e.data.fetchedAt==="string"?e.data.fetchedAt:void 0),u=typeof e.data.statusCode==="number"?e.data.statusCode:null,p=typeof e.data.imageUrl==="string"?e.data.imageUrl:"",d=e.data.frameBlocked===!0,m=typeof e.data.frameBlockedReason==="string"?e.data.frameBlockedReason:"",[f,h]=A(!1),[v,x]=A(t);H(()=>{if(t)x(!0)},[t]);let g=j(async()=>{if(!n||f)return;h(!0);try{await gc(e.id)}finally{h(!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 b=a==="ready"?"var(--c-ok)":a==="error"?"var(--c-danger)":"var(--c-muted)";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:RP(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:b,fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.04em",flexShrink:0},children:[i("span",{style:{width:"7px",height:"7px",borderRadius:"999px",background:b}},void 0,!1,void 0,this),a]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(r||p)&&i("div",{style:{display:"grid",gridTemplateColumns:p&&t?"160px 1fr":"1fr",gap:"12px",alignItems:"start"},children:[p&&t&&i("img",{src:p,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:g,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&&!d&&i("button",{type:"button",onClick:()=>x((I)=>!I),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:v?"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&&d&&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&&v&&!d&&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),d&&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 F_(e){return e.type==="html"&&e.data.presentation===!0}function $P(e){let t=e;if(t?.enabled!==!0)return"disabled";if(!Array.isArray(t.allowed))return"enabled:default";let n=[...new Set(t.allowed.filter((o)=>typeof o==="string"))].sort();return n.length>0?`enabled:${n.join(",")}`:"disabled"}function Ks({node:e,expanded:t=!1,presentation:n=!1,presentationExitToken:o,autoFocus:r=!1}){let s=L(null),a=gt.value,c=$P(e.data.axCapabilities),l=Be(()=>`theme-${crypto.randomUUID()}`,[]),u=Be(()=>`ax-${crypto.randomUUID()}`,[c]),p=Be(()=>`frame-${crypto.randomUUID()}`,[]),d=typeof e.data.html==="string"?e.data.html:typeof e.data.content==="string"?e.data.content:"",m=Be(()=>bi(d),[d]),f=Be(()=>d?Rs(e.id,{theme:a,themeToken:l,present:n,presentToken:o,v:m,axToken:u,frameToken:p}):"",[d,n,o,l,m,e.id,u,p]),h=Ti(f);ki(e,s,t?"":p),Ni({enabled:!0,token:u,nodeId:e.id,sourceSurface:"html-node",iframeRef:s}),H(()=>{if(s.current?.contentWindow?.postMessage({source:Tn,type:"theme-update",token:l,theme:a},"*"),r)s.current?.focus()},[a,l]);let v=e.data.axCapabilities,x=v?.enabled===!0&&(!Array.isArray(v.allowed)||v.allowed.length>0),g=Dn.value;H(()=>{if(!x||g==null)return;s.current?.contentWindow?.postMessage({source:Tn,type:"ax-update",token:u,state:g},"*")},[x,g,u]),H(()=>{if(!r)return;let I=window.setTimeout(()=>s.current?.focus(),0);return()=>window.clearTimeout(I)},[r,f]);let b=()=>{if(s.current?.contentWindow?.postMessage({source:Tn,type:"theme-update",token:l,theme:a},"*"),x&&Dn.value!=null)s.current?.contentWindow?.postMessage({source:Tn,type:"ax-update",token:u,state:Dn.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(dm,{source:h,iframeRef:s,className:n?"html-node-frame html-node-frame-presentation":t?"html-node-frame html-node-frame-expanded":"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"HTML node",sandbox:"allow-scripts",allow:"",tabIndex:r?0:void 0,onLoad:b},void 0,!1,void 0,this)}var pm=null;async function B_(){if(!pm)pm=await hb();return pm}function H_(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 OP({html:e}){let t=L(null);return H(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=Qn(e),n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function LP(e,t){return`${e.role}:${e.status??"none"}:${t}:${e.text}`}function j_({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 U_({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,"aria-label":"Dismiss error",style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function zl({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",p=a==="answered",[d,m]=A(""),[f,h]=A(""),[v,x]=A(null),[g,b]=A(new Map),I=L(null),R=L(null),M=n[n.length-1],_=`${n.length}:${M?.role??""}:${M?.status??""}:${Math.floor((M?.text?.length??0)/200)}`;H(()=>{if(t&&c&&I.current)I.current.focus()},[t,c]),H(()=>{if(!_)return;if(R.current)R.current.scrollTo({top:R.current.scrollHeight,behavior:"smooth"})},[_]);let N=L(null),w=L(n);w.current=n,H(()=>{let G=n.some((q)=>q.role==="assistant"&&q.status==="streaming"),S=()=>{let q=!1,ye=w.current.map((ue,Pe)=>({turn:ue,index:Pe})).filter(({turn:ue})=>ue.role==="assistant"&&ue.text);if(ye.length===0)return;return Promise.all(ye.map(async({turn:ue,index:Pe})=>{let ke=await Vn(ue.text);return{index:Pe,html:Qn(ke)}})).then((ue)=>{if(q)return;let Pe=new Map;for(let ke of ue)Pe.set(ke.index,ke.html);b(Pe)}),()=>{q=!0}};if(!G){if(N.current)clearTimeout(N.current),N.current=null;return S()}if(N.current)clearTimeout(N.current);return N.current=setTimeout(()=>{N.current=null,S()},400),()=>{if(N.current)clearTimeout(N.current),N.current=null}},[n]);let k=j(async()=>{let G=d.trim();if(!G)return;let S=d;x(null),fe(e.id,{turns:[{role:"user",text:G,status:"pending"}],threadStatus:"pending",text:G}),m("");let q=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds:void 0;if(!(await ys(G,e.position,e.id,q,e.id)).ok)fe(e.id,{turns:[],threadStatus:"draft",text:"",status:"draft"}),m(S),x("Failed to send prompt. Your draft has been restored.")},[d,e.id,e.position,e.data.contextNodeIds]),z=j(async()=>{let G=f.trim();if(!G)return;let S=f;x(null);let q=Array.isArray(e.data.turns)?[...e.data.turns]:[];if(q.push({role:"user",text:G,status:"pending"}),fe(e.id,{turns:q,threadStatus:"pending"}),h(""),!(await gb(e.id,G)).ok)q.pop(),fe(e.id,{turns:q,threadStatus:"answered"}),h(S),x("Failed to send reply. Your draft has been restored.")},[f,e.id,e.data.turns]),X=j((G)=>{if(G.key==="Enter"&&(G.metaKey||G.ctrlKey)){G.preventDefault(),k();return}if(G.key==="Tab"&&d.startsWith("/")){G.preventDefault();let S=d.slice(1).split(/\s/)[0];if(S)B_().then((q)=>{let ie=H_(S,q);if(ie)m(`/${ie}`)})}},[k,d]),W=j((G)=>{if(G.key==="Enter"&&(G.metaKey||G.ctrlKey)){G.preventDefault(),z();return}if(G.key==="Tab"&&f.startsWith("/")){G.preventDefault();let S=f.slice(1).split(/\s/)[0];if(S)B_().then((q)=>{let ie=H_(S,q);if(ie)h(`/${ie}`)})}},[z,f]),J=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(j_,{count:J},void 0,!1,void 0,this),i(U_,{message:v,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("textarea",{ref:I,value:d,onInput:(G)=>m(G.target.value),onKeyDown:X,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-ui)",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:k,disabled:!d.trim(),style:{padding:"5px 14px",fontSize:"12px",fontWeight:600,background:d.trim()?"var(--c-accent)":"var(--c-line)",color:d.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:d.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)":p?"var(--c-ok)":"var(--c-muted)"},children:l?"Sending…":p?"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(j_,{count:J},void 0,!1,void 0,this),i(U_,{message:v,onDismiss:()=>x(null)},void 0,!1,void 0,this),i("div",{ref:R,style:{flex:1,overflow:"auto",minHeight:0},children:n.map((G,S)=>i("div",{children:[S>0&&i("div",{class:"thread-turn-divider"},void 0,!1,void 0,this),G.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:G.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${G.status==="streaming"?" pulsing":""}`},void 0,!1,void 0,this),"PMX"]},void 0,!0,void 0,this),G.status==="streaming"&&!G.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:G.text?1:0.4},children:g.get(S)?i(_e,{children:[i(OP,{html:g.get(S)??""},void 0,!1,void 0,this),G.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:G.status==="streaming"?"Waiting for response…":G.text||"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},LP(G,S),!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:p?"6px":0},children:[i("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:u?"var(--c-accent)":l?"var(--c-warn)":p?"var(--c-ok)":"var(--c-muted)"},children:u?"Streaming…":l?"Sending…":p?"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),p&&i("div",{class:"thread-reply-area",children:[i("textarea",{value:f,onInput:(G)=>h(G.target.value),onKeyDown:W,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-ui)",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 DP({html:e}){let t=L(null);return H(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=Qn(e),n.append(o.content.cloneNode(!0))},[e]),i("div",{ref:t},void 0,!1,void 0,this)}function Rl({node:e,expanded:t=!1}){let n=e.data.content||"",o=e.data.status||"streaming",[r,s]=A(""),a=o==="streaming",c=o==="complete";H(()=>{if(!n){s("");return}let u=!1;return Vn(n).then((p)=>{if(!u)s(Qn(p))}),()=>{u=!0}},[n]);let l=j(()=>{ys("",{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(DP,{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 Z_(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 W_={mcp:"var(--c-muted)",file:"var(--c-muted)",subagent:"var(--c-subagent)",other:"var(--c-muted)"},FP={running:"⠋",success:"✓",failed:"✕"},BP={running:"var(--c-accent)",success:"var(--c-ok)",failed:"var(--c-danger)"};function Ml({node:e}){let{toolName:t,category:n,status:o,duration:r,resultSummary:s,error:a}=Z_(e.data),c=W_[n]??W_.other,l=FP[o]??"◌",u=BP[o]??"var(--c-muted)",p=o==="running",d=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:p?"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(--font-code)",fontSize:"11px",fontWeight:600,color:c,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t},void 0,!1,void 0,this),d&&i("div",{style:{fontSize:"10px",color:a?"var(--c-danger)":"var(--c-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1.3},children:d},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)}var HP=new Set(["png","jpg","jpeg","gif","svg","webp","bmp","ico","avif"]),jP=new Set(["md","mdx","markdown"]);function UP(e){let t=e.split(".").pop()?.toLowerCase()??"";if(HP.has(t))return"image";if(jP.has(t))return"markdown";return"file"}async function $i(e,t,n){let o=Oe.value,r=400,s=300,a=20,c=Math.ceil(Math.sqrt(e.length));for(let l=0;l<e.length;l++){let u=e[l],p=l%c,d=Math.floor(l/c),m=t-c*420/2+p*420,f=n-150+d*320,h=UP(u.name),v=u.name;if(/\.(pdf|pptx?|xlsx?|docx?|od[pts])$/i.test(v)){if(!o||u.size===0||u.size>20971520){on("remove","File not attached","Open a board and choose a nonempty file under 20 MiB.");continue}let x=new URLSearchParams({boardId:o,name:v,mime:u.type,x:String(m),y:String(f)});on("context","Attaching document",v),await ne("attachDocument",`/api/canvas/attachments?${x}`,null,{method:"POST",body:u});continue}if(Oe.value!==o)return;if(h==="image"){let x=new FileReader,g=await new Promise((b)=>{x.onload=()=>b(x.result),x.readAsDataURL(u)});if(Oe.value!==o)return;await On({type:"image",title:v,content:g,x:m,y:f,width:400,height:300,...o?{boardId:o}:{}})}else{let x=await u.text();if(Oe.value!==o)return;let g=h==="markdown"||h==="file";await On({type:h,title:v,content:x,x:m,y:f,width:g?720:400,height:g?500:300,...o?{boardId:o}:{}})}}}var q_={width:260,height:150},ZP={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 fm(e){return!!e&&e in Nt}function bo(e){if(!e)return null;let t=F.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 mm(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Js(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 G_(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 hm({intent:e}){let t=fm(e.nodeType)?Bn(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:()=>wi.value=e.id,onMouseLeave:()=>{if(wi.value===e.id)wi.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(),br(e)},children:i(Ve,{size:14},void 0,!1,void 0,this)},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 V_({intent:e,rect:t}){let n=fm(e.nodeType)?Bn(e.nodeType):null,o=fm(e.nodeType)?Nt[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:Js(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(hm,{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:Js(e)},children:[n==="edit"&&i("div",{class:"intent-edit-bar"},void 0,!1,void 0,this),i(hm,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function WP(e){let t=e.phase==="settling"?bo(e.settledNodeId):null;switch(e.kind){case"create":{if(!e.position)return null;let n=e.nodeType&&ZP[e.nodeType]||q_,o=t??{left:e.position.x,top:e.position.y,...n};return i(V_,{intent:e,rect:o},e.id,!1,void 0,this)}case"move":{if(!e.position)return null;let o=bo(e.nodeId)??q_,r=t??{left:e.position.x,top:e.position.y,width:o.width,height:o.height};return i(V_,{intent:e,rect:r},e.id,!1,void 0,this)}case"remove":{let n=t??bo(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??bo(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=bo(e.edge.from),o=bo(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:Js(e)},children:i(hm,{intent:e},void 0,!1,void 0,this)},e.id,!1,void 0,this)}default:return null}}function K_(){let e=Array.from(lt.value.values());if(H(()=>{function t(n){if(n.key!=="Escape")return;let o=wi.value;if(!o)return;let r=lt.value.get(o);if(!r||r.phase!=="forming")return;n.stopImmediatePropagation(),n.preventDefault(),br(r)}return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[]),e.length===0)return null;return i("div",{class:"intent-layer",onAnimationEnd:(t)=>{if(t.animationName!=="intent-settle"&&t.animationName!=="intent-dissolve")return;let n=t.target.dataset.intentId;if(n&&lt.value.get(n)?.phase!=="forming")Er(n)},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=bo(t.edge.from),o=bo(t.edge.to);if(!n||!o)return null;return i("path",{d:G_(mm(n),mm(o)),class:`intent-edge type-${t.edge.type}`,style:{opacity:Js(t)}},`line-${t.id}`,!1,void 0,this)}if(t.kind==="move"&&t.position){let n=bo(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:G_(mm(n),r),class:"intent-trail",markerEnd:"url(#intent-arrow)",style:{opacity:Js(t)}},`line-${t.id}`,!1,void 0,this)}return null})]},void 0,!0,void 0,this),e.map(WP)]},void 0,!0,void 0,this)}var J_=32000;var $l="Agent session";function Y_(e){return e.some((t)=>t.attached)}function Q_(e){return e.filter((t)=>!t.attached)}function Jo(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"}}var It=K([]),gm=K({used:0,total:J_}),Yo=K([]),Rr=K(!1),Oi=K(!1),vm=K(null);function An(e){return It.value.find((n)=>n.sessionId===e)?.parentAgentId?"var(--c-subagent)":"var(--c-agent)"}function eS(e){return(e.trim().replace(/^[^a-z0-9]+/i,"").charAt(0)||e.trim().charAt(0)||"?").toUpperCase()}function Ol(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 _t=Ge(()=>Y_(It.value)),ym=Ge(()=>Q_(It.value)),tS=Ge(()=>{let e=new Set;return[...It.value].filter((t)=>t.label!==$l).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))}),nS=Ge(()=>It.value.filter((e)=>e.attached)),Li=Ge(()=>It.value.find((e)=>e.attached)??null);function qP(e){let t=new Set;for(let n of e)if(n.nodeId&&n.kind!=="create")t.add(n.nodeId);return t}var Ll=Ge(()=>qP(lt.value.values()));function Dl(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 bm(e){if(!e)return;if(Array.isArray(e.presences))It.value=e.presences;if(e.budget&&Number.isFinite(e.budget.used)&&Number.isFinite(e.budget.total))gm.value={used:e.budget.used,total:e.budget.total};if(Array.isArray(e.activity))Yo.value=e.activity}function oS(){let e=L(new Map),t=oe.value.scale,n=F.value,o=1/Math.max(0.05,t),r=It.value.map((s)=>{let a=Dl(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.cursor?" has-explicit-cursor":""}${s.attached?"":" is-external"}${s.parentAgentId?" is-worker":""}`,"data-session-id":s.sessionId,style:{transform:`translate(${a.x}px, ${a.y}px)`,"--identity-color":An(s.sessionId)},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:Jo(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 xo(e=1000){let[t,n]=A(()=>Date.now());return H(()=>{if(e<=0)return;n(Date.now());let o=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(o)},[e]),t}function rS(){let e=xo(Os.value.length>0?5000:0),t=Os.value.filter((o)=>o.cursor!==null&&(!o.lastSeenAt||e-Date.parse(o.lastSeenAt)<Ow+5000));if(t.length===0)return null;let n=1/Math.max(0.05,oe.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 Fl(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 wm(){let e=Dn.value;return e&&typeof e==="object"?e:{}}var iS=Ge(()=>wm().workItems??[]),_m=Ge(()=>wm().approvalGates??[]),Mr=Ge(()=>_m.value.filter((e)=>e.status==="pending")),Qo=Ge(()=>{let e=wm().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 sS(e){return(await mn("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 aS=Ge(()=>_m.value.filter((e)=>e.status==="held")),cS=Ge(()=>_m.value.filter((e)=>e.status==="approved"||e.status==="rejected")),lS=K({events:[],evidence:[],steering:[]}),$r=K("all");function Sm(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 GP=new Set(["api","mcp","sdk","cli"]);function xm(e,t){if(e?.trim())return e.trim();let n=t?.trim();if(n&&!GP.has(n))return n;return null}var VP=/^(node|edge|group|annotation|jsonrender|graph|render)\.|^arrange$|^canvas\.clear$|^snapshot\.restore$/,uS=K(null),ea=K(new Set),XP={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 KP(e,t=40,n=[],o=null,r="all"){let s=n.find((l)=>VP.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,...!Se()&&o?.actor==="agent"&&s?.id===l.id?{undoable:!0}:{}})),...e.events.map((l)=>({id:`event-${l.id}`,kind:l.kind,label:XP[l.kind]??l.kind,body:l.detail?`${l.summary} — ${l.detail}`:l.summary,createdAt:l.createdAt,who:xm(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:xm(l.agentId,l.source)})),...e.steering.map((l)=>{let u=l.agentId??(l.source&&l.source!=="browser"?l.source:null),p=l.target?`→ ${l.target} · `:u?"→ all · ":"",d=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} `:""}${p}${l.message}${d}`,createdAt:l.createdAt,who:xm(l.agentId,l.source)}})],c=r==="all"?a:a.filter((l)=>Sm(l.kind)===r);return c.sort((l,u)=>l.createdAt<u.createdAt?1:l.createdAt>u.createdAt?-1:0),c.slice(0,t)}var dS=Ge(()=>KP(lS.value,40,Yo.value,uS.value,$r.value));async function er(){let[e,t]=await Promise.all([ne("refreshTimeline","/api/canvas/ax/timeline?limit=40",null),ne("refreshHistoryTop","/api/canvas/history",null)]);if(t)uS.value=t.top??null;if(!e)return;lS.value={events:Array.isArray(e.events)?e.events:[],evidence:Array.isArray(e.evidence)?e.evidence:[],steering:Array.isArray(e.steering)?e.steering:[]}}async function km(e){if(!(await mn("undoAgentEdit","/api/canvas/undo",{method:"POST"})).ok)return!1;return ea.value=new Set([...ea.value,e.id]),await $n("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"})}),er(),!0}async function Tm(e=!1){if(Se())return on("remove","Undo / redo unavailable","Open the local PMX workbench to use shared history."),!1;let t=await mn(e?"redo":"undo",e?"/api/canvas/redo":"/api/canvas/undo",{method:"POST"});if(t.ok)er();return t.ok}async function pS(e,t){if(!(await mn("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 $n("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 mS(e){return(await mn("reopenGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/reopen`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser"})})).ok}async function fS(e,t){return(await mn("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 tr(){return(await mn("startSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser",label:$l,attached:!0,phase:"idle"})})).ok}async function Bl(e){return(await mn("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}function Ys(e){if(!Array.isArray(e))return[];return e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let n=t;if(typeof n.id!=="string"||typeof n.title!=="string")return[];return[{id:n.id,title:n.title,...typeof n.reason==="string"?{reason:n.reason}:{}}]})}var nr=K(null);function Cm(e){let t=Di.value?.context;nr.value=e&&t?new Set([...t.read,...t.pinned,...t.created,...t.edited].map((n)=>n.id)):null}var Di=K(null);function Qs(e,t){let n=new Set(e.map((o)=>o.id));return[...e,...t.filter((o)=>!n.has(o.id))]}function JP(e,t){return{labels:[...new Set([...e.labels,...t.labels])],sessions:e.sessions+1,endedAt:t.endedAt,endedBy:e.endedBy===t.endedBy?t.endedBy:void 0,counts:t.counts,snapshot:null,context:{read:Qs(e.context.read,t.context.read),pinned:Qs(e.context.pinned,t.context.pinned),created:Qs(e.context.created,t.context.created),edited:Qs(e.context.edited,t.context.edited),changedSinceRead:Qs(e.context.changedSinceRead,t.context.changedSinceRead)}}}function hS(e){let{counts:t,snapshot:n,context:o}=e;if(typeof e.label!=="string"||typeof e.endedAt!=="string")return;if(e.unchanged===!0||typeof e.parentAgentId==="string")return;let r={labels:[e.label],sessions:1,endedAt:e.endedAt,endedBy:e.endedBy==="human"||e.endedBy==="agent"||e.endedBy==="idle-timeout"?e.endedBy:void 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,context:{read:Ys(o?.read),pinned:Ys(o?.pinned),created:Ys(o?.created),edited:Ys(o?.edited),changedSinceRead:Ys(o?.changedSinceRead)}},s=Di.value;if(Di.value=s?JP(s,r):r,s&&nr.value)Cm(!0)}function Hl(){Di.value=null,nr.value=null}function gS(){if(!_t.value)return null;let e=Qo.value;if(!e)return null;let t=F.value,n=e.nodeIds.map((s)=>t.get(s)).filter((s)=>s!==void 0),o=Fl(n,e.padding);if(!o)return null;let r=1/Math.max(0.05,oe.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 vS=K(new Map),ta=K({});function Em(e){vS.value=new Map((e.nodes??[]).map((t)=>[t.nodeId,t])),ta.value=e.pins??{}}async function jl(){let e=await ne("fetchContextStatus","/api/canvas/ax/context-status",{});if(e.ok&&e.boardId===Oe.value)Em(e)}function yS(e,t){let n=vS.value.get(e),o=ta.value[e]?.pinnedAt;if(!n||o&&n.lastReadAt<o)return{kind:"not-read"};if(t>n.readRevision)return{kind:"changed",by:n.lastReadBy,at:n.lastReadAt};return{kind:"read",by:n.lastReadBy,at:n.lastReadAt,count:n.readCount}}function Ul(e){return e.agentId?.trim()||e.source}var bS="",xS=new Map,wS=Ge(()=>{let e=Le.value,t=new Map;if(e.size>0){let o=new Map;for(let r of wd([...F.value.values()],e)){let s=r.pinnedNodeTitle??r.pinnedNodeId;for(let a of r.neighbors){let c=o.get(a.id)??[];c.push({pinNodeId:r.pinnedNodeId,pinTitle:s,distance:a.distance}),o.set(a.id,c)}}for(let[r,s]of o)s.sort((a,c)=>a.distance-c.distance),t.set(r,s.map(({pinNodeId:a,pinTitle:c})=>({pinNodeId:a,pinTitle:c})))}let n=[...t].sort(([o],[r])=>o.localeCompare(r)).map(([o,r])=>`${o}:${r.map((s)=>`${s.pinNodeId}=${s.pinTitle}`).join(",")}`).join("|");if(n===bS)return xS;return bS=n,xS=t,t});function Qe({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)}var Zl={eye:"M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12zM12 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5",eyeOff:"M3 3l18 18M10.6 6.1A10 10 0 0 1 12 6c6.5 0 10 6 10 6a17 17 0 0 1-3 3.6M6.6 6.6C3.8 8.3 2 12 2 12s3.5 6 10 6a9.6 9.6 0 0 0 4.4-1",spark:"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z",pen:"M4 20l4.2-1L19 8.2 15.8 5 5 15.8z",warn:"M12 4l9 16H3zM12 10v4M12 17v.5"};function _S(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function YP(e,t){if(t){let n=ta.value[e.id],o=n?.pinnedBy.actor==="agent"?` Pinned by ${Ul(n.pinnedBy)}${n.reason?`: ${n.reason}`:""}.`:"",r=yS(e.id,e.contentRevision??0);if(r.kind==="not-read")return{tone:"muted",glyph:"eyeOff",word:"not read",label:"Not read yet",body:`In context, but no agent has loaded it since it was pinned.${o}`};if(r.kind==="changed")return{tone:"warn",glyph:"warn",word:"changed since read",label:"The agent's copy is out of date",body:`Changed after ${r.by} read it at ${_S(r.at)}.${o}`};return{tone:"agent",glyph:"eye",word:"read",label:"Read by the agent",body:`${r.count>1?`Read ${r.count} times · last`:"Read"} ${_S(r.at)} by ${r.by}.${o}`}}if(e.lastEditedBy?.actor==="human")return null;if(e.createdBy?.actor==="agent"){let n=Ul(e.createdBy);return{tone:"agent",glyph:"spark",word:`by ${n}`,label:`Created by ${n}`,body:"The byline stays until you edit the node."}}if(e.lastEditedBy?.actor==="agent")return{tone:"agent",glyph:"pen",word:"edited",label:`Edited by ${Ul(e.lastEditedBy)}`,body:"The mark stays until you edit the node."};return null}function SS({node:e,pinned:t}){let n=YP(e,t);if(!n)return null;return i(Qe,{label:n.label,body:n.body,align:"end",tapToOpen:!0,children:i("span",{class:`node-context-mark is-${n.tone}`,"data-mark":n.word,children:[i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:i("path",{d:Zl[n.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),n.word]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function kS(e){return ta.value[e]?.pinnedBy.actor==="agent"}function TS({node:e,pinned:t}){let[n,o]=A(!1),r=t?void 0:wS.value.get(e.id);if(!r||r.length===0)return null;let s=r.length>1?`near ${r.length}`:"near",a=n?r.map((c)=>{let l=F.value.get(c.pinNodeId);return l?`“${c.pinTitle}” (${Math.round(xd(e,l))} px)`:`“${c.pinTitle}”`}).join(", "):"";return i(Qe,{label:n?`Near ${a}`:"Near a pin",body:"The agent gets its title and a short summary, not its full content. Pin it to send its content.",align:"end",tapToOpen:!0,children:i("span",{class:"node-near-mark","data-near":r.map((c)=>c.pinNodeId).join(" "),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocusIn:()=>o(!0),onFocusOut:()=>o(!1),children:[i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[i("circle",{cx:"12",cy:"12",r:"8",class:"node-near-ring"},void 0,!1,void 0,this),i("circle",{cx:"12",cy:"12",r:"2.2",class:"node-near-dot"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function QP(e){let t=typeof e==="number"&&Number.isFinite(e)?Math.floor(e):1;return Math.max(1,Math.min(20,t))}function Wl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function na(e){return typeof e==="string"&&e.length>0}function CS(e){let t=e.axStep;if(!Wl(t))return null;if(!na(t.flowId)||!na(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 ES(e){let t=e.axFlow;if(!Wl(t)||!na(t.flowId)||!Array.isArray(t.steps))return null;let n=[];for(let r of t.steps){if(!Wl(r)||!na(r.nodeId)||!na(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=Wl(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:QP(o.maxRuns)}}}var eN={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)"},IS={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},PS={fontSize:"10px",color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginRight:"auto"},NS={...Tr,background:"color-mix(in srgb, var(--c-accent) 25%, transparent)",color:"var(--c-text)"},tN=[{status:"in-progress",label:"Start",toast:"Step started"},{status:"done",label:"Done",toast:"Step done"},{status:"blocked",label:"Blocked",toast:"Step blocked"}];async function AS(e,t,n){let o={...t,loop:n};fe(e.id,{axFlow:o}),await kt(e.id,{data:{axFlow:o}})}function zS(e){return typeof e?.axWorkStatus==="string"?e.axWorkStatus:"todo"}function nN({node:e,flow:t}){let[n,o]=A(""),{running:r,run:s,maxRuns:a}=t.loop,c=async()=>{await AS(e,t,{running:!0,run:s>=a?0:s,maxRuns:a});let u=t.steps.find((d)=>zS(F.value.get(d.nodeId)?.data)!=="done"),p=u??t.steps[t.steps.length-1];await Uo(e,"ax.work.update",{id:p.workItemId,status:u?"in-progress":"done"},"Loop running")},l=async()=>{let u=n.trim();if(!u)return;await Uo(e,"ax.steer",{message:u},"Steering sent"),o("")};return i("div",{class:"ax-flow-controls",style:{...IS,marginTop:"6px",rowGap:"4px"},children:[i("span",{class:"ax-flow-runs",style:PS,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:NS,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(),AS(e,t,{...t.loop,running:!1})},children:"Stop"},void 0,!1,void 0,this):i("button",{type:"button",class:"ax-node-action",style:Tr,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:Tr,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 ql({node:e}){let t=CS(e.data);if(!t)return null;let n=ES(e.data),o=zS(e.data);return i("div",{class:"ax-step-dock",style:eN,children:[i("div",{class:"ax-step-controls",style:IS,children:[i("span",{class:"ax-step-position",style:PS,children:["Step ",t.index,"/",t.total]},void 0,!0,void 0,this),tN.map((r)=>i("button",{type:"button",class:"ax-node-action","aria-pressed":o===r.status,style:o===r.status?NS:Tr,title:`Set this step's work item to "${r.status}".`,onClick:(s)=>{s.stopPropagation(),Uo(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(nN,{node:e,flow:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Fi=8,Or=K(null),Bi=[],Hi=[],$S=null;function RS(e){let t=e?.data.parentGroup;return typeof t==="string"&&t.length>0?t:null}function MS(e){if(!e||!Array.isArray(e.data.children))return[];return e.data.children.filter((t)=>typeof t==="string")}function oN(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=RS(r);while(s&&!o.has(s))o.add(s),s=RS(n.get(s));if(r.type!=="group")return o;let a=[...MS(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(...MS(l))}return o}function OS(e,t){Bi=[],Hi=[],$S=e;let n=Array.from(t),o=oN(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,p=r.position.y+r.size.height/2;Bi.push({val:s,minY:l,maxY:u}),Bi.push({val:a,minY:l,maxY:u}),Bi.push({val:c,minY:l,maxY:u}),Hi.push({val:l,minX:s,maxX:a}),Hi.push({val:u,minX:s,maxX:a}),Hi.push({val:p,minX:s,maxX:a})}}function LS(){Bi=[],Hi=[],$S=null}function DS(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=Fi+1,p=null;for(let v=0;v<3;v++){let x=r[v];for(let g of Bi){let b=Math.abs(x-g.val);if(b<u)u=b,l=g.val-a[v],p={axis:"x",pos:g.val,from:Math.min(g.minY,t),to:Math.max(g.maxY,t+o)}}}let d=null,m=Fi+1,f=null;for(let v=0;v<3;v++){let x=s[v];for(let g of Hi){let b=Math.abs(x-g.val);if(b<m)m=b,d=g.val-c[v],f={axis:"y",pos:g.val,from:Math.min(g.minX,e),to:Math.max(g.maxX,e+n)}}}let h=[];if(p&&u<=Fi)h.push(p);if(f&&m<=Fi)h.push(f);return{x:l!==null&&u<=Fi?l:e,y:d!==null&&m<=Fi?d:t,guides:h}}function FS({nodeId:e,viewport:t,onMove:n,onDragEnd:o,onClick:r}){let s=L(!1),a=L({x:0,y:0}),c=L({x:0,y:0});return j((u,p,d)=>{u.stopPropagation(),u.preventDefault(),s.current=!0,document.documentElement.classList.add("is-node-dragging"),window.getSelection()?.removeAllRanges(),a.current={x:u.clientX,y:u.clientY},c.current={x:p,y:d};let m=null,f=null,h=!1,v=()=>{if(f=null,!s.current||!m)return;let b=m;m=null;let I=t.value.scale,R=(b.x-a.current.x)/I,M=(b.y-a.current.y)/I;n(e,c.current.x+R,c.current.y+M)},x=(b)=>{if(!s.current)return;if(!h&&Math.hypot(b.clientX-u.clientX,b.clientY-u.clientY)<4)return;if(h=!0,m={x:b.clientX,y:b.clientY},f!==null)return;f=window.requestAnimationFrame(v)},g=(b)=>{if(f!==null)window.cancelAnimationFrame(f),v();if(s.current=!1,document.documentElement.classList.remove("is-node-dragging"),document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",g),document.removeEventListener("pointercancel",g),o(),!h&&b.type==="pointerup")r?.()};document.addEventListener("pointermove",x),document.addEventListener("pointerup",g),document.addEventListener("pointercancel",g)},[e,t,n,o,r])}var rN=200,iN=100;function BS({nodeId:e,viewport:t,onResize:n,onResizeEnd:o}){let r=L(!1),s=L({x:0,y:0}),a=L({w:0,h:0});return j((l,u,p)=>{l.stopPropagation(),l.preventDefault(),r.current=!0,s.current={x:l.clientX,y:l.clientY},a.current={w:u,h:p},document.documentElement.classList.add("is-node-resizing");let d=null,m=null,f=()=>{if(m=null,!r.current||!d)return;let x=d;d=null;let g=t.value.scale,b=(x.x-s.current.x)/g,I=(x.y-s.current.y)/g;n(e,Math.max(rN,a.current.w+b),Math.max(iN,a.current.h+I))},h=(x)=>{if(!r.current)return;if(d={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(f)},v=()=>{if(m!==null)window.cancelAnimationFrame(m),f();r.current=!1,document.documentElement.classList.remove("is-node-resizing"),document.removeEventListener("pointermove",h),document.removeEventListener("pointerup",v),document.removeEventListener("pointercancel",v),o()};document.addEventListener("pointermove",h),document.addEventListener("pointerup",v),document.addEventListener("pointercancel",v)},[e,t,n,o])}var sN={ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1}};function aN(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,p=l*t.dx+u*t.dy;if(p<=0)continue;let d=Math.abs(l*t.dy)+Math.abs(u*t.dx);if(d>p)continue;let m=p+d*2;if(m<a)a=m,s=c}return s}var cN=0.4,lN=0.55,uN=175;function dN(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*cN/Si);if(Number.isFinite(n)&&n>0)r=Math.min(r,n*lN/uN);return Math.max(1,r)}function HS({node:e,children:t,onContextMenu:n}){let o=je.value===e.id,r=Ne.value.has(e.id),s=Le.value.has(e.id),a=oc.value.has(e.id),c=!o&&zb.value.has(e.id),l=uo.value,u=l!==null&&l.has(e.id),p=l!==null&&!l.has(e.id),[d,m]=A(!1),f=L(null),h=j((T,ce,pe)=>{let me=DS(ce,pe,e.size.width,e.size.height),qt=F.value.get(T);if(qt?.position.x===me.x&&qt.position.y===me.y){Or.value=me.guides.length>0?me.guides:null;return}wt(T,{position:{x:me.x,y:me.y}}),Or.value=me.guides.length>0?me.guides:null,Lb(T)},[e.size.width,e.size.height]),v=L(null),x=j(()=>{if(LS(),Or.value=null,Ap(null),v.current)document.removeEventListener("keydown",v.current),v.current=null;Tt();let T=Xn.value;if(Ob(),!T||T.nodeId!==e.id)return;if(T.mode==="add")$d(T.groupId,[e.id]);else{let ce=F.value.get(T.groupId),pe=Array.isArray(ce?.data.children)?ce.data.children.filter((me)=>typeof me==="string"&&me!==e.id):[];yc(T.groupId,pe)}},[e.id]),g=FS({nodeId:e.id,viewport:oe,onMove:h,onDragEnd:x,onClick:()=>{Ne.value=new Set([e.id])}}),b=j((T,ce,pe)=>{let me=F.value.get(T);if(me?.size.width===ce&&me.size.height===pe)return;wt(T,{size:{width:ce,height:pe}})},[]),I=j(()=>{fe(e.id,{userResized:!0}),kt(e.id,{data:{userResized:!0}}),Tt()},[e.id]),R=BS({nodeId:e.id,viewport:oe,onResize:b,onResizeEnd:I}),M=j((T)=>{T.stopPropagation(),T.preventDefault(),Ye.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]),_=j((T)=>{if(T.button!==0)return;if(d)return;if(T.target instanceof Element&&T.target.closest("button, input")){T.stopPropagation();return}if(Qt.value==="connect"){M(T);return}if(T.shiftKey){T.stopPropagation(),Dd(e.id);return}if(mo(e.id),Ap(e.id),Ww(e.id,typeof e.data.title==="string"&&e.data.title?e.data.title:e.type),OS(e.id,F.value.values()),e.type!=="group"){let ce=(pe)=>{if(pe.key==="Escape")$b()};v.current=ce,document.addEventListener("keydown",ce)}g(T,e.position.x,e.position.y)},[e.id,e.type,e.data.title,e.position.x,e.position.y,g,d,M]),N=j((T)=>{if(T.button!==0)return;if(T.stopPropagation(),Qt.value==="connect"){M(T);return}if(T.shiftKey){Dd(e.id);return}mo(e.id)},[e.id,M]),w=j((T)=>{if((T.target instanceof Element?T.target:null)?.closest('button, input, textarea, select, a, [contenteditable="true"]'))return;if(n)n(T,e.id)},[n,e.id]),k=j((T)=>{let ce=T.target;if(ce&&ce!==T.currentTarget&&ce.closest('input, textarea, [contenteditable="true"]'))return;let pe=sN[T.key];if(pe){T.preventDefault();let me=aN(e,pe,F.value.values());if(!me)return;mo(me.id),requestAnimationFrame(()=>{document.querySelector(`.canvas-node[data-node-id="${CSS.escape(me.id)}"]`)?.focus()})}else if(T.key==="Enter"&&T.target===T.currentTarget&&ms.has(e.type))T.preventDefault(),kn(e.id)},[e]),z=e.data.title||(e.type==="file"?(e.data.path||e.data.content||"").split(/[\\/]/).pop()??"":"")||Nt[e.type],X=j((T)=>{let ce=T.trim();if(ce&&ce!==z)fe(e.id,{title:ce}),kt(e.id,{title:ce});m(!1)},[e.id,z]),W=L(null),J=L(!1),G=L(null);H(()=>{if(J.current||!Ip(e))return;let T=W.current;if(!T)return;let ce=new ResizeObserver(()=>{if(J.current){ce.disconnect();return}let pe=T.scrollHeight,me=Kw(e,pe);if(me===null)return;if(Math.abs(me-e.size.height)>8){if(Cc(e.id,{width:e.size.width,height:me}),G.current!==null)window.clearTimeout(G.current);G.current=window.setTimeout(()=>{Tt({recordHistory:!1}),G.current=null},0)}J.current=!0,ce.disconnect()});return ce.observe(T),()=>{if(ce.disconnect(),G.current!==null)window.clearTimeout(G.current),G.current=null}},[e.id,e.type,e.data.mode,e.data.strictSize,e.collapsed,e.size.width,e.size.height]);let S=e.pinned,q=e.type==="trace",ie=q&&e.data.status==="running",ye=e.type==="group",ue=e.data.strictSize===!0,Pe=Math.max(oe.value.scale,0.01),ke=dN(Pe,e.collapsed?0:e.size.height,e.size.width),Me=ye&&e.data.color?e.data.color:void 0,cn={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":ke.toFixed(3),"--node-port-scale":(1/Pe).toFixed(3),...Me?{"--group-color":Me}:{}},Pn=_t.value&&Ll.value.has(e.id),D=["canvas-node",o?"active":"",c?"neighbor":"",u?"search-match":"",p?"search-dimmed":"",r?"selected":"",s?"context-pinned":"",a?"attention-pulse":"",S?"pinned":"",q?"trace-node":"",ie?"trace-running":"",ye?"group-node":"",ue?"strict-size":"",Pn?"agent-mutating":"",nr.value&&!nr.value.has(e.id)?"lens-dimmed":""].filter(Boolean).join(" "),Y=ye?(Array.isArray(e.data.children)?e.data.children:[]).filter((T)=>typeof T==="string"&&F.value.has(T)):[],[Te,de]=A(!1),be=Xn.value,se=ye&&be?.groupId===e.id&&be.mode==="add",re=ye&&be?.groupId===e.id&&be.mode==="remove",Z=Ye.value?.targetId===e.id,xe=ye?[...new Set(Y.map((T)=>F.value.get(T)?.type).filter((T)=>!!T))].slice(0,4):[];if(ye&&e.collapsed)return i("div",{class:`${D} group-chip`,"data-node-type":e.type,style:{...cn,width:"auto",height:"auto"},onPointerDown:N,onDblClick:w,title:"Expand group","data-testid":"group-chip",children:i("div",{class:"node-titlebar group-chip-inner",onPointerDown:_,children:[i("button",{type:"button",class:"group-chip-expand","aria-label":`Expand group ${z}`,onClick:(T)=>{T.stopPropagation(),Ss(e.id)},children:i(ks,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"group-chip-text",children:[i("div",{class:"group-chip-name",children:z},void 0,!1,void 0,this),i("div",{class:"group-chip-meta",children:[xe.map((T)=>i("span",{class:"group-kind-dot","aria-hidden":"true"},T,!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:`${D}${se?" is-drop-target":""}${re?" is-drop-source":""}${Z?" is-edge-target":""}${ye&&Te?" group-menu-open":""}`,"data-node-type":e.type,"data-node-id":e.id,style:cn,tabIndex:o?0:-1,onKeyDown:k,onPointerDown:N,onMouseDown:(T)=>{if(T.shiftKey)T.preventDefault()},onDblClick:w,children:[i("div",{class:"node-content",children:[ye&&i("div",{class:"node-titlebar group-edge-row",onPointerDown:_,children:[i("span",{class:"group-name-pill",children:[d?i("input",{ref:f,class:"node-title-input group-title-input",value:z,onBlur:(T)=>X(T.target.value),onKeyDown:(T)=>{if(T.key==="Enter")X(T.target.value);if(T.key==="Escape")m(!1)},onClick:(T)=>T.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"group-name",title:z,children:z},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":`${z} actions`,children:[i("button",{type:"button",class:"group-action",title:"Auto-arrange children","aria-label":"Auto-arrange children",disabled:Y.length===0,onClick:(T)=>{T.stopPropagation(),$d(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:(T)=>{T.stopPropagation(),Ss(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":Te,onClick:(T)=>{T.stopPropagation(),de((ce)=>!ce)},children:i(qd,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),Te&&i("div",{class:"group-menu",role:"menu",onPointerDown:(T)=>T.stopPropagation(),children:[i("button",{type:"button",role:"menuitem",onClick:(T)=>{T.stopPropagation(),de(!1),m(!0),requestAnimationFrame(()=>f.current?.focus())},children:"Rename"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",onClick:(T)=>{T.stopPropagation(),de(!1),Do(e.id),si(e.id)},children:"Ungroup"},void 0,!1,void 0,this),i("button",{type:"button",role:"menuitem",disabled:Y.length===0,onClick:(T)=>{T.stopPropagation(),de(!1),Sc(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),!ye&&i("div",{class:"node-titlebar",onPointerDown:_,children:[i("span",{class:"node-type-icon","aria-hidden":"true",children:(()=>{let T=Bn(e.type);return i(T,{size:Math.round(14*ke)},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),d?i("input",{ref:f,class:"node-title-input",value:z,onBlur:(T)=>X(T.target.value),onKeyDown:(T)=>{if(T.key==="Enter")X(T.target.value);if(T.key==="Escape")m(!1)},onClick:(T)=>T.stopPropagation()},void 0,!1,void 0,this):i("span",{class:"node-title",title:z,children:z},void 0,!1,void 0,this),i(TS,{node:e,pinned:s},void 0,!1,void 0,this),i(SS,{node:e,pinned:s},void 0,!1,void 0,this),i("div",{class:"node-controls",children:[S&&i("span",{class:"pin-indicator",title:"Pinned",children:"⊙"},void 0,!1,void 0,this),ms.has(e.type)&&i("button",{type:"button",onClick:(T)=>{T.stopPropagation(),kn(e.id)},title:"Expand (focus mode)",children:i(ix,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:`ctx-pin-btn${s?" ctx-pin-active":""}`,onClick:(T)=>{T.stopPropagation(),Jn(e.id)},title:s?"Remove from context":"Add to context","aria-label":s?"Remove from context":"Add to context","aria-pressed":s,children:i("span",{class:"ctx-pin-mark",children:[i($c,{},void 0,!1,void 0,this),s&&kS(e.id)&&i("span",{class:"ctx-pin-agent-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"node-hover-control",onClick:(T)=>{T.stopPropagation(),n?.(T,e.id)},title:"More actions","aria-label":"More actions",children:i(qd,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("button",{type:"button",class:"node-hover-control",onClick:(T)=>{T.stopPropagation(),Oo(e.id)},title:"Close",children:i(Ve,{size:14},void 0,!1,void 0,this)},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(ql,{node:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&i("div",{class:"node-resize-handle",onPointerDown:(T)=>R(T,e.size.width,e.size.height)},void 0,!1,void 0,this),r&&["tl","tr","bl","br"].map((T)=>i("span",{class:`node-selection-handle is-${T}`,"aria-hidden":"true"},T,!1,void 0,this)),Ar.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),Ar.value.get(e.id)," took over — agent yielded"]},void 0,!0,void 0,this),!ye&&["top","right","bottom","left"].map((T)=>i("div",{class:`node-port node-port-${T}`,onPointerDown:(ce)=>{if(ce.button!==0)return;ce.stopPropagation(),ce.preventDefault(),ce.currentTarget.setPointerCapture(ce.pointerId);let pe=e.position.x+e.size.width/2,me=e.position.y+e.size.height/2,qt=e.size.width/2,St=e.size.height/2,Gt,yn;switch(T){case"top":Gt=pe,yn=me-St;break;case"bottom":Gt=pe,yn=me+St;break;case"left":Gt=pe-qt,yn=me;break;case"right":Gt=pe+qt,yn=me;break}Ye.value={fromId:e.id,fromX:Gt,fromY:yn,cursorX:Gt,cursorY:yn}}},T,!1,void 0,this))]},void 0,!0,void 0,this)}function Gl({node:e}){let t=typeof e.data.boardId==="string"?e.data.boardId:"",n=rn.value.find((o)=>o.id===t);return i("div",{class:"board-node",children:[i("div",{class:"board-node-content",children:[i("div",{class:"board-node-label",children:"Linked board"},void 0,!1,void 0,this),i("strong",{class:"board-node-title",children:n?.name??"Missing board"},void 0,!1,void 0,this),i("div",{class:"board-node-meta",children:n?`${n.nodeCount} nodes`:t||"No target id"},void 0,!1,void 0,this),n?.summary&&i("p",{class:"board-node-summary",children:n.summary},void 0,!1,void 0,this),!!n?.pinnedTitles?.length&&i("p",{class:"board-node-meta",children:["Pinned: ",n.pinnedTitles.map((o)=>o.title).join(", ")]},void 0,!0,void 0,this),!!n?.backlinks?.length&&i("p",{class:"board-node-meta",children:["Linked from: ",[...new Set(n.backlinks.map((o)=>o.title))].join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("button",{class:"board-node-open",type:"button",disabled:!n,onClick:()=>n&&void sn(n.id),children:[n?"Open board":"Target unavailable",n&&i(jo,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var pN={relation:"var(--c-muted)","depends-on":"var(--c-rel-informs)",flow:"var(--c-accent)",references:"var(--c-muted)"},mN=new Set(["depends-on","flow"]);function fN(e){if(!Number.isFinite(e)||e<=0)return 1;return e<1?1/e:1}function hN(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 Vl(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,p=Math.abs(c/(a||0.001)),d=u/(l||0.001);if(p>d){let f=c>0?1:-1;return{x:n+u/p*(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+p*l*(c>0?1:-1),side:m>0?"right":"left"}}function Xl(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 gN(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 vN({edge:e,fromNode:t,toNode:n,focused:o,dimmed:r,selected:s,scale:a,onContextMenu:c}){let l=Vl(t,n),u=Vl(n,t),p=u.x-l.x,d=u.y-l.y,m=Math.sqrt(p*p+d*d),f=Math.min(Math.max(m*0.35,32),160),h=Xl(l,f),v=Xl(u,f),x=`M ${l.x} ${l.y} C ${h.x} ${h.y}, ${v.x} ${v.y}, ${u.x} ${u.y}`,g=pN[e.type],b=mN.has(e.type),I=hN(e,a),R=Math.min(a,2.2),M=e.label&&a<=3.4?gN(l.x,l.y,h.x,h.y,v.x,v.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:(N)=>{N.stopPropagation(),Kn.value=e.id},onDblClick:c?(N)=>c(N,e.id):void 0},void 0,!1,void 0,this),(o||s)&&i("path",{d:x,fill:"none",stroke:g,"stroke-width":6*a,"stroke-dasharray":I,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:g,"stroke-width":(s?3:o?2.5:1.5)*a,"stroke-dasharray":I,"marker-end":b?"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:g,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),M&&e.label&&i("g",{transform:`translate(${M.x}, ${M.y})`,children:[i("rect",{class:"edge-label-bg",x:-(e.label.length*3.5+8)*R,y:-10*R,width:(e.label.length*7+16)*R,height:20*R,rx:4*R},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 jS({nodes:e,edges:t,onEdgeContextMenu:n}){let o=e.value,r=Array.from(t.value.values()),s=je.value,a=s!==null,c=uo.value,l=c!==null,u=fN(oe.value.scale);if(r.length===0&&!Ye.value)return null;let p=96,d=Array.from(o.values());if(d.length===0)return null;let m=Math.min(...d.map((b)=>b.position.x))-p,f=Math.min(...d.map((b)=>b.position.y))-p,h=Math.max(...d.map((b)=>b.position.x+b.size.width))+p,v=Math.max(...d.map((b)=>b.position.y+b.size.height))+p,x=Math.max(1,h-m),g=Math.max(1,v-f);return i("svg",{"aria-label":"Canvas connections",role:"img",viewBox:`${m} ${f} ${x} ${g}`,width:x,height:g,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((b)=>{let I=_c(b.from),R=_c(b.to);if(!I||!R||I.id===R.id)return null;let M=a&&(b.from===s||b.to===s),_=l&&!(c.has(b.from)||c.has(b.to));return i(vN,{edge:b,fromNode:I,toNode:R,focused:M,dimmed:a&&!M||_,selected:Kn.value===b.id,scale:u,onContextMenu:n},b.id,!1,void 0,this)}),Ye.value&&(()=>{let b=Ye.value,I=_c(b.fromId),R={position:{x:b.cursorX,y:b.cursorY},size:{width:1,height:1}},M;if(I){let _=Vl(I,R),N=Vl(R,I),w=N.x-_.x,k=N.y-_.y,z=Math.sqrt(w*w+k*k),X=Math.min(Math.max(z*0.35,32),160),W=Xl(_,X),J=Xl(N,X);M=`M ${_.x} ${_.y} C ${W.x} ${W.y}, ${J.x} ${J.y}, ${N.x} ${N.y}`}else{let _=b.cursorX-b.fromX,N=b.cursorY-b.fromY,w=Math.sqrt(_*_+N*N),k=Math.min(w*0.25,80),z=_/(w||1),X=N/(w||1);M=`M ${b.fromX} ${b.fromY} C ${b.fromX+z*k} ${b.fromY+X*k}, ${b.cursorX-z*k} ${b.cursorY-X*k}, ${b.cursorX} ${b.cursorY}`}return i("g",{children:[i("path",{d:M,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:M,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:b.cursorX,cy:b.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 yN(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 Am({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-ui)","font-weight":"700",opacity:"0.95",children:t.text},t.id,!1,void 0,this)}return i("path",{d:yN(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)}function bN(e){switch(e.type){case"markdown":return i(Vc,{node:e},void 0,!1,void 0,this);case"mcp-app":return i(Ko,{node:e},void 0,!1,void 0,this);case"webpage":return i(Nl,{node:e},void 0,!1,void 0,this);case"json-render":return i(Ko,{node:e},void 0,!1,void 0,this);case"graph":return i(Ko,{node:e},void 0,!1,void 0,this);case"board":return i(Gl,{node:e},void 0,!1,void 0,this);case"prompt":return i(zl,{node:e},void 0,!1,void 0,this);case"response":return i(Rl,{node:e},void 0,!1,void 0,this);case"status":return i(Il,{node:e},void 0,!1,void 0,this);case"context":return i(Lc,{node:e},void 0,!1,void 0,this);case"ledger":return i(Hc,{node:e},void 0,!1,void 0,this);case"trace":return i(Ml,{node:e},void 0,!1,void 0,this);case"file":return i(Bc,{node:e},void 0,!1,void 0,this);case"diff":return i(Dc,{node:e},void 0,!1,void 0,this);case"mermaid":return i(ll,{node:e},void 0,!1,void 0,this);case"image":return i(Pl,{node:e},void 0,!1,void 0,this);case"html":return i(Ks,{node:e},void 0,!1,void 0,this);case"group":return i(D_,{node:e},void 0,!1,void 0,this);default:return i("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function xN(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 wN(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&&xN(t,c,l)<=n+r.width/2)return r}}return null}var Im="currentColor",US=4,ZS=24,_N=14,WS={width:520,height:420};function SN(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 Nm(e){let t=e.trim();if(!t)return[];let n=t.includes(`
331
+ `)?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=SN(a);if(!c||o.has(c))continue;o.add(c),r.push(c)}return r}function kN(e){let t=Nm(e.getData("text/uri-list"));if(t.length>0)return t;return Nm(e.getData("text/plain"))}function TN(e){if(!e)return!1;return e.types.includes("text/uri-list")||e.types.includes("text/plain")}function Pm(e){if(!(e instanceof HTMLElement))return!1;return Boolean(e.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}function CN(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 qS({onNodeContextMenu:e,onEdgeContextMenu:t,onCanvasContextMenu:n,annotationMode:o=!1,annotationTool:r=null}){let s=oe.value,a=L(!1),c=L(null),l=L(!1),u=L([]),[p,d]=A(null),[m,f]=A(null),[h,v]=A(null),x=L(null),[g,b]=A(!1),I=L(0),R=L(null),M=L(null);H(()=>{let D=null,Y=nn(()=>{oe.value;let Te=M.current;if(!Te)return;if(Te.style.willChange="transform",D)clearTimeout(D);D=setTimeout(()=>{Te.style.willChange="auto"},180)});return()=>{if(D)clearTimeout(D);Y()}},[]);let _=Ic({viewport:oe,disabled:o,onViewportChange:(D)=>{if(a.current||o)return;fo(),Wb(D)},onViewportCommit:(D)=>{if(a.current||o)return;fo(),Gb(D)}}),N=j((D)=>{x.current=D,v(D)},[]),w=j(async(D,Y,Te)=>{if(D.length===0)return;let{width:de,height:be}=WS,se=24,re=Math.ceil(Math.sqrt(D.length)),Z=Math.ceil(D.length/re),xe=re*de+Math.max(0,re-1)*se,T=Z*be+Math.max(0,Z-1)*se;for(let ce=0;ce<D.length;ce++){let pe=ce%re,me=Math.floor(ce/re),qt=Y-xe/2+pe*(de+se),St=Te-T/2+me*(be+se);await On({type:"webpage",content:D[ce],x:qt,y:St,width:de,height:be})}},[]),k=j((D)=>{let Y=_.current;if(!Y)return;if(r==="eraser"){if((D.target instanceof Element?D.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;D.preventDefault(),D.stopPropagation();let Z=Y.getBoundingClientRect(),xe=oe.value,T={x:(D.clientX-Z.left-xe.x)/xe.scale,y:(D.clientY-Z.top-xe.y)/xe.scale},ce=wN(Array.from(ci.value.values()),T,_N/xe.scale);if(ce)Zb(ce.id);return}if(r==="text"){if((D.target instanceof Element?D.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;D.preventDefault(),D.stopPropagation(),je.value=null,Ut();let Z=Y.getBoundingClientRect(),xe=oe.value;N({x:(D.clientX-Z.left-xe.x)/xe.scale,y:(D.clientY-Z.top-xe.y)/xe.scale,value:""});return}if(r==="pen"){if((D.target instanceof Element?D.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;D.preventDefault(),D.stopPropagation(),je.value=null,Ut(),l.current=!0;let Z=Y.getBoundingClientRect(),xe=oe.value,T={x:(D.clientX-Z.left-xe.x)/xe.scale,y:(D.clientY-Z.top-xe.y)/xe.scale};u.current=[T],f({id:"draft-annotation",type:"freehand",points:[T],bounds:{x:0,y:0,width:0,height:0},color:Im,width:US,createdAt:""}),Y.setPointerCapture(D.pointerId);return}if(D.target!==Y)return;if(ui()||D.button===1||D.button===2){if(!D.shiftKey&&!R.current)je.value=null,Ut();return}D.preventDefault(),D.stopPropagation(),a.current=!0;let Te=Y.getBoundingClientRect(),de=D.clientX-Te.left,be=D.clientY-Te.top,se={startX:de,startY:be,currentX:de,currentY:be};R.current=se,d(se),Y.setPointerCapture(D.pointerId)},[r,_]);H(()=>nn(()=>{let D=oe.value,Y=c.current,Te=_.current;if(!Y||!Te)return;let de=Te.getBoundingClientRect();sl({x:(Y.x-de.left-D.x)/D.scale,y:(Y.y-de.top-D.y)/D.scale})}),[]);let z=j((D)=>{{let de=_.current;if(de){c.current={x:D.clientX,y:D.clientY};let be=de.getBoundingClientRect(),se=oe.value;sl({x:(D.clientX-be.left-se.x)/se.scale,y:(D.clientY-be.top-se.y)/se.scale})}}if(l.current){let de=_.current;if(!de)return;let be=de.getBoundingClientRect(),se=oe.value,re={x:(D.clientX-be.left-se.x)/se.scale,y:(D.clientY-be.top-se.y)/se.scale},Z=u.current.at(-1);if(Z&&Math.hypot(re.x-Z.x,re.y-Z.y)<2)return;u.current=[...u.current,re],f((xe)=>xe?{...xe,points:u.current}:null);return}if(!a.current||!R.current)return;let Y=_.current?.getBoundingClientRect();if(!Y)return;let Te={...R.current,currentX:D.clientX-Y.left,currentY:D.clientY-Y.top};R.current=Te,d(Te)},[_]),X=j((D)=>{if(l.current){l.current=!1;let re=u.current;if(u.current=[],f(null),re.length>=2)jd({points:re,color:Im,width:US});let Z=_.current;if(Z?.hasPointerCapture(D.pointerId))Z.releasePointerCapture(D.pointerId);return}let Y=R.current;if(!a.current||!Y)return;a.current=!1,R.current=null;let Te=Math.min(Y.startX,Y.currentX),de=Math.max(Y.startX,Y.currentX),be=Math.min(Y.startY,Y.currentY),se=Math.max(Y.startY,Y.currentY);if(de-Te<=5&&se-be<=5)je.value=null,Ut();if(de-Te>5||se-be>5){let re=oe.value,Z=(Te-re.x)/re.scale,xe=(de-re.x)/re.scale,T=(be-re.y)/re.scale,ce=(se-re.y)/re.scale,pe=[];for(let me of F.value.values()){let qt=me.position.x,St=me.position.y;if(qt+me.size.width>Z&&qt<xe&&St+me.size.height>T&&St<ce)pe.push(me.id)}if(pe.length>0)Rb(pe)}d(null)},[]);H(()=>{if(o)return;if(!l.current&&!m&&!h)return;l.current=!1,u.current=[],f(null),N(null)},[o,m,N,h]);let W=j(()=>{let D=x.current;if(!D)return;let Y=D.value.trim();if(N(null),!Y)return;let Te={x:D.x,y:D.y};jd({type:"text",points:[Te],color:Im,width:ZS,text:Y})},[N]);H(()=>{if(r!=="text"&&h)N(null)},[r,N,h]),H(()=>{let D=(se,re,Z)=>{let xe=null;for(let T of F.value.values()){if(T.id===Z||T.type==="group")continue;if(se>=T.position.x&&se<=T.position.x+T.size.width&&re>=T.position.y&&re<=T.position.y+T.size.height)xe=T.id}return xe};function Y(se){if(!Ye.value)return;let re=_.current;if(!re)return;let Z=re.getBoundingClientRect(),xe=oe.value,T=(se.clientX-Z.left-xe.x)/xe.scale,ce=(se.clientY-Z.top-xe.y)/xe.scale;Ye.value={...Ye.value,cursorX:T,cursorY:ce,targetId:D(T,ce,Ye.value.fromId)}}function Te(){let se=Ye.value;if(!se)return;Ye.value=null;let re=se.targetId;if(!re)return;if(se.withLabel){hn("Edge label","label text").then((Z)=>{xr(se.fromId,re,"relation",Z??void 0)});return}xr(se.fromId,re,"relation",void 0)}function de(se){let re=Ye.value;if(!re)return;if(se.key==="Escape")se.preventDefault(),Ye.value=null;else if(se.key==="l"||se.key==="L")se.preventDefault(),Ye.value={...re,withLabel:!re.withLabel}}function be(){Ye.value=null}return document.addEventListener("pointermove",Y),document.addEventListener("pointerup",Te),document.addEventListener("pointercancel",be),document.addEventListener("keydown",de),()=>{document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",Te),document.removeEventListener("pointercancel",be),document.removeEventListener("keydown",de)}},[_]);let J=j((D)=>{if(o)return;let Y=_.current;if(!Y||D.target!==Y||!n)return;let Te=Y.getBoundingClientRect(),de=oe.value,be=(D.clientX-Te.left-de.x)/de.scale,se=(D.clientY-Te.top-de.y)/de.scale;n(D,be,se)},[o,_,n]),G=j((D)=>{D.preventDefault()},[]),S=j((D)=>{if(Pm(D.target instanceof Element?D.target:null))return;D.preventDefault()},[]),q=j((D)=>{if(D.preventDefault(),I.current++,D.dataTransfer?.types.includes("Files")||TN(D.dataTransfer))b(!0)},[]),ie=j((D)=>{if(D.preventDefault(),D.dataTransfer)D.dataTransfer.dropEffect="copy"},[]),ye=j((D)=>{if(D.preventDefault(),I.current--,I.current<=0)I.current=0,b(!1)},[]),ue=j(async(D)=>{D.preventDefault(),b(!1),I.current=0;let Y=_.current;if(!Y||!D.dataTransfer)return;let Te=Y.getBoundingClientRect(),de=oe.value,be=(D.clientX-Te.left-de.x)/de.scale,se=(D.clientY-Te.top-de.y)/de.scale,re=Array.from(D.dataTransfer.files);if(re.length===0){let Z=kN(D.dataTransfer);await w(Z,be,se);return}await $i(re,be,se)},[_,w]);H(()=>{let D=async(Y)=>{if(Y.defaultPrevented)return;if(Pm(Y.target instanceof Element?Y.target:null))return;if(Pm(document.activeElement))return;let Te=Y.clipboardData?.getData("text/plain")??"",de=Nm(Te);if(de.length===0)return;let be=_.current;if(!be)return;Y.preventDefault();let se=be.getBoundingClientRect(),re=oe.value,Z=(se.width/2-re.x)/re.scale,xe=(se.height/2-re.y)/re.scale;await w(de,Z,xe)};return document.addEventListener("paste",D),()=>{document.removeEventListener("paste",D)}},[_,w]);let Pe=CN(F.value.values(),ot.value,new Set(Fd.value.keys())),ke=Xn.value,Me=ke?F.value.get(ke.groupId):void 0,cn=ke?F.value.get(ke.nodeId):void 0,Pn=null;if(p){let D=Math.min(p.startX,p.currentX),Y=Math.min(p.startY,p.currentY),Te=Math.abs(p.currentX-p.startX),de=Math.abs(p.currentY-p.startY);Pn={position:"absolute",left:`${D}px`,top:`${Y}px`,width:`${Te}px`,height:`${de}px`,pointerEvents:"none"}}return i("div",{class:`canvas-viewport${ui()?" pan-mode":""}`,ref:_,tabIndex:0,onPointerDown:k,onPointerMove:z,onPointerLeave:()=>{c.current=null,sl(null)},onPointerUp:X,onContextMenu:G,onDblClick:J,onDragStart:S,onDragEnter:q,onDragOver:ie,onDragLeave:ye,onDrop:ue,style:{width:"100%",height:"100%",position:"relative",overflow:"hidden",cursor:r==="eraser"?"cell":r==="text"?"text":o||Ye.value||a.current||Qt.value==="connect"?"crosshair":ui()?"grab":"default"},children:[i("div",{ref:M,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(gS,{},void 0,!1,void 0,this),i(K_,{},void 0,!1,void 0,this),i(oS,{},void 0,!1,void 0,this),i(rS,{},void 0,!1,void 0,this),i(jS,{nodes:F,edges:Je,onEdgeContextMenu:t},void 0,!1,void 0,this),Ye.value&&i("div",{class:"edge-hint-pill","data-testid":"edge-hint",style:{left:`${Ye.value.cursorX+14}px`,top:`${Ye.value.cursorY+14}px`},children:[i("span",{class:"edge-hint-main",children:Ye.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",Ye.value.withLabel?" · label on":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),ke&&Me&&cn&&i("div",{class:"drop-pill","data-testid":"drop-pill",style:{left:`${cn.position.x}px`,top:`${cn.position.y+cn.size.height+10}px`},children:[i("span",{class:"drop-pill-text",children:ke.mode==="add"?`release to add to ${String(Me.data.title??"group")}`:`release to remove from ${String(Me.data.title??"group")}`},void 0,!1,void 0,this),i("span",{class:"drop-pill-hint",children:ke.mode==="add"?"esc keeps it out":"esc keeps it in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(Am,{annotations:Array.from(ci.value.values())},void 0,!1,void 0,this),m&&m.points.length>=2&&i(Am,{annotations:[m]},void 0,!1,void 0,this),Pe.map((D)=>i(HS,{node:D,onContextMenu:e,children:bN(D)},D.id,!1,void 0,this)),Or.value&&i("svg",{class:"snap-guides-svg",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"visible"},children:Or.value.map((D,Y)=>D.axis==="x"?i("line",{x1:D.pos,y1:D.from-20,x2:D.pos,y2:D.to+20,class:"snap-guide-line"},Y,!1,void 0,this):i("line",{x1:D.from-20,y1:D.pos,x2:D.to+20,y2:D.pos,class:"snap-guide-line"},Y,!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),h&&i("input",{class:"annotation-text-input",value:h.value,autoFocus:!0,style:{left:`${h.x*s.scale+s.x}px`,top:`${h.y*s.scale+s.y}px`,fontSize:`${ZS*s.scale}px`},onInput:(D)=>N({...h,value:D.target.value}),onBlur:W,onPointerDown:(D)=>D.stopPropagation(),onKeyDown:(D)=>{if(D.key==="Enter")D.preventDefault(),W();if(D.key==="Escape")D.preventDefault(),N(null)}},void 0,!1,void 0,this),Pn&&i("div",{class:"lasso-rect",style:Pn},void 0,!1,void 0,this),g&&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 Kl({label:e,value:t,options:n,onChange:o,className:r="",above:s=!1}){let[a,c]=A(!1),l=L(null),u=L(null),p=L(null),d=()=>{c(!1),u.current?.focus()};return _n(()=>{if(!a)return;(p.current?.querySelector('[aria-checked="true"]:not(:disabled)')??p.current?.querySelector("button:not(:disabled)"))?.focus();let f=(h)=>{if(h.target instanceof Node&&!l.current?.contains(h.target))c(!1)};return document.addEventListener("pointerdown",f),()=>document.removeEventListener("pointerdown",f)},[a]),i("div",{ref:l,class:`choice-menu ${r}`,onBlur:(m)=>{if(m.relatedTarget instanceof Node&&!l.current?.contains(m.relatedTarget))c(!1)},onKeyDown:(m)=>{if(m.key!=="Tab"&&(m.key!=="Escape"||a))m.stopPropagation();if(m.key==="Escape"&&a)m.preventDefault(),m.stopPropagation(),d();if(["ArrowDown","ArrowUp","Home","End"].includes(m.key)){if(m.preventDefault(),m.stopPropagation(),!a){c(!0);return}let f=[...p.current?.querySelectorAll("button:not(:disabled)")??[]];if(!f.length)return;let h=f.findIndex((x)=>x===document.activeElement),v=m.key==="Home"?0:m.key==="End"?f.length-1:(h+(m.key==="ArrowUp"?-1:1)+f.length)%f.length;f[v]?.focus()}},children:[i("button",{ref:u,type:"button",class:"choice-menu-trigger","aria-label":e,"aria-haspopup":"menu","aria-expanded":a,onClick:()=>c(!a),children:[i("span",{children:n.find((m)=>m.value===t)?.label??e},void 0,!1,void 0,this),i(Nc,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a&&i("div",{ref:p,role:"menu","aria-label":e,class:`toolbar-menu choice-menu-options${s?" opens-above":""}`,children:n.map((m)=>i("button",{type:"button",role:"menuitemradio",class:`toolbar-menu-item${m.value===t?" active":""}`,"aria-checked":m.value===t,disabled:m.disabled,tabIndex:-1,"data-value":m.value,onClick:()=>{o(m.value),d()},children:[i("span",{children:m.label},void 0,!1,void 0,this),m.value===t&&i("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},m.value,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function GS(){let e=[...Le.value],t=F.value,[n,o]=A(""),[r,s]=A(!1),a=tS.value,[c,l]=A(null),u=a.length>=2,p=!u&&a.length===1&&a[0].steerable?a[0]:null,d=u?c?a.find((h)=>h.value===c&&h.steerable)??null:null:p,m=d?.value??null,f=async()=>{let h=n.trim();if(!h||r)return;s(!0);let v=await fS(h,m);if(s(!1),v)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((h)=>{let v=t.get(h),x=typeof v?.data.title==="string"&&v.data.title.trim()?v.data.title:v?.type??h;return i("span",{class:"command-bar-chip","data-node-id":h,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:()=>Jn(h),children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},h,!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(fi,{size:15,class:"command-bar-icon"},void 0,!1,void 0,this),u&&i(Kl,{className:"command-bar-target",label:"Steer which agent",value:m??"",above:!0,onChange:(h)=>l(h||null),options:[{value:"",label:"All agents"},...a.map((h)=>{let v=h.pendingSteers&&h.pendingSteers>0?` · ${h.pendingSteers} queued`:"",x=h.polling?" · polling":"";return{value:h.value,disabled:!h.steerable,label:h.attached?`${h.label}${x}${v}`:h.steerable?`${h.label} · writer${x}${v}`:`${h.label} · no inbox`}})]},void 0,!1,void 0,this),i("input",{class:"command-bar-input",type:"text",value:n,placeholder:`Steer ${d?.label??"the agent"}, or ${rt("K")} to search the board…`,"aria-label":"Steer the agent",disabled:r,onInput:(h)=>o(h.target.value),onKeyDown:(h)=>{if(h.key==="Enter")h.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 zm=Ge(()=>{if(fn.value==="disconnected")return"reconnecting";if(fn.value==="connected"&&!Yt.value&&_r.value>1)return"resyncing";return null});function VS(){let e=zm.value;if(!e)return null;if(e==="reconnecting"){let t=Sr.value,n=kr.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 EN={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 In(e){if(e.x!==void 0&&e.y!==void 0)return On(e);let t=EN[e.type]??{width:360,height:200},n=e.width??t.width,o=e.height??t.height,r=Ro(),s=oe.value,a=await On({...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)pt(a.id);return a}var Jl=!1,XS=!1,Lr=null,ji=null;function Rm(){return Jl}function Yl(){Jl=!1,XS=!0,KS()}function KS(){if(Lr&&ji)Lr.removeEventListener("change",ji);Lr=null,ji=null}function AN(){if(typeof window>"u"||!window.location)return null;let e=new URLSearchParams(window.location.search).get("theme");if(e==="auto")return"auto";return Ls(e)?e:null}function JS(e){if(XS)return;let t=AN();if(!t)return;if(KS(),Jl=!0,t!=="auto"){e(t);return}Lr=window.matchMedia("(prefers-color-scheme: light)"),ji=()=>{if(Jl&&Lr)e(Lr.matches?"daylight":"harbor")},ji(),Lr.addEventListener("change",ji)}var IN='a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';function an(e,t,n={}){H(()=>{if(!t)return;let o=e.current;if(!o)return;let r=document.activeElement,s=n.restoreTo,a=()=>Array.from(o.querySelectorAll(IN)),c=n.initial?.current??a()[0];if(c&&!o.contains(document.activeElement))c.focus();let l=(u)=>{if(u.key!=="Tab")return;let p=a();if(p.length===0)return;let d=p[0],m=p[p.length-1],f=document.activeElement;if(u.shiftKey&&(f===d||!o.contains(f)))u.preventDefault(),m.focus();else if(!u.shiftKey&&f===m)u.preventDefault(),d.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 PN(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 NN(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 Mm={md:"markdown",app:"mcp-app",web:"webpage",ui:"json-render",chart:"graph",ctx:"context",log:"ledger"};function zN(e){let t=e.toLowerCase().trim();if(t.startsWith("type:")){let n=t.slice(5).trim(),r=Object.keys(Nt).find((a)=>a.startsWith(n));if(r)return{typeFilter:r,remaining:""};let s=Mm[n];if(s)return{typeFilter:s,remaining:""}}if(Mm[t])return{typeFilter:Mm[t],remaining:""};return{typeFilter:null,remaining:e}}function YS({onClose:e,onToggleMinimap:t}){let[n,o]=A(""),[r,s]=A(0),[a,c]=A([]),[l,u]=A("idle"),p=L(null),d=L(null),m=L(null);an(m,!0,{initial:p}),H(()=>{setTimeout(()=>p.current?.focus(),30)},[]),H(()=>{let _=n.trim();if(_.length<2){c([]),u("idle");return}let N=!0;u("loading");let w=window.setTimeout(()=>void ne("paletteLibrarySearch",`/api/canvas/search?q=${encodeURIComponent(_)}&scope=library&limit=12`,null).then((k)=>{if(!N)return;if(!k){c([]),u("error");return}c(k.results??[]),u("idle")}),150);return()=>{N=!1,window.clearTimeout(w)}},[n]);let f=j(()=>{let _=[];for(let w of F.value.values()){let k=w.data.title||Nt[w.type],z=w.data.content||w.data.path||"",X=w.type==="group"&&Array.isArray(w.data.children)?w.data.children.length:0;_.push({id:`node:${w.id}`,kind:"node",label:k,description:w.type==="group"?`group · ${X} node${X===1?"":"s"}`:z.length>60?`${Nt[w.type].toLowerCase()} · ${z.slice(0,60)}…`:z?`${Nt[w.type].toLowerCase()} · ${z}`:Nt[w.type].toLowerCase(),icon:Bn(w.type),nodeType:w.type,action:()=>{pt(w.id),e()}})}let N=[{label:"New markdown note",shortcut:"M",icon:Ho,iconTone:"accent",action:()=>{In({type:"markdown",title:"New note",width:520,height:360}),e()}},{label:"Link to board…",icon:Bn("board"),iconTone:"accent",action:()=>{window.dispatchEvent(new CustomEvent("pmx-open-board-link")),e()}},..._t.value?[]:[{label:"Start agent session",icon:fi,iconTone:"purple",action:()=>{tr(),e()}}],{label:"Fit view",shortcut:"F",icon:zc,iconTone:"muted",action:()=>{pi(bt().width,bt().height),e()}},{label:"Auto-arrange (grid)",icon:go,iconTone:"muted",action:()=>{Ec(),e()}},{label:"Auto-arrange (graph-aware)",icon:go,iconTone:"muted",action:()=>{Ac(),e()}},{label:"Toggle minimap",icon:Rc,iconTone:"muted",action:()=>{t(),e()}},{label:"Toggle theme (Harbor/Daylight)",icon:Mc,iconTone:"muted",action:()=>{let w=Go(gt.value)==="dark"?"daylight":"harbor";Yl(),document.documentElement.setAttribute("data-theme",w),Ri(),gt.value=w,fc(w),e()}}];for(let w of N)_.push({id:`action:${w.label}`,kind:"action",label:w.label,...w.shortcut?{shortcut:w.shortcut}:{},icon:w.icon,...w.iconTone?{iconTone:w.iconTone}:{},action:w.action});return _},[e,t]),{typeFilter:h,remaining:v}=zN(n),x=f(),g;if(!n.trim())g=x.map((_)=>({..._,score:0,indices:[]}));else{g=[];for(let _ of x){if(h){if(_.kind!=="node"||_.nodeType!==h)continue;if(!v){g.push({..._,score:0,indices:[]});continue}}let N=PN(v||n,_.label);if(N.match)g.push({..._,score:N.score,indices:N.indices})}g.sort((_,N)=>N.score-_.score)}for(let _ of a)g.push({id:`library:${_.boardId}:${_.cardId}`,kind:"library",label:_.title||_.boardTitle,description:`${_.boardTitle} · ${_.snippet}`,icon:Bn("board"),score:0,indices:[],action:()=>{(async()=>{if(await sn(_.boardId),Oe.value!==_.boardId)return;for(let N=0;N<40&&Oe.value===_.boardId;N++){if(F.value.has(_.cardId)){pt(_.cardId),e();return}await new Promise((w)=>window.setTimeout(w,25))}})()}});g=[...g.filter((_)=>_.kind==="action"),...g.filter((_)=>_.kind==="node"),...g.filter((_)=>_.kind==="library")];let b=g.findIndex((_)=>_.kind==="node"),I=g.findIndex((_)=>_.kind==="library");H(()=>{if(!n.trim()){uo.value=null;return}let _=new Set;for(let N of g)if(N.kind==="node")_.add(N.id.slice(5));uo.value=_.size>0?_:null},[n,g]),H(()=>()=>{uo.value=null},[]);let R=Math.min(r,Math.max(0,g.length-1)),M=j((_)=>{if(_.key==="ArrowDown")_.preventDefault(),s((N)=>Math.min(N+1,g.length-1));else if(_.key==="ArrowUp")_.preventDefault(),s((N)=>Math.max(N-1,0));else if(_.key==="Enter"){if(_.preventDefault(),g[R])g[R].action()}else if(_.key==="Escape")_.preventDefault(),_.stopPropagation(),e()},[g,R,e]);return H(()=>{let _=d.current;if(!_)return;_.children[R]?.scrollIntoView({block:"nearest"})},[R]),H(()=>{s(0)},[n]),i("div",{class:"command-palette-backdrop",onMouseDown:e,children:i("div",{ref:m,class:"command-palette",role:"dialog","aria-modal":"true","aria-label":"Search and commands",onMouseDown:(_)=>_.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:p,type:"text",class:"command-palette-input",value:n,onInput:(_)=>o(_.target.value),onKeyDown:M,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:d,children:[l==="loading"&&i("div",{class:"command-palette-empty",role:"status",children:"Searching all boards…"},void 0,!1,void 0,this),l==="error"&&i("div",{class:"command-palette-empty",role:"alert",children:"Library search is unavailable."},void 0,!1,void 0,this),g.length===0&&l!=="loading"&&i("div",{class:"command-palette-empty",children:"No matching nodes, boards, or actions"},void 0,!1,void 0,this),g.map((_,N)=>{let w=_.icon,k=N===0&&_.kind==="action"?"Actions":N===b?"Jump to":N===I?"Across boards":null;return i("div",{class:"command-palette-row",children:[k&&i("div",{class:"command-palette-group",children:k},void 0,!1,void 0,this),i("button",{type:"button",class:`command-palette-item${N===R?" selected":""}`,onMouseEnter:()=>s(N),onClick:()=>_.action(),children:[i("span",{class:`command-palette-icon tone-${_.iconTone??"kind"}`,"aria-hidden":"true",children:i(w,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"command-palette-label",children:[_.indices.length>0?NN(_.label,_.indices):_.label,_.description&&i("span",{class:"command-palette-desc",children:[" — ",_.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_.shortcut&&i("kbd",{class:"command-palette-kbd",children:_.shortcut},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},_.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:rt("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 QS({onClose:e}){let t=L(null),n=L(null),[o,r]=A(""),[s,a]=A("");an(t,!0,{initial:n});let c=rn.value.filter((u)=>u.id!==Oe.value&&u.name.toLowerCase().includes(o.trim().toLowerCase())),l=async(u)=>{let p=rn.value.find((h)=>h.id===u);if(!p)return a("That board is no longer available.");let d=Ro(),m=oe.value;if(!(await ne("createBoardLink","/api/canvas/node",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"board",title:p.name,x:Math.round((d.x-m.x)/m.scale-180),y:Math.round((d.y-m.y)/m.scale-100),width:360,height:200,data:{boardId:u}})})).ok)return a("Could not create the board link.");e()};return i("div",{class:"text-prompt-backdrop",onMouseDown:e,children:i("div",{ref:t,class:"text-prompt board-link-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-link-title",onMouseDown:(u)=>u.stopPropagation(),children:[i("h2",{id:"board-link-title",children:"Link to a board"},void 0,!1,void 0,this),i("input",{ref:n,type:"search",class:"text-prompt-input","aria-label":"Find a board to link",placeholder:"Find a board…",value:o,onInput:(u)=>r(u.currentTarget.value)},void 0,!1,void 0,this),s&&i("div",{role:"alert",class:"board-copy-error",children:s},void 0,!1,void 0,this),i("ul",{class:"board-link-results",children:[c.map((u)=>i("li",{children:i("button",{type:"button",onClick:()=>void l(u.id),children:[i("span",{children:u.name},void 0,!1,void 0,this),i("small",{children:[u.nodeCount," nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},u.id,!1,void 0,this)),c.length===0&&i("li",{class:"board-copy-status",children:rn.value.length<=1?"Create another board first, then link it here.":"No boards match your search."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"text-prompt-actions",children:i("button",{type:"button",onClick:e,children:"Cancel"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function ek(){let[e,t]=A(null),n=j((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"node",x:a.clientX,y:a.clientY,nodeId:c})},[]),o=j((a,c,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"canvas",x:a.clientX,y:a.clientY,canvasX:c,canvasY:l})},[]),r=j((a,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"edge",x:a.clientX,y:a.clientY,edgeId:c})},[]),s=j(()=>t(null),[]);return H(()=>{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 RN="#4bbcFF",MN=[{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 tk({menu:e,onClose:t}){let n;if(e.kind==="node"){let c=F.value.get(e.nodeId);if(!c)return null;n=BN(c)}else if(e.kind==="edge"){let c=e.edgeId,l=Je.value.get(c);n=[{label:l?.label?`Edit label “${l.label.slice(0,18)}${l.label.length>18?"…":""}”`:"Add label…",action:()=>{hn("Edge label (empty clears it)","label text",{initial:l?.label??"",allowEmpty:!0,confirm:"Save"}).then((u)=>{if(u===null)return;bc(c,{label:u})})}},{separator:!0},...["flow","depends-on","relation","references"].map((u)=>({label:`${l?.type===u?"✓":" "} ${u}`,action:()=>void bc(c,{type:u})})),{separator:!0},...["solid","dashed","dotted"].map((u)=>({label:`${(l?.style??"solid")===u?"✓":" "} ${u}`,action:()=>void bc(c,{style:u})})),{separator:!0},{label:"Delete edge",danger:!0,action:()=>void xc(c)}]}else n=FN(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 p=`${l}:${u}`;if(c.separator)return i("div",{class:"context-menu-separator"},p,!1,void 0,this);if(c.render)return i("div",{class:"context-menu-custom",children:c.render(t)},p,!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)]},p,!0,void 0,this)})},void 0,!1,void 0,this)}function $N(e){return(typeof e.data.path==="string"?e.data.path.trim():"")||null}function Ql(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 nk(e){if(typeof e.data.color!=="string"||!e.data.color.trim())return null;return Ql(e.data.color)}function ON(e){let t=nk(e);return t&&/^#[0-9a-f]{6}$/.test(t)?t:Ql(RN)}function $m(e,t){let n=t?Ql(t):null;wt(e.id,{data:{...e.data,color:n}}),kt(e.id,{data:{color:n}})}function LN(e,t){let n=nk(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:()=>{$m(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:MN.map((o)=>{let r=Ql(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:()=>{$m(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:ON(e),onClick:(o)=>o.stopPropagation(),onInput:(o)=>{$m(e,o.currentTarget.value),t()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Lm(e,t,n,o){return{x:e-n/2,y:t-o/2}}function DN(e,t){return e.trim().replace(/[?#].*$/,"").split("/").filter(Boolean).at(-1)||t}async function Om(e){let t=await hn(e.promptLabel,e.placeholder??"");if(!t)return;let n=t.trim();if(!n)return;let o=Lm(e.canvasX,e.canvasY,e.width,e.height);if(!(await On({type:e.type,...e.type!=="webpage"?{title:DN(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 FN(e,t){return[{label:"New note",action:()=>{let r=Lm(e,t,520,360);On({type:"markdown",title:"New note",x:r.x,y:r.y,width:520,height:360})}},{label:"Open webpage...",action:()=>{Om({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:()=>{Om({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:()=>{Om({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."})}},{label:"Link to board…",action:()=>window.dispatchEvent(new CustomEvent("pmx-open-board-link"))},{separator:!0},{label:"New group",action:()=>{let r=Lm(e,t,600,400);ii({title:"Group",x:r.x,y:r.y,width:600,height:400})}}]}function BN(e){let t=[],n=$N(e);if(t.push({label:"Focus",action:()=>pt(e.id)}),t.push({label:"Rename…",action:()=>{hn("Rename node","Node title",{initial:typeof e.data.title==="string"?e.data.title:"",confirm:"Save"}).then((l)=>{if(!l?.trim())return;kt(e.id,{title:l.trim()})})}}),ms.has(e.type))t.push({label:"Expand",shortcut:"⤢",action:()=>kn(e.id)});if(t.push({label:e.collapsed?"Expand":"Collapse",action:()=>Ss(e.id)}),Yc(e))t.push({label:"Open in new tab",action:()=>void Qc(e)});let o=Le.value.has(e.id);t.push({label:o?"Unpin from context":"Pin as context",action:()=>Jn(e.id)}),t.push({label:e.pinned?"Unlock position":"Lock position (no auto-arrange)",action:()=>{let l=!e.pinned;wt(e.id,{pinned:l}),kt(e.id,{pinned:l}),Tt()}});let r=ws.value;if(r&&r.from!==e.id){let l=F.value.get(r.from),u=l?(l.data.title||l.id).slice(0,20):r.from;t.push({label:`Connect from "${u}"`,action:()=>{xr(r.from,e.id,"relation"),ws.value=null}})}t.push({label:r?"Connect from here (replace)":"Connect from here",action:()=>{ws.value={from:e.id}}});let s=Array.from(Je.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:()=>pb("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:()=>{gc(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)=>LN(e,u)}),l.length>0)t.push({label:`Ungroup (${l.length} node${l.length!==1?"s":""})`,action:()=>{Do(e.id),si(e.id)}})}let a=typeof e.data.parentGroup==="string"?e.data.parentGroup:null,c=a?F.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((p)=>p!==e.id):[];t.push({label:`Remove from “${l}”`,action:()=>{yc(c.id,u)}})}return t.push({separator:!0}),t.push({label:e.type==="group"?"Delete frame (children stay)":"Delete",danger:!0,action:()=>{Oo(e.id)}}),t}function ok(){let e=Le.value.size;if(e===0||Gn.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:Hb,title:"Clear all context pins","aria-label":"Clear all context pins",children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function rk({onClose:e}){let t=L(null),[n,o]=A("Bug report"),[r,s]=A(""),[a,c]=A("");return an(t,!0),i("div",{class:"text-prompt-backdrop feedback-backdrop",onPointerDown:e,children:i("form",{ref:t,class:"text-prompt feedback-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"feedback-title","aria-describedby":"feedback-privacy",action:"https://github.com/pskoett/pmx-canvas/issues/new",method:"get",target:"_blank",rel:"noopener noreferrer",onPointerDown:(l)=>l.stopPropagation(),onKeyDown:(l)=>{if(l.stopPropagation(),l.key==="Escape")l.preventDefault(),e()},children:[i("div",{id:"feedback-title",class:"text-prompt-title",children:"Bug and feedback"},void 0,!1,void 0,this),i("p",{id:"feedback-privacy",class:"feedback-note",children:"Opens a draft issue in pskoett/pmx-canvas. Review and submit it on GitHub using your account. Issues are public. Only what you enter below is included; no board contents, workspace paths, screenshots, or logs are attached."},void 0,!1,void 0,this),i("div",{class:"feedback-field",children:[i("span",{children:"Feedback type"},void 0,!1,void 0,this),i(Kl,{label:"Feedback type",value:n,onChange:o,options:["Bug report","Feature request","General feedback"].map((l)=>({value:l,label:l}))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("label",{children:["Title",i("input",{class:"text-prompt-input",name:"title",required:!0,maxLength:120,value:r,onInput:(l)=>s(l.currentTarget.value),placeholder:"A short summary"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("label",{children:["Description",i("textarea",{class:"text-prompt-input",required:!0,maxLength:1200,rows:6,value:a,onInput:(l)=>c(l.currentTarget.value),placeholder:"What happened, what you expected, and steps to reproduce — or describe your idea."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("input",{type:"hidden",name:"body",value:`## ${n}
332
332
 
333
- ${a.trim()}`},void 0,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",onClick:e,children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"submit",class:"text-prompt-confirm",disabled:!r.trim()||!a.trim(),children:["Continue on GitHub ",i(jo,{size:14},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,!1,void 0,this)}function oa(e,t){console.error(`[tool-rail] ${e} failed`,t)}function Dr(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"}};hn(t[e].message,t[e].placeholder).then((n)=>{if(!n)return;In({type:e,content:n}).catch((o)=>oa(`create ${e}`,o))})}function yt({label:e,shortcut:t,detail:n,ariaLabel:o,active:r,menuOpen:s,onClick:a,btnRef:c,children:l}){let[u,p]=A(null),d=(h)=>{let v=h.currentTarget.getBoundingClientRect();p({left:v.right+10,top:v.top+v.height/2})},m=()=>p(null),f=o??(t?`${e} (${t})`:n?`${e} (${n})`:e);return i(_e,{children:[i("button",{ref:c,type:"button",class:`rail-btn${r?" active":""}`,"aria-label":f,"aria-pressed":r===void 0?void 0:r,onClick:(h)=>{m(),a(h)},onPointerEnter:d,onPointerLeave:m,onFocus:d,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 ik({minimapVisible:e,onToggleMinimap:t,snapshotOpen:n,onToggleSnapshot:o,snapshotBtnRef:r,onOpenPalette:s,onOpenShortcuts:a,annotationTool:c,onSetAnnotationTool:l}){let u=Qt.value,p=li.value,d=Array.from(F.value.values()).filter((z)=>z.type==="trace").length,m=Je.value.size,[f,h]=A(!1),[v,x]=A(null),[g,b]=A(null),I=L(null),R=L(null),M=(z)=>(X)=>{if(v===z){x(null);return}let W=X.currentTarget.getBoundingClientRect();b({bottom:W.bottom,right:W.right}),x(z)},_=g?{position:"fixed",left:`${g.right+8}px`,bottom:`${window.innerHeight-g.bottom}px`,top:"auto",right:"auto"}:void 0;H(()=>{if(!v)return;let z=(W)=>{if(I.current&&W.target instanceof Node&&!I.current.contains(W.target))x(null)},X=(W)=>{if(W.key==="Escape")x(null)};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",X),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",X)}},[v]);let N=(z)=>{Yl(),document.documentElement.setAttribute("data-theme",z),Ri(),gt.value=z,fc(z),x(null)},w=zp(gt.value),k=(z,X={})=>{ct(`/api/workbench/intent?_ts=${Date.now()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:z,payload:X})}).catch((W)=>oa("sendIntent",W))};return i(_e,{children:[i("div",{class:"tool-rail",ref:I,role:"toolbar","aria-label":"Canvas tools","aria-orientation":"vertical",children:[i(yt,{label:"Home",ariaLabel:"PMX Canvas — Home",onClick:()=>{x(null),sn(null).catch((z)=>oa("openHome",z))},children:i("span",{class:"rail-brand",children:i(Oc,{size:22},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Bug and feedback",menuOpen:f,onClick:()=>{x(null),h(!0)},children:i("svg",{width:"16",height:"16",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:"4.5",y:"5",width:"7",height:"9",rx:"3.5"},void 0,!1,void 0,this),i("path",{d:"M6 5V4a2 2 0 0 1 4 0v1M8 8v6M2 4l2.5 2M14 4l-2.5 2M1.5 9h3M11.5 9h3M2 14l2.5-2M14 14l-2.5-2"},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(yt,{label:"Select",shortcut:"V",active:u==="select",onClick:()=>Qt.value="select",children:i(bx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Pan",shortcut:"Space",active:u==="pan",onClick:()=>Qt.value="pan",children:i(xx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Connect",shortcut:"C",active:u==="connect",onClick:()=>Qt.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(yt,{label:"Markdown note",shortcut:"M",onClick:()=>void In({type:"markdown",title:"New note",width:520,height:360}).catch((z)=>oa("create markdown",z)),children:i(Ho,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Attach files",ariaLabel:"Attach files",detail:"Images (PNG, JPEG, SVG…), Markdown and text/code files. PDF, Word, Excel, PowerPoint and OpenDocument use agent import with review.",onClick:()=>R.current?.click(),children:i(ax,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("input",{ref:R,type:"file",hidden:!0,multiple:!0,"aria-label":"Attach files",onChange:(z)=>{let X=bt(),W=oe.value;$i(Array.from(z.currentTarget.files??[]),(X.width/2-W.x)/W.scale,(X.height/2-W.y)/W.scale),z.currentTarget.value=""}},void 0,!1,void 0,this),i(yt,{label:"Webpage",shortcut:"W",onClick:()=>Dr("webpage"),children:i(mi,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Group",shortcut:"G",onClick:()=>void In({type:"group",title:"Group"}).catch((z)=>oa("create group",z)),children:i(Vd,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Draw",shortcut:"A",active:c==="pen",onClick:()=>l(c==="pen"?null:"pen"),children:i(dx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Text note",active:c==="text",onClick:()=>l(c==="text"?null:"text"),children:i(mx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Eraser",active:c==="eraser",onClick:()=>l(c==="eraser"?null:"eraser"),children:i(px,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"rail-spacer"},void 0,!1,void 0,this),i(yt,{label:"Search & commands",shortcut:rt("K"),onClick:s,children:i(vx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Arrange",detail:m>0?"graph-aware":"grid",onClick:()=>m>0?Ac():Ec(),children:i(go,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),!Se()&&i(yt,{label:p?"Disable trace":"Enable trace",active:p,onClick:()=>k("trace-toggle",{enabled:!p}),children:i(hx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),!Se()&&(p||d>0)&&i(yt,{label:"Clear trace",onClick:()=>k("trace-clear"),children:i(gx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:e?"Hide minimap":"Show minimap",active:e,onClick:t,children:i(Rc,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Snapshots",active:n,onClick:o,btnRef:r,children:i(fx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"toolbar-menu-anchor",children:[i(yt,{label:"Theme",detail:Ci[w].label,menuOpen:v==="theme",ariaLabel:"Choose theme",active:v==="theme",onClick:M("theme"),children:Go(w)==="dark"?i(ux,{},void 0,!1,void 0,this):i(Mc,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),v==="theme"&&i("div",{class:"toolbar-menu",style:_,role:"menu","aria-label":"Theme",children:Np.map((z)=>i("button",{type:"button",role:"menuitemradio","aria-checked":w===z,class:`toolbar-menu-item${w===z?" active":""}`,onClick:()=>N(z),children:[i("span",{class:"theme-swatch",style:{background:Ci[z].swatchBg},children:i("span",{class:"theme-swatch-dot",style:{background:Ci[z].swatchAccent}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{children:Ci[z].label},void 0,!1,void 0,this),w===z&&i("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},z,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(yt,{label:"Shortcuts",shortcut:"?",onClick:a,children:i(yx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),f&&i(rk,{onClose:()=>h(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sk({onOpenPalette:e}){let t=L(null),n=()=>{In({type:"markdown",title:"New note",width:520,height:360}).catch(()=>{})},o=async(r)=>{if(!r||r.length===0)return;let s=Ro(),a=oe.value;await $i(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(Ho,{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:()=>Dr("webpage"),children:[i(mi,{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:rt("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 tr(),children:[i(fi,{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 · ",rt("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)}var ak="From old snapshots";function ck(e){if(!e?.trim())return null;let t=e.split("/").map((n)=>n.trim());if(t.length>8)throw Error("Folders can be nested up to 8 levels.");if(t.some((n)=>!n||n==="."||n===".."||n.length>60))throw Error('Each folder name must be 1–60 characters, and cannot be "." or "..".');return t.join("/")}function Dm(e){return e.split("/").map((t,n,o)=>o.slice(0,n+1).join("/"))}function lk({board:e,folders:t,onClose:n}){let o=L(null),[r,s]=A(e.category??""),[a,c]=A(""),[l,u]=A(!1),[p,d]=A("");an(o,!0),H(()=>{let h=(v)=>{if(v.key!=="Escape")return;if(v.preventDefault(),v.stopPropagation(),!l)n()};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[l,n]);let m=a.trim()?[r,a.trim()].filter(Boolean).join("/"):r,f=async()=>{let h;try{if(a.includes("/"))throw Error("Use one folder name; choose its parent above.");h=ck(m)}catch(v){d(v instanceof Error?v.message:String(v));return}if(u(!0),d(""),await uc(e.id,{category:h}),rn.value.find((v)=>v.id===e.id)?.category===h)n();else d("Could not move this board. Try again.");u(!1)};return i("div",{class:"text-prompt-backdrop",onPointerDown:()=>!l&&n(),children:i("div",{ref:o,class:"text-prompt home-folder-dialog",role:"dialog","aria-modal":"true","aria-label":`Move ${e.name}`,onPointerDown:(h)=>h.stopPropagation(),children:[i("div",{class:"text-prompt-title",children:["Move “",e.name,"”"]},void 0,!0,void 0,this),i("p",{class:"home-folder-hint",children:"Choose a folder, or create one inside it. The board keeps its content and links."},void 0,!1,void 0,this),i("fieldset",{class:"home-folder-options",disabled:l,children:[i("legend",{children:"Destination folder"},void 0,!1,void 0,this),["",...t].map((h)=>i("label",{class:"home-folder-option",style:{paddingLeft:`${8+Math.min(h.split("/").length-1,5)*14}px`},children:[i("input",{type:"radio",name:"folder-destination",value:h,checked:r===h,onChange:()=>{s(h),d("")}},void 0,!1,void 0,this),i("span",{children:h||"Home (no folder)"},void 0,!1,void 0,this)]},h,!0,void 0,this))]},void 0,!0,void 0,this),i("label",{class:"home-folder-new",children:["New folder inside ",r||"Home"," ",i("span",{class:"home-folder-hint",children:"(optional)"},void 0,!1,void 0,this),i("input",{class:"text-prompt-input","aria-label":"New folder name",placeholder:"e.g. Decisions",maxLength:60,value:a,disabled:l,onInput:(h)=>{c(h.currentTarget.value),d("")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"home-folder-hint",children:["Move to: ",i("strong",{children:m||"Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p&&i("p",{role:"alert",children:p},void 0,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",disabled:l,onClick:n,children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"button",class:"text-prompt-confirm",disabled:l||m===(e.category??""),onClick:()=>void f(),children:l?"Moving…":"Move board"},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 uk({board:e,onClose:t}){let n=L(null),o=L(null),[r,s]=A(null),[a,c]=A(new Set),[l,u]=A(`${e.name} copy`),[p,d]=A(!0),[m,f]=A(!0),[h,v]=A(!1),[x,g]=A(""),[b,I]=A(!1);return an(n,!0,{initial:o}),H(()=>{let M=!0;return cb(e.id).then((_)=>{if(!M)return;if(!_||!Array.isArray(_.cards))return g("Could not load reusable cards. Try again.");s(_),c(new Set(_.cards.filter((N)=>N.reusable).map((N)=>N.id)))}),()=>{M=!1}},[e.id]),i("div",{class:"text-prompt-backdrop",onMouseDown:t,children:i("div",{ref:n,class:"text-prompt board-copy-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-copy-title",onMouseDown:(M)=>M.stopPropagation(),children:i("form",{onSubmit:async(M)=>{if(M.preventDefault(),!l.trim()||!r)return;I(!0),g("");let _=await lb({sourceBoardId:e.id,name:l.trim(),...e.category?{category:e.category}:{},nodeIds:[...a],includeReadme:p,includeStructure:m});if(I(!1),!_)return g("Could not create the board. Try a different name.");if(h)await sn(_.id);t()},children:[i("h2",{id:"board-copy-title",children:["Create from ",e.name]},void 0,!0,void 0,this),i("label",{class:"board-copy-field",children:["Board name",i("input",{ref:o,class:"text-prompt-input",value:l,onInput:(M)=>u(M.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!r&&!x&&i("div",{class:"board-copy-status",role:"status",children:"Loading reusable cards…"},void 0,!1,void 0,this),x&&i("div",{class:"board-copy-error",role:"alert",children:x},void 0,!1,void 0,this),r&&i("fieldset",{class:"board-copy-cards",children:[i("legend",{children:"Cards to copy"},void 0,!1,void 0,this),r.cards.filter((M)=>M.reusable).length===0?i("div",{class:"board-copy-status",children:"No reusable cards on this board."},void 0,!1,void 0,this):r.cards.filter((M)=>M.reusable).map((M)=>i("label",{class:"board-copy-card",children:[i("input",{type:"checkbox",checked:a.has(M.id),onChange:(_)=>{let N=new Set(a);_.currentTarget.checked?N.add(M.id):N.delete(M.id),c(N)}},void 0,!1,void 0,this),i("span",{children:[i("strong",{children:M.title||"Untitled card"},void 0,!1,void 0,this),i("small",{children:M.type},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},M.id,!0,void 0,this))]},void 0,!0,void 0,this),i("div",{class:"board-copy-options",children:[i("label",{children:[i("input",{type:"checkbox",checked:m,onChange:(M)=>f(M.currentTarget.checked)},void 0,!1,void 0,this)," ","Preserve groups and connections"]},void 0,!0,void 0,this),i("label",{children:[i("input",{type:"checkbox",checked:p,disabled:!r?.readmeNodeId,onChange:(M)=>d(M.currentTarget.checked)},void 0,!1,void 0,this)," ","Include README"]},void 0,!0,void 0,this),i("label",{children:[i("input",{type:"checkbox",checked:h,onChange:(M)=>v(M.currentTarget.checked)},void 0,!1,void 0,this)," Open the new board after creating"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("p",{class:"board-copy-note",children:"Only selected cards and structure are copied. Asks, history, and context pins start clear."},void 0,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",onClick:t,children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"submit",disabled:!r||!l.trim()||b,children:b?"Creating…":"Create board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function BN(e){if(!e)return"never opened";let t=Math.floor((Date.now()-new Date(e).getTime())/60000);if(t<1)return"just now";if(t<60)return`${t}m ago`;let n=Math.floor(t/60);if(n<24)return`${n}h ago`;let o=Math.floor(n/24);if(o<30)return`${o}d ago`;return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function dk(e){return`${e} node${e!==1?"s":""}`}async function Fm(){let e=await hn("New board","Board name",{confirm:"Create"});if(e)await ab(e)}var pk="pmx-canvas-home-collapsed";function HN(){try{let e=localStorage.getItem(pk);if(e)return new Set(JSON.parse(e))}catch{}return new Set([ak])}function jN(e){try{localStorage.setItem(pk,JSON.stringify([...e]))}catch{}}function mk(){let e=rn.value,[t,n]=A(null),[o,r]=A(null),[s,a]=A(null),[c,l]=A(""),[u,p]=A([]),[d,m]=A(HN),f=L(0),h=[...new Set(e.flatMap((k)=>k.category?Dm(k.category):[]))].sort((k,z)=>k.localeCompare(z)),v=c.trim().toLocaleLowerCase(),x=e.filter((k)=>`${k.name} ${k.category??""}`.toLocaleLowerCase().includes(v)),g=new Set(x.flatMap((k)=>k.category?Dm(k.category):[])),b=e.find((k)=>k.id===o),I=e.find((k)=>k.id===s);H(()=>{let k=c.trim();if(!k){p([]);return}let z=!1,X=window.setTimeout(()=>{ne("searchLibrary",`/api/canvas/search?q=${encodeURIComponent(k)}&scope=library&limit=30`,null).then((W)=>{if(!z)p(W?.results??[])})},150);return()=>{z=!0,window.clearTimeout(X)}},[c]);let R=async(k)=>{let z=++f.current;await sn(k.boardId);for(let X=0;X<40;X++){if(z!==f.current||Oe.value!==k.boardId)return;if(F.value.has(k.cardId)){pt(k.cardId);return}await new Promise((W)=>window.setTimeout(W,25))}},M=(k)=>{let z=new Set(d);if(z.has(k))z.delete(k);else z.add(k);m(z),jN(z)},_=async(k)=>{let z=await hn("Rename board","Board name",{initial:k.name,confirm:"Rename"});if(z&&z!==k.name)await uc(k.id,{name:z})},N=(k)=>t===k.id?i("li",{class:"home-board is-confirming","data-testid":"home-board",children:[i("div",{class:"home-board-confirm-text",children:["Delete ",i("strong",{children:k.name},void 0,!1,void 0,this)," and its ",dk(k.nodeCount)," and snapshots? This can't be undone."]},void 0,!0,void 0,this),i("div",{class:"home-board-actions",children:[i("button",{type:"button",class:"home-board-action",onClick:()=>n(null),children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action is-danger",onClick:()=>{n(null),db(k.id)},children:"Delete board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k.id,!0,void 0,this):i("li",{class:"home-board","data-testid":"home-board",children:[i("button",{type:"button",class:"home-board-open",onClick:()=>void sn(k.id),children:[i("span",{class:"home-board-name",children:k.name},void 0,!1,void 0,this),i("span",{class:"home-board-meta",children:[dk(k.nodeCount)," · ",BN(k.lastOpenedAt)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"home-board-actions",children:[i("button",{type:"button",class:"home-board-action","aria-haspopup":"dialog",onClick:()=>r(k.id),children:"Move"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action","aria-haspopup":"dialog",onClick:()=>a(k.id),children:"Create from…"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action",onClick:()=>void _(k),children:"Rename"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action",onClick:()=>n(k.id),children:"Delete"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k.id,!0,void 0,this),w=(k,z)=>{let X=h.filter((S)=>S.slice(0,S.lastIndexOf("/"))===k&&S.includes("/")),W=x.filter((S)=>S.category===k),J=x.filter((S)=>S.category===k||S.category?.startsWith(`${k}/`)).length,G=!!v||!d.has(k);return i("section",{class:"home-section","data-testid":"home-section","data-folder":k,"aria-label":k,children:[i("button",{type:"button",class:"home-section-head","aria-expanded":G,onClick:()=>M(k),children:[i("svg",{class:"home-section-chevron",viewBox:"0 0 20 20",width:"18",height:"18",fill:"none","aria-hidden":"true",children:i("path",{d:"m7.5 4.75 5.25 5.25-5.25 5.25"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("svg",{class:"home-section-folder",viewBox:"0 0 20 20",width:"18",height:"18",fill:"none","aria-hidden":"true",children:i("path",{d:"M2.75 5.75A1.75 1.75 0 0 1 4.5 4h3l1.75 2h6.25a1.75 1.75 0 0 1 1.75 1.75v6.5A1.75 1.75 0 0 1 15.5 16h-11a1.75 1.75 0 0 1-1.75-1.75v-8.5Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"home-section-name",children:k.split("/").at(-1)},void 0,!1,void 0,this),i("span",{class:"home-section-count",children:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&i("div",{class:"home-folder-children",style:{marginLeft:z<5?"14px":"0"},children:[X.filter((S)=>g.has(S)).map((S)=>w(S,z+1)),W.length>0&&i("ul",{class:"home-view-list","aria-label":`Boards in ${k}`,children:W.map(N)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k,!0,void 0,this)};return i("div",{class:"home-view","data-testid":"home-view",children:[i("div",{class:"home-view-inner",children:[i("div",{class:"home-view-head",children:[i("h1",{class:"home-view-title",children:"Boards"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-view-new",onClick:()=>void Fm(),children:"New board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("input",{class:"text-prompt-input home-search",type:"search","aria-label":"Find boards and folders",placeholder:"Find boards and folders…",value:c,onInput:(k)=>l(k.currentTarget.value)},void 0,!1,void 0,this),e.length===0?i("div",{class:"home-view-empty",children:"No boards yet. Create one, or let an agent start writing — it opens one."},void 0,!1,void 0,this):v&&u.length>0?i("ul",{class:"home-view-list","aria-label":"Library search results",children:u.map((k)=>i("li",{class:"home-board",children:i("button",{type:"button",class:"home-board-open",onClick:()=>void R(k),children:[i("span",{class:"home-board-name",children:k.title||k.boardTitle},void 0,!1,void 0,this),i("span",{class:"home-board-meta",children:[k.boardTitle," · ",k.snippet]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},`${k.boardId}:${k.cardId}`,!1,void 0,this))},void 0,!1,void 0,this):x.length===0?i("div",{class:"home-view-empty",role:"status",children:["No boards match “",c,"”."]},void 0,!0,void 0,this):i(_e,{children:[h.filter((k)=>!k.includes("/")&&g.has(k)).map((k)=>w(k,0)),x.some((k)=>!k.category)&&i("section",{"aria-label":"Unfiled boards",children:[h.length>0&&i("div",{class:"home-folder-hint",children:"Unfiled boards"},void 0,!1,void 0,this),i("ul",{class:"home-view-list",children:x.filter((k)=>!k.category).map(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),b&&i(lk,{board:b,folders:h,onClose:()=>r(null)},b.id,!1,void 0,this),I&&i(uk,{board:I,onClose:()=>a(null)},I.id,!1,void 0,this)]},void 0,!0,void 0,this)}var Ui=K(!1);function UN(e){return e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}function fk(){let[e,t]=A(!1),[n,o]=A(!1),[r,s]=A(null),[a,c]=A(null),[l,u]=A(!1),[p,d]=A(""),m=Ui.value,f=Oe.value;if(H(()=>{if(!m||!f)return;let v=!0;return c(null),d(""),s(null),ne("exportPreview",`/api/canvas/export/preview?board=${encodeURIComponent(f)}&includeFiles=${e}&includeDerivedText=${n}`,null).then((x)=>{if(v)s(x?.manifest??null)}),()=>{v=!1}},[m,e,n,f]),H(()=>{o(!1)},[m,f]),H(()=>{if(!m)return;let v=(x)=>{if(x.key!=="Escape")return;x.stopPropagation(),Ui.value=!1};return window.addEventListener("keydown",v,{capture:!0}),()=>window.removeEventListener("keydown",v,{capture:!0})},[m]),!m)return null;let h=async()=>{if(!r||r.boardId!==Oe.value)return;u(!0);let v=await ne("exportBoard","/api/canvas/export",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({board:r.boardId,includeFiles:e,includeDerivedText:n})});if(u(!1),v?.path&&Oe.value===r.boardId)c(v)};return i("div",{class:"text-prompt-backdrop",onPointerDown:()=>Ui.value=!1,children:i("div",{class:"text-prompt export-dialog",role:"dialog","aria-label":"Export board","data-testid":"export-dialog",onPointerDown:(v)=>v.stopPropagation(),children:[i("div",{class:"text-prompt-title",children:["Export ",r?`“${r.boardName}”`:"board"]},void 0,!0,void 0,this),!r?i("div",{class:"export-dialog-note",children:"Reading the board…"},void 0,!1,void 0,this):i(_e,{children:[i("div",{class:"export-dialog-note",children:"One HTML file anyone can open without installing anything. It will contain:"},void 0,!1,void 0,this),i("ul",{class:"export-dialog-list",children:[i("li",{children:[r.cards," card",r.cards!==1?"s":""," and ",r.connections," connection",r.connections!==1?"s":""]},void 0,!0,void 0,this),r.frames>0&&i("li",{children:[r.frames," embedded pages, charts or diagrams, with the code that draws them"]},void 0,!0,void 0,this),r.embeddedImages>0&&i("li",{children:[r.embeddedImages," local images"]},void 0,!0,void 0,this),r.placeholders.length>0&&i("li",{children:["Shown as placeholders:"," ",r.placeholders.map((v)=>`${v.title} (${v.reason})`).join(", ")]},void 0,!0,void 0,this),r.remoteImages.length>0&&i("li",{children:["Web images loaded when opened: ",r.remoteImages.join(", ")]},void 0,!0,void 0,this),r.links.length>0&&i("li",{children:["Links included in cards: ",r.links.join(", ")]},void 0,!0,void 0,this),r.frameNetworkDestinations.length>0&&i("li",{children:["Network destinations referenced by embedded pages: ",r.frameNetworkDestinations.join(", ")]},void 0,!0,void 0,this),r.embeddedCodeCanAccessNetwork&&i("li",{children:"Warning: embedded code can access the network. Scripts may contact destinations that cannot be listed in advance."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(r.attachments?.length??0)>0&&i("p",{children:"Original attachments are excluded. Their filenames remain visible."},void 0,!1,void 0,this),(r.sourceDerivedCards?.length??0)>0&&i("label",{class:"export-dialog-files",children:[i("input",{type:"checkbox",checked:n,onChange:(v)=>o(v.currentTarget.checked)},void 0,!1,void 0,this),i("span",{children:["Include imported document text (",r.sourceDerivedCards.length," cards)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r.files.length>0&&i("label",{class:"export-dialog-files",children:[i("input",{type:"checkbox",checked:e,onChange:(v)=>t(v.target.checked)},void 0,!1,void 0,this),i("span",{children:["Include the contents of ",r.files.length," local file",r.files.length!==1?"s":"",": ",r.files.map((v)=>v.path).join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&i("div",{class:"export-dialog-result","data-testid":"export-result",children:[i("div",{children:["Saved (",UN(a.bytes),"): ",i("code",{children:a.path},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"export-dialog-links",children:Se()?i("button",{type:"button",disabled:l,onClick:async()=>{u(!0),d("");try{await ob(a.url)}catch(v){d(v instanceof Error?v.message:"Download failed. Try again.")}finally{u(!1)}},children:l?"Downloading…":"Download"},void 0,!1,void 0,this):i(_e,{children:[i("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:"Open"},void 0,!1,void 0,this),i("a",{class:"is-primary",href:`${a.url}?download=1`,children:"Download"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Se()&&i("p",{children:"Download the HTML file to open it outside ChatGPT."},void 0,!1,void 0,this),p&&i("p",{role:"alert",children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",onClick:()=>Ui.value=!1,children:a?"Done":"Cancel"},void 0,!1,void 0,this),!a&&i("button",{type:"button",class:"text-prompt-confirm",disabled:!r||l,onClick:()=>void h(),children:l?"Exporting…":"Export"},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 Bm({presence:e,size:t=18}){return i("span",{class:"writer-avatar",style:{background:An(e.sessionId),width:`${t}px`,height:`${t}px`},"aria-hidden":"true",children:eS(e.label)},void 0,!1,void 0,this)}function hk(){let e=ym.value;if(_t.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=Rr.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:()=>{Rr.value=!o},children:[i("span",{class:"external-indicator-avatars",children:e.slice(0,3).map((r)=>i(Bm,{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 ZN(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 WN(e){return e.reduce((t,n)=>n.lastSeenAt>t?n.lastSeenAt:t,"")}function qN(){return[...lt.value.values()].filter((e)=>!e.auto&&e.phase==="forming")}function gk(){let e=Rr.value,t=ym.value,n=xo(e?1e4:0);if(H(()=>{if(!e)return;let c=(l)=>{if(l.key!=="Escape")return;if(Oi.value)Oi.value=!1;else Rr.value=!1};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]),!e||_t.value||t.length===0)return null;let o=vm.value,r=qN().filter((c)=>!o||(c.source??"")===o),s=Yo.value.filter((c)=>!o||c.sessionId===o),a=(c,l)=>i("button",{type:"button",class:`activity-filter${o===c?" is-active":""}`,style:c?{"--writer":An(c)}:void 0,"aria-pressed":o===c,onClick:()=>{vm.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"," ",Ol(WN(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:()=>{Rr.value=!1},children:i(Ve,{},void 0,!1,void 0,this)},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:()=>{br(c).then((l)=>{if(l)Er(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}=ZN(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:An(c.sessionId)},children:c.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"activity-age",children:Ol(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:()=>{Oi.value=!0},children:"Writers"},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-link is-accent",onClick:()=>{Rr.value=!1,tr()},children:["Start session ",i(jo,{size:14},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 GN(){let e=[];if(Qo.value)e.push("scoped");if(Mr.value.length>0)e.push("gated");return e.length>0?e.join(" + "):"open"}function vk(){let e=Oi.value,t=xo(e?1e4:0),n=L(null);if(an(n,e),!e)return null;let o=It.value.filter((a)=>a.attached),r=It.value.filter((a)=>!a.attached),s=()=>{Oi.value=!1};return i(_e,{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:lo.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:i(Ve,{},void 0,!1,void 0,this)},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(Bm,{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:GN()},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(Bm,{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"," ",Ol(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 yk(e,t){switch(e.type){case"markdown":return i(Vc,{node:e,expanded:t},void 0,!1,void 0,this);case"mcp-app":return i(Ko,{node:e,expanded:t},void 0,!1,void 0,this);case"webpage":return i(Nl,{node:e,expanded:t},void 0,!1,void 0,this);case"json-render":return i(Ko,{node:e,expanded:t},void 0,!1,void 0,this);case"graph":return i(Ko,{node:e,expanded:t},void 0,!1,void 0,this);case"board":return i(Gl,{node:e},void 0,!1,void 0,this);case"prompt":return i(zl,{node:e},void 0,!1,void 0,this);case"response":return i(Rl,{node:e,expanded:t},void 0,!1,void 0,this);case"status":return i(Il,{node:e},void 0,!1,void 0,this);case"context":return i(Lc,{node:e,expanded:t},void 0,!1,void 0,this);case"ledger":return i(Hc,{node:e},void 0,!1,void 0,this);case"trace":return i(Ml,{node:e},void 0,!1,void 0,this);case"file":return i(Bc,{node:e,expanded:t},void 0,!1,void 0,this);case"diff":return i(Dc,{node:e},void 0,!1,void 0,this);case"mermaid":return i(ll,{node:e,expanded:t},void 0,!1,void 0,this);case"image":return i(Pl,{node:e,expanded:t},void 0,!1,void 0,this);case"html":return i(Ks,{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 bk(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 VN(e){if(!e)return 0;return e.split(/\s+/).filter(Boolean).length}function XN(e,t){return e!==null&&typeof e==="object"&&e.source===Tn&&e.type==="presentation-exit"&&e.token===t}function KN(e){return e==="ArrowRight"||e==="PageDown"||e===" "||e==="ArrowLeft"||e==="PageUp"||e==="Home"||e==="End"}function xk(e){return e instanceof HTMLElement&&Boolean(e.closest(".html-presentation-exit"))}function wk(){let e=ot.value,t=e?F.value.get(e):void 0,[n,o]=A(!1),[r,s]=A(!1),[a,c]=A(""),l=L(null),u=L(null),p=j(()=>{s(!1),ho()},[]),d=j(()=>{c(`presentation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`),s(!0)},[]),m=j((S)=>{document.querySelector(".html-presentation-overlay iframe.html-node-frame-presentation")?.contentWindow?.postMessage({source:Tn,token:a,...S},"*")},[a]),f=j(()=>{s(!1)},[]),h=j((S)=>{if(S.key==="Escape"){S.preventDefault(),S.stopPropagation(),s(!1);return}if(S.key==="Tab"&&!xk(S.target)){S.preventDefault(),S.stopPropagation(),u.current?.focus();return}if((S.key===" "||S.key==="Enter")&&xk(S.target))return;if(!KN(S.key))return;S.preventDefault(),S.stopPropagation(),m({type:"presentation-key",key:S.key})},[m]),v=j((S)=>{if(S.target.classList.contains("expanded-overlay-backdrop"))ho()},[]),x=j(()=>{if(!t)return;let S=bk(t);if(!S)return;navigator.clipboard.writeText(S).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},[t]),g=j(()=>{if(!e)return;Jn(e)},[e]);H(()=>{s(!1)},[e]),_n(()=>{if(!r)return;let S=()=>{let ye=l.current;if(!ye||ye.contains(document.activeElement))return;ye.focus()},q=[0,50,150].map((ye)=>window.setTimeout(S,ye)),ie=(ye)=>{if(!XN(ye.data,a))return;s(!1)};return document.addEventListener("keydown",h,!0),window.addEventListener("message",ie),()=>{q.forEach((ye)=>{window.clearTimeout(ye)}),document.removeEventListener("keydown",h,!0),window.removeEventListener("message",ie)}},[h,a,r]);let b=L(null),I=j(()=>e?document.querySelector(`.canvas-node[data-node-id="${CSS.escape(e)}"]`):null,[e]);if(an(b,t!==void 0,{restoreTo:I}),!t)return null;let R=t.data.title||t.data.path?.split("/").pop()||Nt[t.type],M=bk(t),_=VN(M),N=e?Le.value.has(e):!1,w=M.length>0,k=Ln.value===e,z=t.type==="mcp-app"||t.type==="webpage"||t.type==="json-render"||t.type==="graph",X=F_(t),W=Bn(t.type),J=t.data.provenance&&typeof t.data.provenance==="object"?t.data.provenance:null,G=J?[J.sourceKind,J.sourceUri,J.syncedAt?`synced ${J.syncedAt.slice(11,16)}`:null].filter((S)=>typeof S==="string"&&S.length>0).join(" · "):null;return i("div",{class:"expanded-overlay-backdrop",onPointerDown:v,style:{pointerEvents:k?"none":"auto"},children:i("div",{ref:b,class:`expanded-overlay-panel${N?" is-pinned":""}`,role:"dialog","aria-modal":"true","aria-label":R,"data-testid":"expanded-node",children:[i("div",{class:"expanded-header",children:[i("span",{class:"expanded-kind-icon","aria-hidden":"true",children:i(W,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"expanded-title",children:R},void 0,!1,void 0,this),i("span",{class:"expanded-kind-pill",children:Nt[t.type]},void 0,!1,void 0,this),i("button",{type:"button",class:`expanded-pin${N?" is-on":""}`,onClick:g,title:N?"In agent context — click to unpin":"Pin as agent context","aria-pressed":N,children:"✦"},void 0,!1,void 0,this),i("span",{class:"expanded-spacer"},void 0,!1,void 0,this),i("div",{class:"expanded-actions",children:[w&&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),Yc(t)&&i("button",{type:"button",class:"expanded-action-btn",onClick:()=>void Qc(t),title:"Open as a full-page site in the system browser",children:["Open in tab ",i(jo,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&i("button",{type:"button",class:"expanded-action-btn expanded-action-primary",onClick:d,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:p,title:"Close (Esc)","aria-label":"Close",children:i(Ve,{},void 0,!1,void 0,this)},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:yk(t,!0)},void 0,!1,void 0,this):yk(t,!0)},void 0,!1,void 0,this),i("div",{style:{"--ax-dock-bleed":"0px","--ax-dock-pad":"16px"},children:i(ql,{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:[G,_>0?`${_.toLocaleString()} word${_!==1?"s":""}`:null].filter(Boolean).join(" · ")||Nt[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${k?" is-saving":""}`,children:k?"Saving edits…":"esc or click outside to close"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&r&&i("div",{ref:l,class:"html-presentation-overlay",role:"dialog","aria-modal":"true","aria-label":`Present ${R}`,tabIndex:-1,onKeyDownCapture:h,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(Ks,{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 Sk=168,kk=112,eu=20;function _k(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,p=-t.y/t.scale,d=u+n/t.scale,m=p+o/t.scale,f={minX:Math.min(s,u)-eu,minY:Math.min(a,p)-eu,maxX:Math.max(c,d)+eu,maxY:Math.max(l,m)+eu},h=f.maxX-f.minX||1,v=f.maxY-f.minY||1;return{bounds:f,scale:Math.min(Sk/h,kk/v)}}function Tk({viewport:e,nodes:t,onNavigate:n,containerWidth:o,containerHeight:r}){let s=L(null),a=L(!1),c=t.value,l=e.value,u=_k(c,l,o,r),{bounds:p,scale:d}=u,m=(w)=>(w-p.minX)*d,f=(w)=>(w-p.minY)*d,h=j((w)=>{let k=s.current;if(!k)return;let z=k.getBoundingClientRect(),X=(w.clientX-z.left)/z.width*Sk,W=(w.clientY-z.top)/z.height*kk,J=_k(t.value,e.value,o,r),G=e.value,S=o/G.scale,q=r/G.scale,ie=X/J.scale+J.bounds.minX,ye=W/J.scale+J.bounds.minY;n(-(ie-S/2)*G.scale,-(ye-q/2)*G.scale)},[t,e,o,r,n]),v=j((w)=>{w.stopPropagation(),w.preventDefault(),a.current=!0,h(w);let k=(X)=>{if(a.current)h(X)},z=()=>{a.current=!1,document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",z)};document.addEventListener("pointermove",k),document.addEventListener("pointerup",z)},[h]),x=Ne.value,g=Le.value,b=_t.value?Ll.value:new Set,I=Qo.value,R=I?Fl(I.nodeIds.map((w)=>c.get(w)).filter((w)=>w!==void 0),I.padding):null,M=It.value.map((w)=>({id:w.sessionId,phase:w.phase,worker:w.parentAgentId!=null,external:!w.attached,at:Dl(w,(k)=>c.get(k))})).filter((w)=>w.at!==null),_=-l.x/l.scale,N=-l.y/l.scale;return i("div",{ref:s,class:"minimap","data-testid":"minimap",title:"Click to jump · drag the frame to pan",onPointerDown:v,children:[Array.from(c.values()).map((w)=>{let k=w.type==="group";return i("span",{class:`minimap-node${k?" is-group":""}${x.has(w.id)?" is-selected":""}${g.has(w.id)?" is-pinned":""}${b.has(w.id)?" is-agent":""}`,"data-kind":w.type,style:{left:`${m(w.position.x)}px`,top:`${f(w.position.y)}px`,width:`${Math.max(k?6:4,w.size.width*d)}px`,height:`${Math.max(k?5:3,w.size.height*d)}px`}},w.id,!1,void 0,this)}),R&&i("span",{class:"minimap-fence",style:{left:`${m(R.x)}px`,top:`${f(R.y)}px`,width:`${R.width*d}px`,height:`${R.height*d}px`}},void 0,!1,void 0,this),M.map((w)=>i("span",{class:`minimap-presence phase-${w.phase}${w.worker?" is-worker":""}${w.external?" is-external":""}`,style:{left:`${m(w.at.x)-4}px`,top:`${f(w.at.y)-4}px`,"--identity-color":An(w.id)}},w.id,!1,void 0,this)),i("span",{class:"minimap-frame",style:{left:`${m(_)}px`,top:`${f(N)}px`,width:`${o/l.scale*d}px`,height:`${r/l.scale*d}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 Ck(){let e=Ne.value.size,t=j(()=>{let c=Array.from(Ne.value);if(c.length===0)return;Sc(c),Ut()},[]),n=j(()=>{let c=Array.from(Ne.value);if(c.length===0)return;ii({title:"Group",childIds:c}),Ut()},[]),o=j(()=>{let c=Array.from(Ne.value);for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++)xr(c[l],c[u],"relation");Ut()},[]),r=j(()=>{let c=Array.from(Ne.value);for(let l of c)Oo(l);Ut()},[]);if(e===0)return null;let s=e>=2,a=!_t.value&&Le.value.size>0&&!Gn.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(_e,{children:[i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Qe,{label:"Align left",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align left",onClick:()=>Bd("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(Qe,{label:"Align top",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align top",onClick:()=>Bd("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(Qe,{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:()=>Fb(),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(Qe,{label:"Auto-arrange selection",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Auto-arrange",onClick:()=>Bb(),children:i(go,{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(Qe,{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(Qe,{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(Qe,{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(Qe,{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(Qe,{label:"Clear selection",shortcut:"Esc",side:"up",children:i("button",{type:"button",class:"selection-bar-icon",onClick:Ut,"aria-label":"Clear selection",children:i(Ve,{size:14},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 tu(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 nu(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 JN={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"vetoed"},YN={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"cancelled"},Ek=[{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"}],Ak=Object.fromEntries(Ek.map((e)=>[e.id,e.hint])),QN={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 Hm(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 ez({item:e}){let t=JN[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&&pt(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:YN[e.status]??t},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:Hm(e.updatedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function tz({gate:e,now:t}){let[n,o]=A(null),r=async(c)=>{o(c),await pS(e,c),o(null)},s=e.nodeIds[0],a=tu(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&&pt(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 ",nu(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:Hm(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nz({gate:e}){let[t,n]=A(!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),mS(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 oz(e){let t=e.resolvedBy;if(!t)return e.status;let n=e.status==="approved"?"Approved":"Rejected";if(t.actor==="human")return`${n} by you`;if(t.actor==="system")return`${n} by system`;let o=t.agentId||t.source||"agent";return`${e.selfAnswer?"Self-":""}${n.toLowerCase()} by ${o}`}function rz({gate:e}){return i("li",{class:`session-item status-${e.status}`,"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:oz(e)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function iz(){let e=Qo.value,t=Ne.value.size,[n,o]=A(!1),r=(s)=>{o(!0),sS(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(_e,{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(_e,{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([...Ne.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 sz(e){if(e==="browser")return"you";return It.value.find((n)=>n.sessionId===e||n.source===e)?.label??e}function az({entry:e}){let t=ea.value.has(e.id);return i("li",{class:`session-timeline-row tone-${QN[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:Ak[Sm(e.kind)],children:e.label},void 0,!1,void 0,this),e.who&&i("span",{class:"session-timeline-who",style:{"--identity-color":An(e.who)},children:sz(e.who)},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:Hm(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 km(e),children:[i(Gd,{size:14},void 0,!1,void 0,this)," undo this edit"]},void 0,!0,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 Ik(){let[e,t]=A(!1),n=Li.value,o=iS.value,r=Mr.value,s=aS.value,a=cS.value,c=dS.value,[l,u]=A(!1),[p,d]=A(null),m=xo();if(H(()=>{er()},[]),!(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:Jo(n),"aria-label":`Session live: ${Jo(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:Jo(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 Bl(n),children:"End"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-collapse",onClick:()=>t(!1),title:"Collapse session panel","aria-label":"Collapse session panel",children:i(ks,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(iz,{},void 0,!1,void 0,this),(()=>{let h=c.find((v)=>v.undoable&&!ea.value.has(v.id));if(!h)return null;return i("div",{class:"session-undo-row","data-testid":"session-undo-row",children:[i("span",{class:"session-undo-text",title:h.body,children:["Agent edit on top: ",h.body]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-undo-btn",onClick:()=>void km(h),children:[i(Gd,{size:14},void 0,!1,void 0,this)," Undo"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)})(),i("div",{class:"session-panel-body",children:[i("section",{class:"session-section",children:(()=>{let h=o.filter((M)=>M.status==="in-progress"||M.status==="todo").length,v=o.filter((M)=>M.status!=="cancelled"),x=v.filter((M)=>M.status==="done").length,g=o.length-v.length,b=r.length>0,I=l||b,R=h>0?`${h} running`:v.length>0?`${x}/${v.length} done${g>0?` · ${g} cancelled`:""}`:o.length>0?`${o.length} cancelled`:"none yet";return i(_e,{children:[i("button",{type:"button",class:"session-section-toggle","aria-expanded":I,"data-testid":"work-items-toggle",onClick:()=>u((M)=>!M),children:[i("span",{class:"session-section-title",children:"Work items"},void 0,!1,void 0,this),i("span",{class:"session-work-summary",children:[h>0&&i("span",{class:"session-work-dot","aria-hidden":"true"},void 0,!1,void 0,this),R]},void 0,!0,void 0,this),i("span",{class:`session-section-chevron${I?" is-open":""}`,"aria-hidden":"true",children:i(ks,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I&&(r.length===0&&s.length===0&&a.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((M)=>i(tz,{gate:M,now:m},M.id,!1,void 0,this)),s.map((M)=>i(nz,{gate:M},M.id,!1,void 0,this)),a.map((M)=>i(rz,{gate:M},M.id,!1,void 0,this)),o.map((M)=>i(ez,{item:M},M.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:Ek.map((h)=>i("button",{type:"button",class:`activity-filter${$r.value===h.id?" is-active":""}`,"aria-pressed":$r.value===h.id,title:h.hint,onMouseEnter:()=>d(h.id),onMouseLeave:()=>d((v)=>v===h.id?null:v),onFocus:()=>d(h.id),onBlur:()=>d((v)=>v===h.id?null:v),onClick:()=>{$r.value=h.id},children:h.label},h.id,!1,void 0,this))},void 0,!1,void 0,this),i("div",{class:"session-timeline-hint","data-testid":"timeline-filter-hint",children:Ak[p??$r.value]},void 0,!1,void 0,this),c.length===0?i("div",{class:"session-empty",children:$r.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:c.map((h)=>i(az,{entry:h},h.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 jm(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)}}var Pk=(e)=>e.map((t)=>t.title).join(", ");function cz({context:e,label:t}){let o=[{key:"read",name:"Read",glyph:"eye"},{key:"pinned",name:"Pinned",glyph:"pin"},{key:"created",name:"Created",glyph:"spark"},{key:"edited",name:"Edited",glyph:"pen"}].filter((s)=>e[s.key].length>0);if(o.length===0&&e.changedSinceRead.length===0)return null;let r=nr.value!==null;return i("div",{class:"session-receipt-context","data-testid":"session-receipt-context",children:[e.changedSinceRead.length>0&&i("div",{class:"session-receipt-warn",children:[i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:i("path",{d:Zl.warn},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{children:[Pk(e.changedSinceRead)," changed after ",t," read"," ",e.changedSinceRead.length===1?"it":"them","."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o.map((s)=>i("div",{class:"session-receipt-context-row","data-row":s.key,children:[i("div",{class:"session-receipt-context-head",children:[s.glyph==="pin"?i($c,{},void 0,!1,void 0,this):i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:i("path",{d:Zl[s.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"session-receipt-context-name",children:s.name},void 0,!1,void 0,this),i("span",{class:"session-receipt-context-count",children:e[s.key].length},void 0,!1,void 0,this),s.key==="pinned"&&i("button",{type:"button",class:"session-receipt-mini",onClick:()=>{for(let a of e.pinned)Jn(a.id)},children:"Unpin"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-context-items",children:s.key==="pinned"?e.pinned.map((a)=>a.reason?`${a.title} — “${a.reason}”`:a.title).join("; "):Pk(e[s.key])},void 0,!1,void 0,this)]},s.key,!0,void 0,this)),i("button",{type:"button",role:"switch","aria-checked":r,class:`session-receipt-lens${r?" is-on":""}`,onClick:()=>Cm(!r),children:[i("span",{class:"session-receipt-lens-track","aria-hidden":"true",children:i("span",{class:"session-receipt-lens-knob"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"Dim untouched nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Nk({onOpenSnapshots:e}){let t=Di.value,[n,o]=A(null),[r,s]=A(!1);if(H(()=>o(null),[t]),!t)return null;let a=async()=>{if(!t.snapshot)return;s(!0);try{let u=await ct(`/api/canvas/snapshots/${encodeURIComponent(t.snapshot.id)}/diff`,{headers:{"x-pmx-workbench":"1"}});if(u.ok){let p=await u.json();o(jm(p.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.sessions>1?`${t.sessions} sessions ended`: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:Hl,"aria-label":"Dismiss receipt",children:i(Ve,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.sessions>1&&i("div",{class:"session-receipt-who",children:t.labels.join(", ")},void 0,!1,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(cz,{context:t.context,label:t.labels.join(", ")},void 0,!1,void 0,this),i("div",{class:"session-receipt-note",children:t.sessions>1?"History has each session’s diff and the snapshot from before it.":t.snapshot?"A snapshot of the board from before this session is saved — restore it to undo the session.":t.context.created.length===0&&t.context.edited.length===0?"The board itself did not change — nothing to restore.":"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 lz=[{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:rt("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:rt("0"),desc:"Reset viewport to origin"},{keys:`${rt("+")} / ${rt("−")}`,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:Es?"Delete / ⌫":"Delete / Backspace",desc:"Delete the selection (or the focused node)"},{keys:Es?"⌘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 zk({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:lz.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:Se()&&n.desc.startsWith("Undo / redo")?"Undo / redo — available in the local workbench only":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 Rk="Before session · ";function Mk(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 uz(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 ou(e){if(!e.startsWith(Rk))return null;let t=e.slice(Rk.length),n=t.lastIndexOf(" · ");return n>0?t.slice(0,n):t}function $k({open:e,onClose:t,anchorRef:n}){let[o,r]=A([]),[s,a]=A(!1),[c,l]=A(!1),[u,p]=A(null),[d,m]=A(""),[f,h]=A(null),[v,x]=A({}),g=L(null),b=L(null);H(()=>{if(!e)return;a(!0),_b().then((w)=>{r(w),a(!1)})},[e]),H(()=>{if(e)setTimeout(()=>b.current?.focus(),50)},[e]),H(()=>{if(!e)return;let w=(k)=>{let z=g.current,X=n.current;if(z&&!z.contains(k.target)&&X&&!X.contains(k.target))t()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[e,t]),H(()=>{if(!e)return;let w=(k)=>{if(k.key==="Escape")t()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,t]);let I=j(async()=>{let w=d.trim();if(!w)return;l(!0);let k=await Sb(w);if(l(!1),k.ok&&k.snapshot)r((z)=>[k.snapshot,...z]),m("")},[d]),R=j(async(w)=>{h(null),p(w);let k=await kb(w);if(p(null),k.ok)t()},[t]),M=j(async(w)=>{if((await Tb(w)).ok)r((z)=>z.filter((X)=>X.id!==w));h(null)},[]),_=j(async(w)=>{x((z)=>({...z,[w]:"loading"}));let k=await ne("snapshotDiff",`/api/canvas/snapshots/${encodeURIComponent(w)}/diff`,{});x((z)=>({...z,[w]:jm(k.diff)??{added:0,removed:0,modified:0}}))},[]);if(!e)return null;let N=(w,k)=>f?.id===w.id?i(_e,{children:[i("button",{type:"button",class:`snapshot-action-btn ${f.action==="delete"?"snapshot-action-confirm":"snapshot-action-restore"}`,onClick:()=>f.action==="delete"?M(w.id):R(w.id),title:f.action==="delete"?"Confirm delete":"Confirm restore",disabled:u!==null,children:f.action==="delete"?"Delete":u===w.id?"Restoring…":"Confirm"},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn",onClick:()=>h(null),title:"Cancel",disabled:u!==null,children:"Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(_e,{children:[i("button",{type:"button",class:"snapshot-action-btn snapshot-action-restore",onClick:()=>h({id:w.id,action:"restore"}),title:Se()?"Restore this snapshot — replaces the current canvas":"Restore this snapshot — replaces the current canvas (undoable)",disabled:u!==null,children:u===w.id?"Restoring…":k},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn snapshot-action-delete",onClick:()=>h({id:w.id,action:"delete"}),title:"Delete this snapshot","aria-label":"Delete snapshot",disabled:u!==null,children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{ref:g,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:i(Ve,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-save-form",children:[i("input",{ref:b,type:"text",class:"snapshot-name-input",value:d,onInput:(w)=>m(w.target.value),onKeyDown:(w)=>{if(w.key==="Enter")I()},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:I,disabled:!d.trim()||c,children:c?"…":"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-restore-note",children:Se()?"Restoring replaces the current canvas. Save a snapshot first to keep your current state.":"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((w)=>ou(w.name)===null),...o.some((w)=>ou(w.name)!==null)?[{id:"__sessions-header__"}]:[],...o.filter((w)=>ou(w.name)!==null)].map((w)=>{if(w.id==="__sessions-header__")return i("div",{class:"snapshot-section-header","data-testid":"history-sessions-header",children:"Sessions"},w.id,!1,void 0,this);let k=ou(w.name),z=v[w.id];if(k!==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 — ",k]},void 0,!0,void 0,this),i("span",{class:"snapshot-item-time",children:Mk(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:["snapshot at session start · ",w.nodeCount," node",w.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 _(w.id),children:z==="loading"?"Comparing…":"View diff"},void 0,!1,void 0,this),N(w,"Restore pre-state")]},void 0,!0,void 0,this)]},w.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:w.name},void 0,!1,void 0,this),i("span",{class:"snapshot-item-time",children:Mk(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:[w.nodeCount," node",w.nodeCount!==1?"s":"",w.edgeCount>0?` · ${w.edgeCount} edge${w.edgeCount!==1?"s":""}`:""," · ",uz(w.createdAt)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-actions",children:N(w,"Restore")},void 0,!1,void 0,this)]},w.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 dz=8;function pz({children:e}){let t=Be(()=>document.createElement("div"),[]);return _n(()=>(document.body.appendChild(t),()=>{Qi(null,t),t.remove()}),[t]),_n(()=>Qi(e,t),[e,t]),null}function Ok({fallbackName:e}){let[t,n]=A(!1),o=L(null),r=L(null),s=L(null);_n(()=>{if(!t)return;let d=(f)=>{if(f.target instanceof Node&&!o.current?.contains(f.target)&&!s.current?.contains(f.target))n(!1)},m=(f)=>{if(f.key==="Escape")f.stopPropagation(),n(!1),r.current?.focus()};return document.addEventListener("pointerdown",d,!0),document.addEventListener("keydown",m,!0),()=>{document.removeEventListener("pointerdown",d,!0),document.removeEventListener("keydown",m,!0)}},[t]);let a=dc(),c=!$o.value?e:a?a.name:"Home",l=rn.value.filter((d)=>d.id!==Oe.value).slice(0,dz),u=r.current?.getBoundingClientRect(),p=(d)=>{n(!1),sn(d)};return i("span",{class:"board-switcher",ref:o,children:[i("button",{ref:r,type:"button",class:"top-bar-title board-switcher-button","aria-haspopup":"menu","aria-expanded":t,"aria-label":`Board: ${c}. Switch board`,onClick:()=>n((d)=>!d),children:[i("span",{class:"board-switcher-name",children:c},void 0,!1,void 0,this),i("span",{class:"board-switcher-caret","aria-hidden":"true",children:i(Nc,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&u&&i(pz,{children:i("div",{ref:s,class:"toolbar-menu board-switcher-menu",role:"menu","aria-label":"Boards",style:{position:"fixed",left:`min(${u.left}px, max(12px, calc(100vw - 352px)))`,top:`${u.bottom+8}px`,right:"auto",maxHeight:`min(70vh, calc(100dvh - ${u.bottom+20}px))`},children:[l.length>0&&i("div",{class:"board-switcher-heading",children:"Recent boards"},void 0,!1,void 0,this),i("div",{class:"board-switcher-recents",children:l.map((d)=>i("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>p(d.id),children:[i("span",{class:"board-switcher-icon","aria-hidden":"true",children:i(Oc,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"board-switcher-item-copy",children:[i("span",{class:"board-switcher-item-name",children:d.name},void 0,!1,void 0,this),i("span",{class:"board-switcher-item-folder",children:d.category?.split("/").join(" / ")||"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"board-switcher-item-meta",children:[d.nodeCount," ",d.nodeCount===1?"node":"nodes"]},void 0,!0,void 0,this)]},d.id,!0,void 0,this))},void 0,!1,void 0,this),i("div",{class:"board-switcher-actions",children:[i("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>{n(!1),Fm()},children:[i("span",{class:"board-switcher-icon","aria-hidden":"true",children:i(ox,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),"New board…"]},void 0,!0,void 0,this),i("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>p(null),children:[i("span",{class:"board-switcher-icon","aria-hidden":"true",children:i(go,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),"All boards (Home)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Lk=3,Dk={"waiting-approval":0,thinking:1,tooling:2,idle:3};function mz(){let e=nS.value;if(e.length===0)return null;let t=e.filter((c)=>!c.parentAgentId||!e.some((l)=>l.sessionId!==c.sessionId&&!l.parentAgentId&&(l.sessionId===c.parentAgentId||l.source===c.parentAgentId))),n=[...t].sort((c,l)=>(Dk[c.phase]??4)-(Dk[l.phase]??4)),o=n.slice(0,Lk),r=n.slice(Lk),s=t.reduce((c,l)=>(c[l.phase]=(c[l.phase]??0)+1,c),{}),a=[s["waiting-approval"]&&`${s["waiting-approval"]} waiting on approval`,s.thinking&&`${s.thinking} thinking`,s.tooling&&`${s.tooling} running tools`,s.idle&&`${s.idle} idle`].filter(Boolean).join(", ");return i(_e,{children:[i("span",{class:"agent-chips",children:o.map((c)=>{let l=c.parentAgentId?0:It.value.filter((u)=>u.parentAgentId!=null&&(u.parentAgentId===c.sessionId||u.parentAgentId===c.source)).length;return i(Qe,{label:`Agent session — ${c.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-${c.phase}`,"data-phase":c.phase,style:{"--identity-color":An(c.sessionId)},children:[i("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"agent-chip-label",children:Jo(c)},void 0,!1,void 0,this),i("span",{class:"agent-chip-who hud-collapsible-text",children:c.label},void 0,!1,void 0,this),l>0&&i("span",{class:"agent-chip-workers",children:["+",l," worker",l===1?"":"s"]},void 0,!0,void 0,this),i("button",{type:"button",class:"agent-chip-end","aria-label":`End ${c.label} session`,title:`End ${c.label}'s session`,onClick:(u)=>{u.stopPropagation(),Bl({source:c.source,agentId:c.agentId})},children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},c.sessionId,!1,void 0,this)})},void 0,!1,void 0,this),r.length>0&&i(Qe,{label:`${t.length} agent sessions attached`,tapToOpen:!0,body:`${t.length} agents on this board — ${a}. 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:["+",r.length," · ",t.length," agents"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function fz(){let e=Mr.value.length,t=Li.value!==null&&e>0,n=xo(t?1000:0);if(!t)return null;let o=Mr.value.map((r)=>tu(r,n)).filter((r)=>r!==null).sort((r,s)=>r-s)[0];return i(Qe,{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&&` · ${nu(o)}`]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function hz(e){if(e>0.9)return"danger";if(e>=0.7)return"warn";return"ok"}function ra(e){return e>=1000?`${(e/1000).toFixed(e>=1e4?0:1)}k`:String(e)}function gz(){let e=Li.value;if(!e)return null;let t=gm.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:`${ra(n.used)} of ${ra(n.total)} tokens of the agent's actual context window are used. Your ✦-pinned nodes account for ≈ ${ra(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: ≈ ${ra(t.used)} of a ${ra(t.total)}-token budget. When the agent's host reports its real context window, this meter switches to showing that instead.`};return i(Qe,{label:c.label,body:c.body,tapToOpen:!0,children:i("span",{class:`context-budget tone-${hz(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 vz(){let[e,t]=A(!1);if(Li.value)return null;return i(Qe,{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),tr().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 Fk(){let e=fn.value,t=Yt.value,n=oe.value,o=F.value.size,r=Je.value.size,s=li.value,a=Array.from(F.value.values()).filter((f)=>f.type==="trace").length,[c,l]=A("");H(()=>{let f=!1;return ct("/health").then((h)=>h.ok?h.json():null).then((h)=>{if(f||typeof h?.workspace!=="string"||!h.workspace)return;let v=h.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop();if(v)l(v)}).catch(()=>{}),()=>{f=!0}},[]);let u=zm.value,p=u??(e==="connected"&&!t?"syncing":e),d=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=bt();pi(f.width,f.height)};return i("div",{class:"top-bar",children:[i(Qe,{label:`Canvas status: ${p}`,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: ${p}`},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Ok,{fallbackName:c||"PMX Canvas"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:lo.value?lo.value.slice(0,12):"…"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:d},void 0,!1,void 0,this),i("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),i(mz,{},void 0,!1,void 0,this),i(fz,{},void 0,!1,void 0,this),i(gz,{},void 0,!1,void 0,this),i(hk,{},void 0,!1,void 0,this),!Se()&&i(vz,{},void 0,!1,void 0,this),i("div",{class:"top-bar-sep"},void 0,!1,void 0,this),Oe.value&&i(Qe,{label:"Export board",body:"One HTML file of this board that anyone can open, no install needed.",children:i("button",{type:"button",class:"present-button",onClick:()=>{Ui.value=!0},children:"Export"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Oe.value&&i(Qe,{label:"Present board",body:"Arrow keys or Space step through stops; Esc exits. Without a saved tour, groups are read top-to-bottom, left-to-right.",children:i("button",{type:"button",class:"present-button",onClick:()=>{Fn.value=!0},children:"Present"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Qe,{label:"Zoom out",shortcut:rt("−"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>di(0.8),"aria-label":"Zoom out",children:i(lx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Qe,{label:"Reset zoom",shortcut:rt("0"),children:i("button",{type:"button",class:"top-bar-zoom-label",onClick:()=>Fo({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(Qe,{label:"Zoom in",shortcut:rt("+"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>di(1.25),"aria-label":"Zoom in",children:i(cx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Qe,{label:"Fit all",shortcut:"F",align:"end",children:i("button",{type:"button",class:"top-bar-btn",onClick:m,"aria-label":"Fit canvas",children:i(zc,{},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 or={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},board:{x:380,y:80,w:360,h:160},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 ia(e,t,n,o={}){let r=or[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 Fr=null,ca=null,ru=0,rr=null,yz=3000,bz=2000,Bk=5000,sa=!1,wo=null,Zi=null,sr=0,ir=null;function xz(){if(Se())return"poll";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 Wi=new Map;function la(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 su(e){if(!ca)return e;let t=ca.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 ua(e,t,n){return su(ia(e,t,n))}function wz(){return cl([...F.value.values()],or.markdown.w,or.markdown.h)}function qi(){if(!F.value.has("status-main"))po(ua("status-main","status",{phase:"idle",message:"",elapsed:0}))}function _z(e,t){let n=`md-${la(e)}`;if(F.value.get(n))fe(n,{path:e,title:t}),je.value=n;else{let r=wz(),s=ua(n,"markdown",{path:e,title:t,content:"",rendered:""});s.position=r,po(s),pt(n)}}function Sz(e){if(F.value.get("context-main"))fe("context-main",{cards:e});else if(e.length>0){let o=ua("context-main","context",{cards:e});po(o)}}function kz(e){let t=e.url,n=`mcp-${la(t)}`;if(F.value.get(n))fe(n,e);else po(ua(n,"mcp-app",e)),pt(n)}function Tz(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(F.value.get(o)){fe(o,e);return}let{serverName:s,toolName:a}=e;if(s&&a){for(let[x,g]of F.value.entries())if(g.type==="mcp-app"&&g.data.mode==="ext-app"&&g.data.serverName===s&&g.data.toolName===a&&!g.data.toolResult){fe(x,{...e});return}}let{_x:c,_y:l,_width:u,_height:p}=e,d=or["mcp-app"],m=u??d.w,f=p??d.h,h=c===void 0||l===void 0?cl([...F.value.values()],m,f):null,v=su(ia(o,"mcp-app",{mode:"ext-app",...e},{position:{x:c??h?.x??d.x,y:l??h?.y??d.y},size:{width:m,height:f}}));po(v),pt(o,{recordHistory:!1})}function Cz(e){let t=e.startsWith("ext-app-")?e:`ext-app-${e}`;if(F.value.has(t))return t;let n=`ext-app-${e}`;if(n!==t&&F.value.has(n))return n;for(let[o,r]of F.value.entries())if(r.type==="mcp-app"&&r.data.mode==="ext-app"&&r.data.toolCallId===e)return o;return null}function qk(e){let t=typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null;if(t&&F.value.has(t))return t;if(typeof e.toolCallId!=="string"||!e.toolCallId)return null;return Cz(e.toolCallId)}function Gk(e,t){if(typeof e!=="string"||!e)return null;if(typeof t!=="string"||!t)return null;let n=null;for(let[o,r]of F.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 Vk(e){if(F.value.get("ledger-main"))fe("ledger-main",e);else{let o=ua("ledger-main","ledger",e);o.collapsed=!0,po(o)}}function qm(e){if(!Ls(e))return;if(document.documentElement.setAttribute("data-theme",e),Ri(),gt.value!==e)gt.value=e}function Ez(e){return e==="markdown"||e==="mcp-app"||e==="webpage"||e==="json-render"||e==="graph"||e==="board"||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 Az(e){return e==="relation"||e==="depends-on"||e==="flow"||e==="references"}function Gm(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 Xk(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 Iz(e){let t=Gm(e),n=Xk(e);return t&&n?{...t,...n}:null}function Pz(e){if(typeof e.id!=="string"||!e.id)return null;if(!Ez(e.type))return null;let t=Gm(e.position),n=Xk(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,contentRevision:typeof e.contentRevision==="number"?e.contentRevision:0,...Hk(e.createdBy)?{createdBy:e.createdBy}:{},...Hk(e.lastEditedBy)?{lastEditedBy:e.lastEditedBy}:{},data:o}}function Hk(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.actor==="string"&&typeof t.source==="string"}function Nz(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(!Az(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 zz(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)=>Gm(o)).filter((o)=>o!==null),n=Iz(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 jk="pmx-canvas-version-reload";function Rz(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(jk)===r)return;window.sessionStorage.setItem(jk,r)}catch{return}window.location.reload()}function Mz(e){let t=Yo.value[0]?.id;if(bm(e),_t.value&&Yo.value[0]?.id!==t)er()}function $z(e){hS(e)}var Uk=null,aa=0,Um=0,Zm=0;function Oz(e){Ep(e)}function Lz(){let e=++aa;ca=null,Yt.value=!1,tl(),Mb(),ac(),Hl(),Em({}),Dn.value=null,Vm();let t=Um,n=Zm;fb().then((o)=>{if(e===aa&&t===Um)Kk({layout:o})}),ne("fetchPinnedContext","/api/canvas/pinned-context",{}).then((o)=>{if(e===aa&&n===Zm)Jk({nodeIds:o.nodeIds})})}sb(Lz);function Dz(e){if(lo.value=e.sessionId||"",fn.value="connected",Pd().then(bs),_r.value+=1,Rz(e.version,e.bundleStamp),yb().then(bm),jl(),Uk?.(),!pc&&!Se())Uk=qw();if(ne("fetchHumanPresence","/api/canvas/human-presence",null).then(Ep),Vm().then(()=>{if(_t.value)er()}),typeof e.theme==="string"&&!Rm())qm(e.theme);if(e.ledgerSummary)Vk(e.ledgerSummary)}function Fz(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(_z(t,n),e.ledgerSummary)Vk(e.ledgerSummary)}function Bz(e){qi(),fe("status-main",{message:typeof e.message==="string"?e.message:String(e.message??""),level:e.level??"ok",source:e.source})}function Hz(e){qi(),fe("status-main",{phase:e.phase,detail:e.detail})}function jz(e){let t=e.cards??[];Sz(t)}function Uz(e){if(typeof e.url==="string"&&e.url)kz({url:e.url,sourceServer:e.sourceServer,sourceTool:e.sourceTool,inferredType:e.inferredType,trustedDomain:e.trustedDomain,hostMode:e.hostMode??"hosted"})}function Zz(e){let t=e.sessions??[];for(let n of t){let o=n.url;if(!o)continue;let r=`mcp-${la(o)}`;if(F.value.has(r))fe(r,{sessionState:n.state,lastSeenAt:n.lastSeenAt})}}function Wz(e){if(typeof e.url==="string"&&e.url){let t=`mcp-${la(e.url)}`;if(F.value.has(t))fe(t,{hostMode:"fallback",fallbackReason:e.reasonCode})}}function qz(e){let n=F.value.get("context-main");if(!n)return;let o=(n.data.auxTabs??[]).concat(e);fe("context-main",{auxTabs:o})}function Gz(e){if(F.value.has("context-main"))if(e.mode==="all")fe("context-main",{auxTabs:[]});else{let o=F.value.get("context-main");if(!o)return;let r=(o.data.auxTabs??[]).filter((s)=>s.id!==e.id);fe("context-main",{auxTabs:r})}}function Vz(e){qi(),fe("status-main",{phase:"idle",lastCompletion:{tokenCount:e.tokenCount,artifactCount:e.artifactCount}})}function Xz(e){qi(),fe("status-main",{phase:"tooling",detail:`${e.name}`,activeTool:e.name})}function Kz(e){qi(),fe("status-main",{activeTool:null})}function Jz(e){if(e.state==="active"&&e.path){let n=`md-${la(e.path)}`;if(F.value.has(n))fe(n,{reviewActive:!0})}}function Yz(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;Tz({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 Qz(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=qk(e)??Gk(e.serverName,e.toolName);if(!t)return;if(F.value.has(t))fe(t,{html:e.html})}function eR(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=qk(e)??Gk(e.serverName,e.toolName);if(!t)return;if(F.value.has(t)){if(e.success===!1){Do(t);return}fe(t,{toolResult:cm({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 tR(e){qi(),fe("status-main",{subagent:{state:e.state,name:e.agentDisplayName??e.agentName}})}function nR(e){let t=e.nodeId;if(!t)return;let n=e.text||"",{position:o,parentNodeId:r,contextNodeIds:s}=e;if(e.threadNodeId&&F.value.has(e.threadNodeId)){let a=e.threadNodeId,c=F.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"});fe(a,{turns:l,threadStatus:"pending"});return}if(!F.value.has(t)){let a=o??or.prompt;po(su(ia(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}}))),pt(t)}if(r&&F.value.has(r))ai({id:`edge-${r}-${t}`,from:r,to:t,type:"flow",style:"dashed"})}function oR(e){let{nodeId:t,status:n}=e;if(t&&F.value.has(t))fe(t,{status:n})}function rR(e){let{responseNodeId:t,promptNodeId:n}=e;if(!t)return;let o=n?F.value.get(n):void 0;if(o&&Array.isArray(o.data.turns)){Wi.set(t,n);let s=[...o.data.turns];s.push({role:"assistant",text:"",status:"streaming"}),fe(n,{turns:s,threadStatus:"streaming",_activeResponseId:t}),pt(n);return}let r=o?{x:o.position.x,y:o.position.y+o.size.height+24}:{x:or.response.x,y:or.response.y};if(!F.value.has(t))po(su(ia(t,"response",{content:"",status:"streaming",promptNodeId:n},{position:r})));if(n)ai({id:`edge-${n}-${t}`,from:n,to:t,type:"flow",animated:!0});pt(t)}function iR(e){let t=e.responseNodeId;if(!t)return;let n=Wi.get(t);if(n){let o=F.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";fe(n,{turns:r,threadStatus:"streaming"})}return}if(!F.value.has(t))return;fe(t,{content:e.content,status:"streaming"})}function sR(e){let t=e.responseNodeId;if(!t)return;let n=Wi.get(t);if(n){let s=F.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";fe(n,{turns:a,threadStatus:"answered",_activeResponseId:void 0})}Wi.delete(t);return}if(!F.value.has(t))return;fe(t,{content:e.content,status:"complete"});let r=F.value.get(t)?.data.promptNodeId;if(r){let s=`edge-${r}-${t}`,a=Je.value.get(s);if(a)Ub(s),ai({...a,animated:!1})}}function Kk(e){let t=e.layout;if(!t?.nodes)return;Um+=1;let n=!Yt.value;Yt.value=!0;let o=t.nodes.map(Pz).filter((c)=>c!==null),r=Array.isArray(t.edges)?t.edges.map(Nz).filter((c)=>c!==null):Array.from(Je.value.values()),s=Array.isArray(t.annotations)?t.annotations.map(zz).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)fo();Xb({...a?{viewport:a}:{},nodes:o,edges:r,...s?{annotations:s}:{}},{applyViewport:n}),Ad({event:"canvas-layout-update",data:e})}function aR(e){if(e<=1)return 500;if(e===2)return 1000;return Math.min(2500,1500+(e-3)*500)}function cR(e){if(Zd())return;let t=e.nodeId;if(t&&F.value.has(t)){if(e.noPan===!0){mo(t);return}pt(t)}}function lR(e){if(Zd())return;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;fo(),qb({x:n,y:o,scale:r})}function uR(e){if(F.value.get("context-main"))fe("context-main",{currentTokens:e.currentTokens,tokenLimit:e.tokenLimit,messagesLength:e.messagesLength,utilization:e.utilization,nearLimit:e.nearLimit})}function dR(e){li.value=e.enabled===!0}function pR(e){if(typeof e.theme==="string"&&!Rm())qm(e.theme)}function Jk(e){Zm+=1;let t=Array.isArray(e.nodeIds)?e.nodeIds.filter((n)=>typeof n==="string"):[];jb(t),Ad({event:"context-pins-changed",data:e}),jl()}function mR(){jl()}var iu=null,Wm=0;async function Vm(){let e=++Wm,t=aa,n=await vb();if(e===Wm&&t===aa)Dn.value=n}function Zk(){if(iu)clearTimeout(iu);Wm+=1,iu=setTimeout(()=>{if(iu=null,Vm(),_t.value)er()},150)}function fR(e){let t=e.intent;if(!t||typeof t.id!=="string"||typeof t.kind!=="string"||typeof t.expiresAt!=="number")return;Dw(t)}function hR(e){let t=typeof e.id==="string"?e.id:"";if(!t)return;if(e.settled===!0)Bw(t,typeof e.nodeId==="string"?e.nodeId:void 0);else Cp(t)}var Yk={connected:Dz,"workbench-open":Fz,"canvas-status":Bz,"execution-phase":Hz,"context-cards":jz,"mcp-app-candidate":Uz,"mcp-app-host-snapshot":Zz,"mcp-app-host-fallback":Wz,"aux-open":qz,"aux-close":Gz,"assistant-complete":Vz,"tool-start":Xz,"tool-complete":Kz,"review-state":Jz,"subagent-status":tR,"ext-app-open":Yz,"ext-app-update":Qz,"ext-app-result":eR,"context-pins-changed":Jk,"context-status-changed":mR,"boards-changed":vr,"canvas-layout-update":Kk,"canvas-focus-node":cR,"canvas-viewport-update":lR,"context-usage":uR,"trace-state":dR,"theme-changed":pR,"canvas-prompt-created":nR,"canvas-prompt-status":oR,"canvas-response-start":rR,"canvas-response-delta":iR,"canvas-response-complete":sR,"ax-state-changed":Zk,"ax-event-created":Zk,"ax-intent":fR,"ax-intent-clear":hR,"agent-presence":Mz,"human-presence":Oz,"agent-session-ended":$z};function Qk(e,t){let n=Yk[e];if(!n)return;let o=n;try{o(t)}catch(r){console.warn(`[sse-bridge] Handler for "${e}" failed:`,r)}}function Wk(){sa=!0,sr+=1;let e=sr;fn.value="connecting";let t=null,n=!1,o=async()=>{if(e!==sr)return;try{let r=new URLSearchParams;if(Zi!==null)r.set("since",String(Zi));let s=lo.value;if(s)r.set("session",s);let a=r.toString(),c=await ct(`/api/workbench/poll${a?`?${a}`:""}`);if(e!==sr)return;if(!c.ok)throw Error(`poll failed with HTTP ${c.status}`);let l=await c.json();if(e!==sr)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){Zi=null,wo=setTimeout(()=>void o(),0);return}if(l.snapshot&&n)ca=Ud(),Yt.value=!1,ac(),tl(),Wi.clear();for(let p of l.events)Qk(p.event,p.payload);n=!0,Zi=l.seq,Sr.value=0,kr.value=0,fn.value="connected",wo=setTimeout(()=>void o(),bz)}catch(r){if(e!==sr)return;console.warn("[sse-bridge] poll transport error:",r),fn.value="disconnected",Sr.value+=1,kr.value=Bk,wo=setTimeout(()=>void o(),Bk)}};return o(),()=>{if(sr+=1,sa=!1,Zi=null,wo)clearTimeout(wo),wo=null}}function Xm(){if(JS(qm),ca=Ud(),Yt.value=!1,ac(),tl(),Wi.clear(),rr)clearTimeout(rr),rr=null;let e=xz();if(e==="poll"||sa)return Wk();let t=lo.value,n=t?`/api/workbench/events?session=${t}`:"/api/workbench/events";fn.value="connecting";let o=new EventSource(n);Fr=o;let r=!1;if(ir)clearTimeout(ir);if(ir=null,e!=="sse")ir=setTimeout(()=>{if(ir=null,r||Fr!==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(),Fr=null,Wk()},yz);for(let[s]of Object.entries(Yk))o.addEventListener(s,(a)=>{r=!0;try{Qk(s,JSON.parse(a.data))}catch(c){console.warn(`[sse-bridge] Failed to parse "${s}" event:`,c)}});return o.onopen=()=>{if(Fr!==o)return;ru=0,Sr.value=0,kr.value=0,fn.value="connected"},o.onerror=()=>{if(Fr!==o)return;fn.value="disconnected",o.close(),Fr=null,ru+=1;let s=aR(ru);Sr.value=ru,kr.value=s,rr=setTimeout(()=>{rr=null,Xm()},s)},()=>{if(rr)clearTimeout(rr),rr=null;if(ir)clearTimeout(ir),ir=null;if(sa){if(sr+=1,sa=!1,Zi=null,wo)clearTimeout(wo),wo=null}o.close(),Fr=null}}function Br(e,t){console.error(`[app] ${e} failed`,t)}function e0(){let[e,t]=A(!0),[n,o]=A(!1),[r,s]=A(!1),[a,c]=A(!1),[l,u]=A(!1),[p,d]=A(null),m=L(null),{menu:f,openNodeMenu:h,openCanvasMenu:v,openEdgeMenu:x,closeMenu:g}=ek(),b=Yt.value,I=$o.value&&Oe.value===null,R=_t.value,M=j(()=>t((W)=>!W),[]),_=j(()=>o((W)=>!W),[]),N=j(()=>o(!1),[]),w=j((W)=>d(W),[]),k=j((W,J)=>{Fo({x:W,y:J,scale:oe.value.scale},200)},[]);H(()=>Xm(),[]),H(()=>{let W=()=>c(!0);return window.addEventListener("pmx-open-board-link",W),()=>window.removeEventListener("pmx-open-board-link",W)},[]),H(()=>{let W=null,J=()=>{if(W!==null)window.clearTimeout(W);W=window.setTimeout(()=>{W=null,bs()},400)};return window.addEventListener("resize",J),()=>{if(W!==null)window.clearTimeout(W);window.removeEventListener("resize",J)}},[]),H(()=>{let W=(S)=>{let q=(S.metaKey||S.ctrlKey)&&!S.altKey;if(q&&S.key==="k"){S.preventDefault(),s((ue)=>!ue);return}if(S.key==="Escape"&&p){S.preventDefault(),d(null);return}if(S.key==="Escape"&&ot.value&&!Ln.value){S.preventDefault(),ho();return}if(S.key==="Escape"&&r){S.preventDefault(),s(!1);return}if(S.key==="Escape"&&l){S.preventDefault(),u(!1);return}let ie=S.target,ye=ie?.tagName;if(ye==="INPUT"||ye==="TEXTAREA"||ie?.isContentEditable)return;if(S.key===" "&&!S.repeat&&!q){S.preventDefault(),_s.value=!0;return}if(S.key==="?"||S.key==="/"&&S.shiftKey){S.preventDefault(),u((ue)=>!ue);return}if(q&&(S.key==="z"||S.key==="Z"))S.preventDefault(),Tm(S.shiftKey);else if(q&&(S.key==="y"||S.key==="Y"))S.preventDefault(),Tm(!0);else if(q&&S.key==="0")S.preventDefault(),Fo({x:0,y:0,scale:1},250);else if(q&&(S.key==="="||S.key==="+"))S.preventDefault(),di(1.25);else if(q&&S.key==="-")S.preventDefault(),di(0.8);else if(S.key==="Escape"){if(Ne.value.size>0||Kn.value!==null){Ut();return}je.value=null,g()}else if(S.key==="Tab")S.preventDefault(),Jb(S.shiftKey?-1:1);else if(S.key==="Delete"||S.key==="Backspace"){if(Kn.value!==null){let Pe=Kn.value;S.preventDefault(),Kn.value=null,xc(Pe).catch((ke)=>Br("delete-edge",ke));return}let ue=Ne.value.size>0?[...Ne.value]:je.value?[je.value]:[];if(ue.length===0)return;S.preventDefault();for(let Pe of ue)Oo(Pe).catch((ke)=>Br("delete",ke));Ut(),je.value=null}else if(je.value&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(S.key)){S.preventDefault();let ue=S.key.replace("Arrow","").toLowerCase();Yb(ue)}else if(!q&&!S.altKey){let ue=S.key.toLowerCase();if(ue==="v"&&!S.shiftKey)Qt.value="select";else if(ue==="c"&&!S.shiftKey&&!q)S.preventDefault(),Qt.value=Qt.value==="connect"?"select":"connect";else if(ue==="m"&&!S.shiftKey)S.preventDefault(),In({type:"markdown",title:"New note",width:520,height:360}).catch((Pe)=>Br("create markdown",Pe));else if(ue==="a"&&!S.shiftKey)S.preventDefault(),d((Pe)=>Pe==="pen"?null:"pen");else if(ue==="g"&&!S.shiftKey){S.preventDefault();let Pe=Array.from(Ne.value);if(Pe.length>=2)ii({title:"Group",childIds:Pe}).catch((ke)=>Br("group selection",ke)),Ut();else In({type:"group",title:"Group"}).catch((ke)=>Br("create group",ke))}else if(ue==="g"&&S.shiftKey){S.preventDefault();for(let Pe of Db())Do(Pe),si(Pe).catch((ke)=>Br("ungroup",ke));Ut()}else if(ue==="i"&&!S.shiftKey)S.preventDefault(),Dr("image");else if(ue==="w"&&!S.shiftKey)S.preventDefault(),Dr("webpage");else if(ue==="h"&&!S.shiftKey)S.preventDefault(),In({type:"html",title:"HTML surface"}).catch((Pe)=>Br("create html",Pe));else if(ue==="f"&&S.shiftKey)S.preventDefault(),Dr("file");else if(ue==="f"&&!S.shiftKey){S.preventDefault();let Pe=bt();pi(Pe.width,Pe.height)}}},J=(S)=>{if(S.key===" ")_s.value=!1},G=()=>{_s.value=!1};return document.addEventListener("keydown",W),document.addEventListener("keyup",J),window.addEventListener("blur",G),()=>{document.removeEventListener("keydown",W),document.removeEventListener("keyup",J),window.removeEventListener("blur",G)}},[p,g,r,l]),H(()=>{let W=window.setTimeout(()=>void bs(),250);return()=>window.clearTimeout(W)},[R]),H(()=>{if(!b)return;let W=window.__pmxCanvasBootstrapReady;if(typeof W==="function")W()},[b]);let z=Array.from(F.value.values()),X=bt();return i("div",{class:`app-shell${Fn.value?" is-presenting":""}`,"data-session-active":R?"true":"false",children:[i(tx,{},void 0,!1,void 0,this),i(ik,{minimapVisible:e,onToggleMinimap:M,snapshotOpen:n,onToggleSnapshot:_,snapshotBtnRef:m,onOpenPalette:()=>s(!0),onOpenShortcuts:()=>u((W)=>!W),annotationTool:p,onSetAnnotationTool:w},void 0,!1,void 0,this),i("div",{class:"app-main",children:[i(Fk,{},void 0,!1,void 0,this),i(VS,{},void 0,!1,void 0,this),i("div",{class:"canvas-region",ref:(W)=>Py(W),children:[i(qS,{onNodeContextMenu:h,onCanvasContextMenu:v,onEdgeContextMenu:x,annotationMode:p!==null,annotationTool:p},void 0,!1,void 0,this),i(_x,{},void 0,!1,void 0,this),i(wx,{},void 0,!1,void 0,this),i(gk,{},void 0,!1,void 0,this),i(vk,{},void 0,!1,void 0,this),I?i(mk,{},void 0,!1,void 0,this):b&&z.length===0&&lt.value.size===0&&i(sk,{onOpenPalette:()=>s(!0)},void 0,!1,void 0,this),Ne.value.size>0&&i(Ck,{},void 0,!1,void 0,this),R&&!Se()?i(GS,{},void 0,!1,void 0,this):Le.value.size>0&&i(ok,{},void 0,!1,void 0,this),i(Nk,{onOpenSnapshots:()=>o(!0)},void 0,!1,void 0,this),i(kx,{},void 0,!1,void 0,this),i(fk,{},void 0,!1,void 0,this),ot.value&&i(wk,{},void 0,!1,void 0,this),i($k,{open:n,onClose:N,anchorRef:m},void 0,!1,void 0,this),e&&!I&&i(Tk,{viewport:oe,nodes:F,edges:Je,onNavigate:k,containerWidth:X.width,containerHeight:X.height},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),R&&i(Ik,{},void 0,!1,void 0,this),f&&i(tk,{menu:f,onClose:g},void 0,!1,void 0,this),r&&i(YS,{onClose:()=>s(!1),onToggleMinimap:M},void 0,!1,void 0,this),a&&i(QS,{onClose:()=>c(!1)},void 0,!1,void 0,this),l&&i(zk,{onClose:()=>u(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}Nx();var t0=document.getElementById("app");if(t0)Qi(i(e0,{},void 0,!1,void 0,this),t0);
333
+ ${a.trim()}`},void 0,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",onClick:e,children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"submit",class:"text-prompt-confirm",disabled:!r.trim()||!a.trim(),children:["Continue on GitHub ",i(jo,{size:14},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,!1,void 0,this)}function oa(e,t){console.error(`[tool-rail] ${e} failed`,t)}function Dr(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"}};hn(t[e].message,t[e].placeholder).then((n)=>{if(!n)return;In({type:e,content:n}).catch((o)=>oa(`create ${e}`,o))})}function yt({label:e,shortcut:t,detail:n,ariaLabel:o,active:r,menuOpen:s,onClick:a,btnRef:c,children:l}){let[u,p]=A(null),d=(h)=>{let v=h.currentTarget.getBoundingClientRect();p({left:v.right+10,top:v.top+v.height/2})},m=()=>p(null),f=o??(t?`${e} (${t})`:n?`${e} (${n})`:e);return i(_e,{children:[i("button",{ref:c,type:"button",class:`rail-btn${r?" active":""}`,"aria-label":f,"aria-pressed":r===void 0?void 0:r,onClick:(h)=>{m(),a(h)},onPointerEnter:d,onPointerLeave:m,onFocus:d,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 ik({minimapVisible:e,onToggleMinimap:t,snapshotOpen:n,onToggleSnapshot:o,snapshotBtnRef:r,onOpenPalette:s,onOpenShortcuts:a,annotationTool:c,onSetAnnotationTool:l}){let u=Qt.value,p=li.value,d=Array.from(F.value.values()).filter((z)=>z.type==="trace").length,m=Je.value.size,[f,h]=A(!1),[v,x]=A(null),[g,b]=A(null),I=L(null),R=L(null),M=(z)=>(X)=>{if(v===z){x(null);return}let W=X.currentTarget.getBoundingClientRect();b({bottom:W.bottom,right:W.right}),x(z)},_=g?{position:"fixed",left:`${g.right+8}px`,bottom:`${window.innerHeight-g.bottom}px`,top:"auto",right:"auto"}:void 0;H(()=>{if(!v)return;let z=(W)=>{if(I.current&&W.target instanceof Node&&!I.current.contains(W.target))x(null)},X=(W)=>{if(W.key==="Escape")x(null)};return document.addEventListener("pointerdown",z),document.addEventListener("keydown",X),()=>{document.removeEventListener("pointerdown",z),document.removeEventListener("keydown",X)}},[v]);let N=(z)=>{Yl(),document.documentElement.setAttribute("data-theme",z),Ri(),gt.value=z,fc(z),x(null)},w=zp(gt.value),k=(z,X={})=>{ct(`/api/workbench/intent?_ts=${Date.now()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:z,payload:X})}).catch((W)=>oa("sendIntent",W))};return i(_e,{children:[i("div",{class:"tool-rail",ref:I,role:"toolbar","aria-label":"Canvas tools","aria-orientation":"vertical",children:[i(yt,{label:"Home",ariaLabel:"PMX Canvas — Home",onClick:()=>{x(null),sn(null).catch((z)=>oa("openHome",z))},children:i("span",{class:"rail-brand",children:i(Oc,{size:22},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Bug and feedback",menuOpen:f,onClick:()=>{x(null),h(!0)},children:i("svg",{width:"16",height:"16",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:"4.5",y:"5",width:"7",height:"9",rx:"3.5"},void 0,!1,void 0,this),i("path",{d:"M6 5V4a2 2 0 0 1 4 0v1M8 8v6M2 4l2.5 2M14 4l-2.5 2M1.5 9h3M11.5 9h3M2 14l2.5-2M14 14l-2.5-2"},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(yt,{label:"Select",shortcut:"V",active:u==="select",onClick:()=>Qt.value="select",children:i(bx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Pan",shortcut:"Space",active:u==="pan",onClick:()=>Qt.value="pan",children:i(xx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Connect",shortcut:"C",active:u==="connect",onClick:()=>Qt.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(yt,{label:"Markdown note",shortcut:"M",onClick:()=>void In({type:"markdown",title:"New note",width:520,height:360}).catch((z)=>oa("create markdown",z)),children:i(Ho,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Attach files",ariaLabel:"Attach files",detail:"Images (PNG, JPEG, SVG…), Markdown and text/code files. PDF, Word, Excel, PowerPoint and OpenDocument use agent import with review.",onClick:()=>R.current?.click(),children:i(ax,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("input",{ref:R,type:"file",hidden:!0,multiple:!0,"aria-label":"Attach files",onChange:(z)=>{let X=bt(),W=oe.value;$i(Array.from(z.currentTarget.files??[]),(X.width/2-W.x)/W.scale,(X.height/2-W.y)/W.scale),z.currentTarget.value=""}},void 0,!1,void 0,this),i(yt,{label:"Webpage",shortcut:"W",onClick:()=>Dr("webpage"),children:i(mi,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Group",shortcut:"G",onClick:()=>void In({type:"group",title:"Group"}).catch((z)=>oa("create group",z)),children:i(Vd,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Draw",shortcut:"A",active:c==="pen",onClick:()=>l(c==="pen"?null:"pen"),children:i(dx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Text note",active:c==="text",onClick:()=>l(c==="text"?null:"text"),children:i(mx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Eraser",active:c==="eraser",onClick:()=>l(c==="eraser"?null:"eraser"),children:i(px,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("div",{class:"rail-spacer"},void 0,!1,void 0,this),i(yt,{label:"Search & commands",shortcut:rt("K"),onClick:s,children:i(vx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Arrange",detail:m>0?"graph-aware":"grid",onClick:()=>m>0?Ac():Ec(),children:i(go,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),!Se()&&i(yt,{label:p?"Disable trace":"Enable trace",active:p,onClick:()=>k("trace-toggle",{enabled:!p}),children:i(hx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),!Se()&&(p||d>0)&&i(yt,{label:"Clear trace",onClick:()=>k("trace-clear"),children:i(gx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:e?"Hide minimap":"Show minimap",active:e,onClick:t,children:i(Rc,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(yt,{label:"Snapshots",active:n,onClick:o,btnRef:r,children:i(fx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"toolbar-menu-anchor",children:[i(yt,{label:"Theme",detail:Ci[w].label,menuOpen:v==="theme",ariaLabel:"Choose theme",active:v==="theme",onClick:M("theme"),children:Go(w)==="dark"?i(ux,{},void 0,!1,void 0,this):i(Mc,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),v==="theme"&&i("div",{class:"toolbar-menu",style:_,role:"menu","aria-label":"Theme",children:Np.map((z)=>i("button",{type:"button",role:"menuitemradio","aria-checked":w===z,class:`toolbar-menu-item${w===z?" active":""}`,onClick:()=>N(z),children:[i("span",{class:"theme-swatch",style:{background:Ci[z].swatchBg},children:i("span",{class:"theme-swatch-dot",style:{background:Ci[z].swatchAccent}},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{children:Ci[z].label},void 0,!1,void 0,this),w===z&&i("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},z,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(yt,{label:"Shortcuts",shortcut:"?",onClick:a,children:i(yx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),f&&i(rk,{onClose:()=>h(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sk({onOpenPalette:e}){let t=L(null),n=()=>{In({type:"markdown",title:"New note",width:520,height:360}).catch(()=>{})},o=async(r)=>{if(!r||r.length===0)return;let s=Ro(),a=oe.value;await $i(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(Ho,{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:()=>Dr("webpage"),children:[i(mi,{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:rt("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 tr(),children:[i(fi,{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 · ",rt("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)}var ak="From old snapshots";function ck(e){if(!e?.trim())return null;let t=e.split("/").map((n)=>n.trim());if(t.length>8)throw Error("Folders can be nested up to 8 levels.");if(t.some((n)=>!n||n==="."||n===".."||n.length>60))throw Error('Each folder name must be 1–60 characters, and cannot be "." or "..".');return t.join("/")}function Dm(e){return e.split("/").map((t,n,o)=>o.slice(0,n+1).join("/"))}function lk({board:e,folders:t,onClose:n}){let o=L(null),[r,s]=A(e.category??""),[a,c]=A(""),[l,u]=A(!1),[p,d]=A("");an(o,!0),H(()=>{let h=(v)=>{if(v.key!=="Escape")return;if(v.preventDefault(),v.stopPropagation(),!l)n()};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[l,n]);let m=a.trim()?[r,a.trim()].filter(Boolean).join("/"):r,f=async()=>{let h;try{if(a.includes("/"))throw Error("Use one folder name; choose its parent above.");h=ck(m)}catch(v){d(v instanceof Error?v.message:String(v));return}if(u(!0),d(""),await uc(e.id,{category:h}),rn.value.find((v)=>v.id===e.id)?.category===h)n();else d("Could not move this board. Try again.");u(!1)};return i("div",{class:"text-prompt-backdrop",onPointerDown:()=>!l&&n(),children:i("div",{ref:o,class:"text-prompt home-folder-dialog",role:"dialog","aria-modal":"true","aria-label":`Move ${e.name}`,onPointerDown:(h)=>h.stopPropagation(),children:[i("div",{class:"text-prompt-title",children:["Move “",e.name,"”"]},void 0,!0,void 0,this),i("p",{class:"home-folder-hint",children:"Choose a folder, or create one inside it. The board keeps its content and links."},void 0,!1,void 0,this),i("fieldset",{class:"home-folder-options",disabled:l,children:[i("legend",{children:"Destination folder"},void 0,!1,void 0,this),["",...t].map((h)=>i("label",{class:"home-folder-option",style:{paddingLeft:`${8+Math.min(h.split("/").length-1,5)*14}px`},children:[i("input",{type:"radio",name:"folder-destination",value:h,checked:r===h,onChange:()=>{s(h),d("")}},void 0,!1,void 0,this),i("span",{children:h||"Home (no folder)"},void 0,!1,void 0,this)]},h,!0,void 0,this))]},void 0,!0,void 0,this),i("label",{class:"home-folder-new",children:["New folder inside ",r||"Home"," ",i("span",{class:"home-folder-hint",children:"(optional)"},void 0,!1,void 0,this),i("input",{class:"text-prompt-input","aria-label":"New folder name",placeholder:"e.g. Decisions",maxLength:60,value:a,disabled:l,onInput:(h)=>{c(h.currentTarget.value),d("")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"home-folder-hint",children:["Move to: ",i("strong",{children:m||"Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),p&&i("p",{role:"alert",children:p},void 0,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",disabled:l,onClick:n,children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"button",class:"text-prompt-confirm",disabled:l||m===(e.category??""),onClick:()=>void f(),children:l?"Moving…":"Move board"},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 uk({board:e,onClose:t}){let n=L(null),o=L(null),[r,s]=A(null),[a,c]=A(new Set),[l,u]=A(`${e.name} copy`),[p,d]=A(!0),[m,f]=A(!0),[h,v]=A(!1),[x,g]=A(""),[b,I]=A(!1);return an(n,!0,{initial:o}),H(()=>{let M=!0;return cb(e.id).then((_)=>{if(!M)return;if(!_||!Array.isArray(_.cards))return g("Could not load reusable cards. Try again.");s(_),c(new Set(_.cards.filter((N)=>N.reusable).map((N)=>N.id)))}),()=>{M=!1}},[e.id]),i("div",{class:"text-prompt-backdrop",onMouseDown:t,children:i("div",{ref:n,class:"text-prompt board-copy-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-copy-title",onMouseDown:(M)=>M.stopPropagation(),children:i("form",{onSubmit:async(M)=>{if(M.preventDefault(),!l.trim()||!r)return;I(!0),g("");let _=await lb({sourceBoardId:e.id,name:l.trim(),...e.category?{category:e.category}:{},nodeIds:[...a],includeReadme:p,includeStructure:m});if(I(!1),!_)return g("Could not create the board. Try a different name.");if(h)await sn(_.id);t()},children:[i("h2",{id:"board-copy-title",children:["Create from ",e.name]},void 0,!0,void 0,this),i("label",{class:"board-copy-field",children:["Board name",i("input",{ref:o,class:"text-prompt-input",value:l,onInput:(M)=>u(M.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!r&&!x&&i("div",{class:"board-copy-status",role:"status",children:"Loading reusable cards…"},void 0,!1,void 0,this),x&&i("div",{class:"board-copy-error",role:"alert",children:x},void 0,!1,void 0,this),r&&i("fieldset",{class:"board-copy-cards",children:[i("legend",{children:"Cards to copy"},void 0,!1,void 0,this),r.cards.filter((M)=>M.reusable).length===0?i("div",{class:"board-copy-status",children:"No reusable cards on this board."},void 0,!1,void 0,this):r.cards.filter((M)=>M.reusable).map((M)=>i("label",{class:"board-copy-card",children:[i("input",{type:"checkbox",checked:a.has(M.id),onChange:(_)=>{let N=new Set(a);_.currentTarget.checked?N.add(M.id):N.delete(M.id),c(N)}},void 0,!1,void 0,this),i("span",{children:[i("strong",{children:M.title||"Untitled card"},void 0,!1,void 0,this),i("small",{children:M.type},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},M.id,!0,void 0,this))]},void 0,!0,void 0,this),i("div",{class:"board-copy-options",children:[i("label",{children:[i("input",{type:"checkbox",checked:m,onChange:(M)=>f(M.currentTarget.checked)},void 0,!1,void 0,this)," ","Preserve groups and connections"]},void 0,!0,void 0,this),i("label",{children:[i("input",{type:"checkbox",checked:p,disabled:!r?.readmeNodeId,onChange:(M)=>d(M.currentTarget.checked)},void 0,!1,void 0,this)," ","Include README"]},void 0,!0,void 0,this),i("label",{children:[i("input",{type:"checkbox",checked:h,onChange:(M)=>v(M.currentTarget.checked)},void 0,!1,void 0,this)," Open the new board after creating"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("p",{class:"board-copy-note",children:"Only selected cards and structure are copied. Asks, history, and context pins start clear."},void 0,!1,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",onClick:t,children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"submit",disabled:!r||!l.trim()||b,children:b?"Creating…":"Create board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function HN(e){if(!e)return"never opened";let t=Math.floor((Date.now()-new Date(e).getTime())/60000);if(t<1)return"just now";if(t<60)return`${t}m ago`;let n=Math.floor(t/60);if(n<24)return`${n}h ago`;let o=Math.floor(n/24);if(o<30)return`${o}d ago`;return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function dk(e){return`${e} node${e!==1?"s":""}`}async function Fm(){let e=await hn("New board","Board name",{confirm:"Create"});if(e)await ab(e)}var pk="pmx-canvas-home-collapsed";function jN(){try{let e=localStorage.getItem(pk);if(e)return new Set(JSON.parse(e))}catch{}return new Set([ak])}function UN(e){try{localStorage.setItem(pk,JSON.stringify([...e]))}catch{}}function mk(){let e=rn.value,[t,n]=A(null),[o,r]=A(null),[s,a]=A(null),[c,l]=A(""),[u,p]=A([]),[d,m]=A(jN),f=L(0),h=[...new Set(e.flatMap((k)=>k.category?Dm(k.category):[]))].sort((k,z)=>k.localeCompare(z)),v=c.trim().toLocaleLowerCase(),x=e.filter((k)=>`${k.name} ${k.category??""}`.toLocaleLowerCase().includes(v)),g=new Set(x.flatMap((k)=>k.category?Dm(k.category):[])),b=e.find((k)=>k.id===o),I=e.find((k)=>k.id===s);H(()=>{let k=c.trim();if(!k){p([]);return}let z=!1,X=window.setTimeout(()=>{ne("searchLibrary",`/api/canvas/search?q=${encodeURIComponent(k)}&scope=library&limit=30`,null).then((W)=>{if(!z)p(W?.results??[])})},150);return()=>{z=!0,window.clearTimeout(X)}},[c]);let R=async(k)=>{let z=++f.current;await sn(k.boardId);for(let X=0;X<40;X++){if(z!==f.current||Oe.value!==k.boardId)return;if(F.value.has(k.cardId)){pt(k.cardId);return}await new Promise((W)=>window.setTimeout(W,25))}},M=(k)=>{let z=new Set(d);if(z.has(k))z.delete(k);else z.add(k);m(z),UN(z)},_=async(k)=>{let z=await hn("Rename board","Board name",{initial:k.name,confirm:"Rename"});if(z&&z!==k.name)await uc(k.id,{name:z})},N=(k)=>t===k.id?i("li",{class:"home-board is-confirming","data-testid":"home-board",children:[i("div",{class:"home-board-confirm-text",children:["Delete ",i("strong",{children:k.name},void 0,!1,void 0,this)," and its ",dk(k.nodeCount)," and snapshots? This can't be undone."]},void 0,!0,void 0,this),i("div",{class:"home-board-actions",children:[i("button",{type:"button",class:"home-board-action",onClick:()=>n(null),children:"Cancel"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action is-danger",onClick:()=>{n(null),db(k.id)},children:"Delete board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k.id,!0,void 0,this):i("li",{class:"home-board","data-testid":"home-board",children:[i("button",{type:"button",class:"home-board-open",onClick:()=>void sn(k.id),children:[i("span",{class:"home-board-name",children:k.name},void 0,!1,void 0,this),i("span",{class:"home-board-meta",children:[dk(k.nodeCount)," · ",HN(k.lastOpenedAt)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"home-board-actions",children:[i("button",{type:"button",class:"home-board-action","aria-haspopup":"dialog",onClick:()=>r(k.id),children:"Move"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action","aria-haspopup":"dialog",onClick:()=>a(k.id),children:"Create from…"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action",onClick:()=>void _(k),children:"Rename"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-board-action",onClick:()=>n(k.id),children:"Delete"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k.id,!0,void 0,this),w=(k,z)=>{let X=h.filter((S)=>S.slice(0,S.lastIndexOf("/"))===k&&S.includes("/")),W=x.filter((S)=>S.category===k),J=x.filter((S)=>S.category===k||S.category?.startsWith(`${k}/`)).length,G=!!v||!d.has(k);return i("section",{class:"home-section","data-testid":"home-section","data-folder":k,"aria-label":k,children:[i("button",{type:"button",class:"home-section-head","aria-expanded":G,onClick:()=>M(k),children:[i("svg",{class:"home-section-chevron",viewBox:"0 0 20 20",width:"18",height:"18",fill:"none","aria-hidden":"true",children:i("path",{d:"m7.5 4.75 5.25 5.25-5.25 5.25"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("svg",{class:"home-section-folder",viewBox:"0 0 20 20",width:"18",height:"18",fill:"none","aria-hidden":"true",children:i("path",{d:"M2.75 5.75A1.75 1.75 0 0 1 4.5 4h3l1.75 2h6.25a1.75 1.75 0 0 1 1.75 1.75v6.5A1.75 1.75 0 0 1 15.5 16h-11a1.75 1.75 0 0 1-1.75-1.75v-8.5Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"home-section-name",children:k.split("/").at(-1)},void 0,!1,void 0,this),i("span",{class:"home-section-count",children:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G&&i("div",{class:"home-folder-children",style:{marginLeft:z<5?"14px":"0"},children:[X.filter((S)=>g.has(S)).map((S)=>w(S,z+1)),W.length>0&&i("ul",{class:"home-view-list","aria-label":`Boards in ${k}`,children:W.map(N)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k,!0,void 0,this)};return i("div",{class:"home-view","data-testid":"home-view",children:[i("div",{class:"home-view-inner",children:[i("div",{class:"home-view-head",children:[i("h1",{class:"home-view-title",children:"Boards"},void 0,!1,void 0,this),i("button",{type:"button",class:"home-view-new",onClick:()=>void Fm(),children:"New board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("input",{class:"text-prompt-input home-search",type:"search","aria-label":"Find boards and folders",placeholder:"Find boards and folders…",value:c,onInput:(k)=>l(k.currentTarget.value)},void 0,!1,void 0,this),e.length===0?i("div",{class:"home-view-empty",children:"No boards yet. Create one, or let an agent start writing — it opens one."},void 0,!1,void 0,this):v&&u.length>0?i("ul",{class:"home-view-list","aria-label":"Library search results",children:u.map((k)=>i("li",{class:"home-board",children:i("button",{type:"button",class:"home-board-open",onClick:()=>void R(k),children:[i("span",{class:"home-board-name",children:k.title||k.boardTitle},void 0,!1,void 0,this),i("span",{class:"home-board-meta",children:[k.boardTitle," · ",k.snippet]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},`${k.boardId}:${k.cardId}`,!1,void 0,this))},void 0,!1,void 0,this):x.length===0?i("div",{class:"home-view-empty",role:"status",children:["No boards match “",c,"”."]},void 0,!0,void 0,this):i(_e,{children:[h.filter((k)=>!k.includes("/")&&g.has(k)).map((k)=>w(k,0)),x.some((k)=>!k.category)&&i("section",{"aria-label":"Unfiled boards",children:[h.length>0&&i("div",{class:"home-folder-hint",children:"Unfiled boards"},void 0,!1,void 0,this),i("ul",{class:"home-view-list",children:x.filter((k)=>!k.category).map(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),b&&i(lk,{board:b,folders:h,onClose:()=>r(null)},b.id,!1,void 0,this),I&&i(uk,{board:I,onClose:()=>a(null)},I.id,!1,void 0,this)]},void 0,!0,void 0,this)}var Ui=K(!1);function ZN(e){return e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}function fk(){let[e,t]=A(!1),[n,o]=A(!1),[r,s]=A(null),[a,c]=A(null),[l,u]=A(!1),[p,d]=A(""),m=Ui.value,f=Oe.value;if(H(()=>{if(!m||!f)return;let v=!0;return c(null),d(""),s(null),ne("exportPreview",`/api/canvas/export/preview?board=${encodeURIComponent(f)}&includeFiles=${e}&includeDerivedText=${n}`,null).then((x)=>{if(v)s(x?.manifest??null)}),()=>{v=!1}},[m,e,n,f]),H(()=>{o(!1)},[m,f]),H(()=>{if(!m)return;let v=(x)=>{if(x.key!=="Escape")return;x.stopPropagation(),Ui.value=!1};return window.addEventListener("keydown",v,{capture:!0}),()=>window.removeEventListener("keydown",v,{capture:!0})},[m]),!m)return null;let h=async()=>{if(!r||r.boardId!==Oe.value)return;u(!0);let v=await ne("exportBoard","/api/canvas/export",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({board:r.boardId,includeFiles:e,includeDerivedText:n})});if(u(!1),v?.path&&Oe.value===r.boardId)c(v)};return i("div",{class:"text-prompt-backdrop",onPointerDown:()=>Ui.value=!1,children:i("div",{class:"text-prompt export-dialog",role:"dialog","aria-label":"Export board","data-testid":"export-dialog",onPointerDown:(v)=>v.stopPropagation(),children:[i("div",{class:"text-prompt-title",children:["Export ",r?`“${r.boardName}”`:"board"]},void 0,!0,void 0,this),!r?i("div",{class:"export-dialog-note",children:"Reading the board…"},void 0,!1,void 0,this):i(_e,{children:[i("div",{class:"export-dialog-note",children:"One HTML file anyone can open without installing anything. It will contain:"},void 0,!1,void 0,this),i("ul",{class:"export-dialog-list",children:[i("li",{children:[r.cards," card",r.cards!==1?"s":""," and ",r.connections," connection",r.connections!==1?"s":""]},void 0,!0,void 0,this),r.frames>0&&i("li",{children:[r.frames," embedded pages, charts or diagrams, with the code that draws them"]},void 0,!0,void 0,this),r.embeddedImages>0&&i("li",{children:[r.embeddedImages," local images"]},void 0,!0,void 0,this),r.placeholders.length>0&&i("li",{children:["Shown as placeholders:"," ",r.placeholders.map((v)=>`${v.title} (${v.reason})`).join(", ")]},void 0,!0,void 0,this),r.remoteImages.length>0&&i("li",{children:["Web images loaded when opened: ",r.remoteImages.join(", ")]},void 0,!0,void 0,this),r.links.length>0&&i("li",{children:["Links included in cards: ",r.links.join(", ")]},void 0,!0,void 0,this),r.frameNetworkDestinations.length>0&&i("li",{children:["Network destinations referenced by embedded pages: ",r.frameNetworkDestinations.join(", ")]},void 0,!0,void 0,this),r.embeddedCodeCanAccessNetwork&&i("li",{children:"Warning: embedded code can access the network. Scripts may contact destinations that cannot be listed in advance."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(r.attachments?.length??0)>0&&i("p",{children:"Original attachments are excluded. Their filenames remain visible."},void 0,!1,void 0,this),(r.sourceDerivedCards?.length??0)>0&&i("label",{class:"export-dialog-files",children:[i("input",{type:"checkbox",checked:n,onChange:(v)=>o(v.currentTarget.checked)},void 0,!1,void 0,this),i("span",{children:["Include imported document text (",r.sourceDerivedCards.length," cards)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r.files.length>0&&i("label",{class:"export-dialog-files",children:[i("input",{type:"checkbox",checked:e,onChange:(v)=>t(v.target.checked)},void 0,!1,void 0,this),i("span",{children:["Include the contents of ",r.files.length," local file",r.files.length!==1?"s":"",": ",r.files.map((v)=>v.path).join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&i("div",{class:"export-dialog-result","data-testid":"export-result",children:[i("div",{children:["Saved (",ZN(a.bytes),"): ",i("code",{children:a.path},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"export-dialog-links",children:Se()?i("button",{type:"button",disabled:l,onClick:async()=>{u(!0),d("");try{await ob(a.url)}catch(v){d(v instanceof Error?v.message:"Download failed. Try again.")}finally{u(!1)}},children:l?"Downloading…":"Download"},void 0,!1,void 0,this):i(_e,{children:[i("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:"Open"},void 0,!1,void 0,this),i("a",{class:"is-primary",href:`${a.url}?download=1`,children:"Download"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Se()&&i("p",{children:"Download the HTML file to open it outside ChatGPT."},void 0,!1,void 0,this),p&&i("p",{role:"alert",children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"text-prompt-actions",children:[i("button",{type:"button",class:"text-prompt-cancel",onClick:()=>Ui.value=!1,children:a?"Done":"Cancel"},void 0,!1,void 0,this),!a&&i("button",{type:"button",class:"text-prompt-confirm",disabled:!r||l,onClick:()=>void h(),children:l?"Exporting…":"Export"},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 Bm({presence:e,size:t=18}){return i("span",{class:"writer-avatar",style:{background:An(e.sessionId),width:`${t}px`,height:`${t}px`},"aria-hidden":"true",children:eS(e.label)},void 0,!1,void 0,this)}function hk(){let e=ym.value;if(_t.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=Rr.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:()=>{Rr.value=!o},children:[i("span",{class:"external-indicator-avatars",children:e.slice(0,3).map((r)=>i(Bm,{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 WN(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 qN(e){return e.reduce((t,n)=>n.lastSeenAt>t?n.lastSeenAt:t,"")}function GN(){return[...lt.value.values()].filter((e)=>!e.auto&&e.phase==="forming")}function gk(){let e=Rr.value,t=ym.value,n=xo(e?1e4:0);if(H(()=>{if(!e)return;let c=(l)=>{if(l.key!=="Escape")return;if(Oi.value)Oi.value=!1;else Rr.value=!1};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e]),!e||_t.value||t.length===0)return null;let o=vm.value,r=GN().filter((c)=>!o||(c.source??"")===o),s=Yo.value.filter((c)=>!o||c.sessionId===o),a=(c,l)=>i("button",{type:"button",class:`activity-filter${o===c?" is-active":""}`,style:c?{"--writer":An(c)}:void 0,"aria-pressed":o===c,onClick:()=>{vm.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"," ",Ol(qN(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:()=>{Rr.value=!1},children:i(Ve,{},void 0,!1,void 0,this)},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:()=>{br(c).then((l)=>{if(l)Er(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}=WN(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:An(c.sessionId)},children:c.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"activity-age",children:Ol(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:()=>{Oi.value=!0},children:"Writers"},void 0,!1,void 0,this),i("button",{type:"button",class:"activity-feed-link is-accent",onClick:()=>{Rr.value=!1,tr()},children:["Start session ",i(jo,{size:14},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 VN(){let e=[];if(Qo.value)e.push("scoped");if(Mr.value.length>0)e.push("gated");return e.length>0?e.join(" + "):"open"}function vk(){let e=Oi.value,t=xo(e?1e4:0),n=L(null);if(an(n,e),!e)return null;let o=It.value.filter((a)=>a.attached),r=It.value.filter((a)=>!a.attached),s=()=>{Oi.value=!1};return i(_e,{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:lo.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:i(Ve,{},void 0,!1,void 0,this)},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(Bm,{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:VN()},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(Bm,{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"," ",Ol(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 yk(e,t){switch(e.type){case"markdown":return i(Vc,{node:e,expanded:t},void 0,!1,void 0,this);case"mcp-app":return i(Ko,{node:e,expanded:t},void 0,!1,void 0,this);case"webpage":return i(Nl,{node:e,expanded:t},void 0,!1,void 0,this);case"json-render":return i(Ko,{node:e,expanded:t},void 0,!1,void 0,this);case"graph":return i(Ko,{node:e,expanded:t},void 0,!1,void 0,this);case"board":return i(Gl,{node:e},void 0,!1,void 0,this);case"prompt":return i(zl,{node:e},void 0,!1,void 0,this);case"response":return i(Rl,{node:e,expanded:t},void 0,!1,void 0,this);case"status":return i(Il,{node:e},void 0,!1,void 0,this);case"context":return i(Lc,{node:e,expanded:t},void 0,!1,void 0,this);case"ledger":return i(Hc,{node:e},void 0,!1,void 0,this);case"trace":return i(Ml,{node:e},void 0,!1,void 0,this);case"file":return i(Bc,{node:e,expanded:t},void 0,!1,void 0,this);case"diff":return i(Dc,{node:e},void 0,!1,void 0,this);case"mermaid":return i(ll,{node:e,expanded:t},void 0,!1,void 0,this);case"image":return i(Pl,{node:e,expanded:t},void 0,!1,void 0,this);case"html":return i(Ks,{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 bk(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 XN(e){if(!e)return 0;return e.split(/\s+/).filter(Boolean).length}function KN(e,t){return e!==null&&typeof e==="object"&&e.source===Tn&&e.type==="presentation-exit"&&e.token===t}function JN(e){return e==="ArrowRight"||e==="PageDown"||e===" "||e==="ArrowLeft"||e==="PageUp"||e==="Home"||e==="End"}function xk(e){return e instanceof HTMLElement&&Boolean(e.closest(".html-presentation-exit"))}function wk(){let e=ot.value,t=e?F.value.get(e):void 0,[n,o]=A(!1),[r,s]=A(!1),[a,c]=A(""),l=L(null),u=L(null),p=j(()=>{s(!1),ho()},[]),d=j(()=>{c(`presentation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`),s(!0)},[]),m=j((S)=>{document.querySelector(".html-presentation-overlay iframe.html-node-frame-presentation")?.contentWindow?.postMessage({source:Tn,token:a,...S},"*")},[a]),f=j(()=>{s(!1)},[]),h=j((S)=>{if(S.key==="Escape"){S.preventDefault(),S.stopPropagation(),s(!1);return}if(S.key==="Tab"&&!xk(S.target)){S.preventDefault(),S.stopPropagation(),u.current?.focus();return}if((S.key===" "||S.key==="Enter")&&xk(S.target))return;if(!JN(S.key))return;S.preventDefault(),S.stopPropagation(),m({type:"presentation-key",key:S.key})},[m]),v=j((S)=>{if(S.target.classList.contains("expanded-overlay-backdrop"))ho()},[]),x=j(()=>{if(!t)return;let S=bk(t);if(!S)return;navigator.clipboard.writeText(S).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},[t]),g=j(()=>{if(!e)return;Jn(e)},[e]);H(()=>{s(!1)},[e]),_n(()=>{if(!r)return;let S=()=>{let ye=l.current;if(!ye||ye.contains(document.activeElement))return;ye.focus()},q=[0,50,150].map((ye)=>window.setTimeout(S,ye)),ie=(ye)=>{if(!KN(ye.data,a))return;s(!1)};return document.addEventListener("keydown",h,!0),window.addEventListener("message",ie),()=>{q.forEach((ye)=>{window.clearTimeout(ye)}),document.removeEventListener("keydown",h,!0),window.removeEventListener("message",ie)}},[h,a,r]);let b=L(null),I=j(()=>e?document.querySelector(`.canvas-node[data-node-id="${CSS.escape(e)}"]`):null,[e]);if(an(b,t!==void 0,{restoreTo:I}),!t)return null;let R=t.data.title||t.data.path?.split("/").pop()||Nt[t.type],M=bk(t),_=XN(M),N=e?Le.value.has(e):!1,w=M.length>0,k=Ln.value===e,z=t.type==="mcp-app"||t.type==="webpage"||t.type==="json-render"||t.type==="graph",X=F_(t),W=Bn(t.type),J=t.data.provenance&&typeof t.data.provenance==="object"?t.data.provenance:null,G=J?[J.sourceKind,J.sourceUri,J.syncedAt?`synced ${J.syncedAt.slice(11,16)}`:null].filter((S)=>typeof S==="string"&&S.length>0).join(" · "):null;return i("div",{class:"expanded-overlay-backdrop",onPointerDown:v,style:{pointerEvents:k?"none":"auto"},children:i("div",{ref:b,class:`expanded-overlay-panel${N?" is-pinned":""}`,role:"dialog","aria-modal":"true","aria-label":R,"data-testid":"expanded-node",children:[i("div",{class:"expanded-header",children:[i("span",{class:"expanded-kind-icon","aria-hidden":"true",children:i(W,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"expanded-title",children:R},void 0,!1,void 0,this),i("span",{class:"expanded-kind-pill",children:Nt[t.type]},void 0,!1,void 0,this),i("button",{type:"button",class:`expanded-pin${N?" is-on":""}`,onClick:g,title:N?"In agent context — click to unpin":"Pin as agent context","aria-pressed":N,children:"✦"},void 0,!1,void 0,this),i("span",{class:"expanded-spacer"},void 0,!1,void 0,this),i("div",{class:"expanded-actions",children:[w&&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),Yc(t)&&i("button",{type:"button",class:"expanded-action-btn",onClick:()=>void Qc(t),title:"Open as a full-page site in the system browser",children:["Open in tab ",i(jo,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&i("button",{type:"button",class:"expanded-action-btn expanded-action-primary",onClick:d,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:p,title:"Close (Esc)","aria-label":"Close",children:i(Ve,{},void 0,!1,void 0,this)},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:yk(t,!0)},void 0,!1,void 0,this):yk(t,!0)},void 0,!1,void 0,this),i("div",{style:{"--ax-dock-bleed":"0px","--ax-dock-pad":"16px"},children:i(ql,{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:[G,_>0?`${_.toLocaleString()} word${_!==1?"s":""}`:null].filter(Boolean).join(" · ")||Nt[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${k?" is-saving":""}`,children:k?"Saving edits…":"esc or click outside to close"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&r&&i("div",{ref:l,class:"html-presentation-overlay",role:"dialog","aria-modal":"true","aria-label":`Present ${R}`,tabIndex:-1,onKeyDownCapture:h,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(Ks,{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 Sk=168,kk=112,eu=20;function _k(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,p=-t.y/t.scale,d=u+n/t.scale,m=p+o/t.scale,f={minX:Math.min(s,u)-eu,minY:Math.min(a,p)-eu,maxX:Math.max(c,d)+eu,maxY:Math.max(l,m)+eu},h=f.maxX-f.minX||1,v=f.maxY-f.minY||1;return{bounds:f,scale:Math.min(Sk/h,kk/v)}}function Tk({viewport:e,nodes:t,onNavigate:n,containerWidth:o,containerHeight:r}){let s=L(null),a=L(!1),c=t.value,l=e.value,u=_k(c,l,o,r),{bounds:p,scale:d}=u,m=(w)=>(w-p.minX)*d,f=(w)=>(w-p.minY)*d,h=j((w)=>{let k=s.current;if(!k)return;let z=k.getBoundingClientRect(),X=(w.clientX-z.left)/z.width*Sk,W=(w.clientY-z.top)/z.height*kk,J=_k(t.value,e.value,o,r),G=e.value,S=o/G.scale,q=r/G.scale,ie=X/J.scale+J.bounds.minX,ye=W/J.scale+J.bounds.minY;n(-(ie-S/2)*G.scale,-(ye-q/2)*G.scale)},[t,e,o,r,n]),v=j((w)=>{w.stopPropagation(),w.preventDefault(),a.current=!0,h(w);let k=(X)=>{if(a.current)h(X)},z=()=>{a.current=!1,document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",z)};document.addEventListener("pointermove",k),document.addEventListener("pointerup",z)},[h]),x=Ne.value,g=Le.value,b=_t.value?Ll.value:new Set,I=Qo.value,R=I?Fl(I.nodeIds.map((w)=>c.get(w)).filter((w)=>w!==void 0),I.padding):null,M=It.value.map((w)=>({id:w.sessionId,phase:w.phase,worker:w.parentAgentId!=null,external:!w.attached,at:Dl(w,(k)=>c.get(k))})).filter((w)=>w.at!==null),_=-l.x/l.scale,N=-l.y/l.scale;return i("div",{ref:s,class:"minimap","data-testid":"minimap",title:"Click to jump · drag the frame to pan",onPointerDown:v,children:[Array.from(c.values()).map((w)=>{let k=w.type==="group";return i("span",{class:`minimap-node${k?" is-group":""}${x.has(w.id)?" is-selected":""}${g.has(w.id)?" is-pinned":""}${b.has(w.id)?" is-agent":""}`,"data-kind":w.type,style:{left:`${m(w.position.x)}px`,top:`${f(w.position.y)}px`,width:`${Math.max(k?6:4,w.size.width*d)}px`,height:`${Math.max(k?5:3,w.size.height*d)}px`}},w.id,!1,void 0,this)}),R&&i("span",{class:"minimap-fence",style:{left:`${m(R.x)}px`,top:`${f(R.y)}px`,width:`${R.width*d}px`,height:`${R.height*d}px`}},void 0,!1,void 0,this),M.map((w)=>i("span",{class:`minimap-presence phase-${w.phase}${w.worker?" is-worker":""}${w.external?" is-external":""}`,style:{left:`${m(w.at.x)-4}px`,top:`${f(w.at.y)-4}px`,"--identity-color":An(w.id)}},w.id,!1,void 0,this)),i("span",{class:"minimap-frame",style:{left:`${m(_)}px`,top:`${f(N)}px`,width:`${o/l.scale*d}px`,height:`${r/l.scale*d}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 Ck(){let e=Ne.value.size,t=j(()=>{let c=Array.from(Ne.value);if(c.length===0)return;Sc(c),Ut()},[]),n=j(()=>{let c=Array.from(Ne.value);if(c.length===0)return;ii({title:"Group",childIds:c}),Ut()},[]),o=j(()=>{let c=Array.from(Ne.value);for(let l=0;l<c.length;l++)for(let u=l+1;u<c.length;u++)xr(c[l],c[u],"relation");Ut()},[]),r=j(()=>{let c=Array.from(Ne.value);for(let l of c)Oo(l);Ut()},[]);if(e===0)return null;let s=e>=2,a=!_t.value&&Le.value.size>0&&!Gn.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(_e,{children:[i("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),i(Qe,{label:"Align left",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align left",onClick:()=>Bd("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(Qe,{label:"Align top",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Align top",onClick:()=>Bd("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(Qe,{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:()=>Fb(),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(Qe,{label:"Auto-arrange selection",side:"up",children:i("button",{type:"button",class:"selection-bar-icon","aria-label":"Auto-arrange",onClick:()=>Bb(),children:i(go,{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(Qe,{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(Qe,{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(Qe,{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(Qe,{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(Qe,{label:"Clear selection",shortcut:"Esc",side:"up",children:i("button",{type:"button",class:"selection-bar-icon",onClick:Ut,"aria-label":"Clear selection",children:i(Ve,{size:14},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 tu(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 nu(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 YN={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"vetoed"},QN={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"cancelled"},Ek=[{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"}],Ak=Object.fromEntries(Ek.map((e)=>[e.id,e.hint])),ez={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 Hm(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 tz({item:e}){let t=YN[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&&pt(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:QN[e.status]??t},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:Hm(e.updatedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nz({gate:e,now:t}){let[n,o]=A(null),r=async(c)=>{o(c),await pS(e,c),o(null)},s=e.nodeIds[0],a=tu(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&&pt(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 ",nu(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:Hm(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oz({gate:e}){let[t,n]=A(!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),mS(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 rz(e){let t=e.resolvedBy;if(!t)return e.status;let n=e.status==="approved"?"Approved":"Rejected";if(t.actor==="human")return`${n} by you`;if(t.actor==="system")return`${n} by system`;let o=t.agentId||t.source||"agent";return`${e.selfAnswer?"Self-":""}${n.toLowerCase()} by ${o}`}function iz({gate:e}){return i("li",{class:`session-item status-${e.status}`,"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:rz(e)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function sz(){let e=Qo.value,t=Ne.value.size,[n,o]=A(!1),r=(s)=>{o(!0),sS(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(_e,{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(_e,{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([...Ne.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 az(e){if(e==="browser")return"you";return It.value.find((n)=>n.sessionId===e||n.source===e)?.label??e}function cz({entry:e}){let t=ea.value.has(e.id);return i("li",{class:`session-timeline-row tone-${ez[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:Ak[Sm(e.kind)],children:e.label},void 0,!1,void 0,this),e.who&&i("span",{class:"session-timeline-who",style:{"--identity-color":An(e.who)},children:az(e.who)},void 0,!1,void 0,this),i("span",{class:"session-item-time",children:Hm(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 km(e),children:[i(Gd,{size:14},void 0,!1,void 0,this)," undo this edit"]},void 0,!0,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 Ik(){let[e,t]=A(!1),n=Li.value,o=iS.value,r=Mr.value,s=aS.value,a=cS.value,c=dS.value,[l,u]=A(!1),[p,d]=A(null),m=xo();if(H(()=>{er()},[]),!(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:Jo(n),"aria-label":`Session live: ${Jo(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:Jo(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 Bl(n),children:"End"},void 0,!1,void 0,this),i("button",{type:"button",class:"session-collapse",onClick:()=>t(!1),title:"Collapse session panel","aria-label":"Collapse session panel",children:i(ks,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i(sz,{},void 0,!1,void 0,this),(()=>{let h=c.find((v)=>v.undoable&&!ea.value.has(v.id));if(!h)return null;return i("div",{class:"session-undo-row","data-testid":"session-undo-row",children:[i("span",{class:"session-undo-text",title:h.body,children:["Agent edit on top: ",h.body]},void 0,!0,void 0,this),i("button",{type:"button",class:"session-undo-btn",onClick:()=>void km(h),children:[i(Gd,{size:14},void 0,!1,void 0,this)," Undo"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)})(),i("div",{class:"session-panel-body",children:[i("section",{class:"session-section",children:(()=>{let h=o.filter((M)=>M.status==="in-progress"||M.status==="todo").length,v=o.filter((M)=>M.status!=="cancelled"),x=v.filter((M)=>M.status==="done").length,g=o.length-v.length,b=r.length>0,I=l||b,R=h>0?`${h} running`:v.length>0?`${x}/${v.length} done${g>0?` · ${g} cancelled`:""}`:o.length>0?`${o.length} cancelled`:"none yet";return i(_e,{children:[i("button",{type:"button",class:"session-section-toggle","aria-expanded":I,"data-testid":"work-items-toggle",onClick:()=>u((M)=>!M),children:[i("span",{class:"session-section-title",children:"Work items"},void 0,!1,void 0,this),i("span",{class:"session-work-summary",children:[h>0&&i("span",{class:"session-work-dot","aria-hidden":"true"},void 0,!1,void 0,this),R]},void 0,!0,void 0,this),i("span",{class:`session-section-chevron${I?" is-open":""}`,"aria-hidden":"true",children:i(ks,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I&&(r.length===0&&s.length===0&&a.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((M)=>i(nz,{gate:M,now:m},M.id,!1,void 0,this)),s.map((M)=>i(oz,{gate:M},M.id,!1,void 0,this)),a.map((M)=>i(iz,{gate:M},M.id,!1,void 0,this)),o.map((M)=>i(tz,{item:M},M.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:Ek.map((h)=>i("button",{type:"button",class:`activity-filter${$r.value===h.id?" is-active":""}`,"aria-pressed":$r.value===h.id,title:h.hint,onMouseEnter:()=>d(h.id),onMouseLeave:()=>d((v)=>v===h.id?null:v),onFocus:()=>d(h.id),onBlur:()=>d((v)=>v===h.id?null:v),onClick:()=>{$r.value=h.id},children:h.label},h.id,!1,void 0,this))},void 0,!1,void 0,this),i("div",{class:"session-timeline-hint","data-testid":"timeline-filter-hint",children:Ak[p??$r.value]},void 0,!1,void 0,this),c.length===0?i("div",{class:"session-empty",children:$r.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:c.map((h)=>i(cz,{entry:h},h.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 jm(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)}}var Pk=(e)=>e.map((t)=>t.title).join(", ");function lz({context:e,label:t}){let o=[{key:"read",name:"Read",glyph:"eye"},{key:"pinned",name:"Pinned",glyph:"pin"},{key:"created",name:"Created",glyph:"spark"},{key:"edited",name:"Edited",glyph:"pen"}].filter((s)=>e[s.key].length>0);if(o.length===0&&e.changedSinceRead.length===0)return null;let r=nr.value!==null;return i("div",{class:"session-receipt-context","data-testid":"session-receipt-context",children:[e.changedSinceRead.length>0&&i("div",{class:"session-receipt-warn",children:[i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:i("path",{d:Zl.warn},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{children:[Pk(e.changedSinceRead)," changed after ",t," read"," ",e.changedSinceRead.length===1?"it":"them","."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o.map((s)=>i("div",{class:"session-receipt-context-row","data-row":s.key,children:[i("div",{class:"session-receipt-context-head",children:[s.glyph==="pin"?i($c,{},void 0,!1,void 0,this):i("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:i("path",{d:Zl[s.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"session-receipt-context-name",children:s.name},void 0,!1,void 0,this),i("span",{class:"session-receipt-context-count",children:e[s.key].length},void 0,!1,void 0,this),s.key==="pinned"&&i("button",{type:"button",class:"session-receipt-mini",onClick:()=>{for(let a of e.pinned)Jn(a.id)},children:"Unpin"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"session-receipt-context-items",children:s.key==="pinned"?e.pinned.map((a)=>a.reason?`${a.title} — “${a.reason}”`:a.title).join("; "):Pk(e[s.key])},void 0,!1,void 0,this)]},s.key,!0,void 0,this)),i("button",{type:"button",role:"switch","aria-checked":r,class:`session-receipt-lens${r?" is-on":""}`,onClick:()=>Cm(!r),children:[i("span",{class:"session-receipt-lens-track","aria-hidden":"true",children:i("span",{class:"session-receipt-lens-knob"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"Dim untouched nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Nk({onOpenSnapshots:e}){let t=Di.value,[n,o]=A(null),[r,s]=A(!1);if(H(()=>o(null),[t]),!t)return null;let a=async()=>{if(!t.snapshot)return;s(!0);try{let u=await ct(`/api/canvas/snapshots/${encodeURIComponent(t.snapshot.id)}/diff`,{headers:{"x-pmx-workbench":"1"}});if(u.ok){let p=await u.json();o(jm(p.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.sessions>1?`${t.sessions} sessions ended`: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:Hl,"aria-label":"Dismiss receipt",children:i(Ve,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.sessions>1&&i("div",{class:"session-receipt-who",children:t.labels.join(", ")},void 0,!1,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(lz,{context:t.context,label:t.labels.join(", ")},void 0,!1,void 0,this),i("div",{class:"session-receipt-note",children:t.sessions>1?"History has each session’s diff and the snapshot from before it.":t.snapshot?"A snapshot of the board from before this session is saved — restore it to undo the session.":t.context.created.length===0&&t.context.edited.length===0?"The board itself did not change — nothing to restore.":"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 uz=[{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:rt("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:rt("0"),desc:"Reset viewport to origin"},{keys:`${rt("+")} / ${rt("−")}`,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:Es?"Delete / ⌫":"Delete / Backspace",desc:"Delete the selection (or the focused node)"},{keys:Es?"⌘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 zk({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:uz.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:Se()&&n.desc.startsWith("Undo / redo")?"Undo / redo — available in the local workbench only":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 Rk="Before session · ";function Mk(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 dz(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 ou(e){if(!e.startsWith(Rk))return null;let t=e.slice(Rk.length),n=t.lastIndexOf(" · ");return n>0?t.slice(0,n):t}function $k({open:e,onClose:t,anchorRef:n}){let[o,r]=A([]),[s,a]=A(!1),[c,l]=A(!1),[u,p]=A(null),[d,m]=A(""),[f,h]=A(null),[v,x]=A({}),g=L(null),b=L(null);H(()=>{if(!e)return;a(!0),_b().then((w)=>{r(w),a(!1)})},[e]),H(()=>{if(e)setTimeout(()=>b.current?.focus(),50)},[e]),H(()=>{if(!e)return;let w=(k)=>{let z=g.current,X=n.current;if(z&&!z.contains(k.target)&&X&&!X.contains(k.target))t()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[e,t]),H(()=>{if(!e)return;let w=(k)=>{if(k.key==="Escape")t()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,t]);let I=j(async()=>{let w=d.trim();if(!w)return;l(!0);let k=await Sb(w);if(l(!1),k.ok&&k.snapshot)r((z)=>[k.snapshot,...z]),m("")},[d]),R=j(async(w)=>{h(null),p(w);let k=await kb(w);if(p(null),k.ok)t()},[t]),M=j(async(w)=>{if((await Tb(w)).ok)r((z)=>z.filter((X)=>X.id!==w));h(null)},[]),_=j(async(w)=>{x((z)=>({...z,[w]:"loading"}));let k=await ne("snapshotDiff",`/api/canvas/snapshots/${encodeURIComponent(w)}/diff`,{});x((z)=>({...z,[w]:jm(k.diff)??{added:0,removed:0,modified:0}}))},[]);if(!e)return null;let N=(w,k)=>f?.id===w.id?i(_e,{children:[i("button",{type:"button",class:`snapshot-action-btn ${f.action==="delete"?"snapshot-action-confirm":"snapshot-action-restore"}`,onClick:()=>f.action==="delete"?M(w.id):R(w.id),title:f.action==="delete"?"Confirm delete":"Confirm restore",disabled:u!==null,children:f.action==="delete"?"Delete":u===w.id?"Restoring…":"Confirm"},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn",onClick:()=>h(null),title:"Cancel",disabled:u!==null,children:"Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):i(_e,{children:[i("button",{type:"button",class:"snapshot-action-btn snapshot-action-restore",onClick:()=>h({id:w.id,action:"restore"}),title:Se()?"Restore this snapshot — replaces the current canvas":"Restore this snapshot — replaces the current canvas (undoable)",disabled:u!==null,children:u===w.id?"Restoring…":k},void 0,!1,void 0,this),i("button",{type:"button",class:"snapshot-action-btn snapshot-action-delete",onClick:()=>h({id:w.id,action:"delete"}),title:"Delete this snapshot","aria-label":"Delete snapshot",disabled:u!==null,children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return i("div",{ref:g,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:i(Ve,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-save-form",children:[i("input",{ref:b,type:"text",class:"snapshot-name-input",value:d,onInput:(w)=>m(w.target.value),onKeyDown:(w)=>{if(w.key==="Enter")I()},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:I,disabled:!d.trim()||c,children:c?"…":"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-restore-note",children:Se()?"Restoring replaces the current canvas. Save a snapshot first to keep your current state.":"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((w)=>ou(w.name)===null),...o.some((w)=>ou(w.name)!==null)?[{id:"__sessions-header__"}]:[],...o.filter((w)=>ou(w.name)!==null)].map((w)=>{if(w.id==="__sessions-header__")return i("div",{class:"snapshot-section-header","data-testid":"history-sessions-header",children:"Sessions"},w.id,!1,void 0,this);let k=ou(w.name),z=v[w.id];if(k!==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 — ",k]},void 0,!0,void 0,this),i("span",{class:"snapshot-item-time",children:Mk(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:["snapshot at session start · ",w.nodeCount," node",w.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 _(w.id),children:z==="loading"?"Comparing…":"View diff"},void 0,!1,void 0,this),N(w,"Restore pre-state")]},void 0,!0,void 0,this)]},w.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:w.name},void 0,!1,void 0,this),i("span",{class:"snapshot-item-time",children:Mk(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-meta",children:[w.nodeCount," node",w.nodeCount!==1?"s":"",w.edgeCount>0?` · ${w.edgeCount} edge${w.edgeCount!==1?"s":""}`:""," · ",dz(w.createdAt)]},void 0,!0,void 0,this),i("div",{class:"snapshot-item-actions",children:N(w,"Restore")},void 0,!1,void 0,this)]},w.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 pz=8;function mz({children:e}){let t=Be(()=>document.createElement("div"),[]);return _n(()=>(document.body.appendChild(t),()=>{Qi(null,t),t.remove()}),[t]),_n(()=>Qi(e,t),[e,t]),null}function Ok({fallbackName:e}){let[t,n]=A(!1),o=L(null),r=L(null),s=L(null);_n(()=>{if(!t)return;let d=(f)=>{if(f.target instanceof Node&&!o.current?.contains(f.target)&&!s.current?.contains(f.target))n(!1)},m=(f)=>{if(f.key==="Escape")f.stopPropagation(),n(!1),r.current?.focus()};return document.addEventListener("pointerdown",d,!0),document.addEventListener("keydown",m,!0),()=>{document.removeEventListener("pointerdown",d,!0),document.removeEventListener("keydown",m,!0)}},[t]);let a=dc(),c=!$o.value?e:a?a.name:"Home",l=rn.value.filter((d)=>d.id!==Oe.value).slice(0,pz),u=r.current?.getBoundingClientRect(),p=(d)=>{n(!1),sn(d)};return i("span",{class:"board-switcher",ref:o,children:[i("button",{ref:r,type:"button",class:"top-bar-title board-switcher-button","aria-haspopup":"menu","aria-expanded":t,"aria-label":`Board: ${c}. Switch board`,onClick:()=>n((d)=>!d),children:[i("span",{class:"board-switcher-name",children:c},void 0,!1,void 0,this),i("span",{class:"board-switcher-caret","aria-hidden":"true",children:i(Nc,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&u&&i(mz,{children:i("div",{ref:s,class:"toolbar-menu board-switcher-menu",role:"menu","aria-label":"Boards",style:{position:"fixed",left:`min(${u.left}px, max(12px, calc(100vw - 352px)))`,top:`${u.bottom+8}px`,right:"auto",maxHeight:`min(70vh, calc(100dvh - ${u.bottom+20}px))`},children:[l.length>0&&i("div",{class:"board-switcher-heading",children:"Recent boards"},void 0,!1,void 0,this),i("div",{class:"board-switcher-recents",children:l.map((d)=>i("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>p(d.id),children:[i("span",{class:"board-switcher-icon","aria-hidden":"true",children:i(Oc,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),i("span",{class:"board-switcher-item-copy",children:[i("span",{class:"board-switcher-item-name",children:d.name},void 0,!1,void 0,this),i("span",{class:"board-switcher-item-folder",children:d.category?.split("/").join(" / ")||"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i("span",{class:"board-switcher-item-meta",children:[d.nodeCount," ",d.nodeCount===1?"node":"nodes"]},void 0,!0,void 0,this)]},d.id,!0,void 0,this))},void 0,!1,void 0,this),i("div",{class:"board-switcher-actions",children:[i("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>{n(!1),Fm()},children:[i("span",{class:"board-switcher-icon","aria-hidden":"true",children:i(ox,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),"New board…"]},void 0,!0,void 0,this),i("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>p(null),children:[i("span",{class:"board-switcher-icon","aria-hidden":"true",children:i(go,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),"All boards (Home)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Lk=3,Dk={"waiting-approval":0,thinking:1,tooling:2,idle:3};function fz(){let e=nS.value;if(e.length===0)return null;let t=e.filter((c)=>!c.parentAgentId||!e.some((l)=>l.sessionId!==c.sessionId&&!l.parentAgentId&&(l.sessionId===c.parentAgentId||l.source===c.parentAgentId))),n=[...t].sort((c,l)=>(Dk[c.phase]??4)-(Dk[l.phase]??4)),o=n.slice(0,Lk),r=n.slice(Lk),s=t.reduce((c,l)=>(c[l.phase]=(c[l.phase]??0)+1,c),{}),a=[s["waiting-approval"]&&`${s["waiting-approval"]} waiting on approval`,s.thinking&&`${s.thinking} thinking`,s.tooling&&`${s.tooling} running tools`,s.idle&&`${s.idle} idle`].filter(Boolean).join(", ");return i(_e,{children:[i("span",{class:"agent-chips",children:o.map((c)=>{let l=c.parentAgentId?0:It.value.filter((u)=>u.parentAgentId!=null&&(u.parentAgentId===c.sessionId||u.parentAgentId===c.source)).length;return i(Qe,{label:`Agent session — ${c.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-${c.phase}`,"data-phase":c.phase,style:{"--identity-color":An(c.sessionId)},children:[i("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),i("span",{class:"agent-chip-label",children:Jo(c)},void 0,!1,void 0,this),i("span",{class:"agent-chip-who hud-collapsible-text",children:c.label},void 0,!1,void 0,this),l>0&&i("span",{class:"agent-chip-workers",children:["+",l," worker",l===1?"":"s"]},void 0,!0,void 0,this),i("button",{type:"button",class:"agent-chip-end","aria-label":`End ${c.label} session`,title:`End ${c.label}'s session`,onClick:(u)=>{u.stopPropagation(),Bl({source:c.source,agentId:c.agentId})},children:i(Ve,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},c.sessionId,!1,void 0,this)})},void 0,!1,void 0,this),r.length>0&&i(Qe,{label:`${t.length} agent sessions attached`,tapToOpen:!0,body:`${t.length} agents on this board — ${a}. 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:["+",r.length," · ",t.length," agents"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function hz(){let e=Mr.value.length,t=Li.value!==null&&e>0,n=xo(t?1000:0);if(!t)return null;let o=Mr.value.map((r)=>tu(r,n)).filter((r)=>r!==null).sort((r,s)=>r-s)[0];return i(Qe,{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&&` · ${nu(o)}`]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function gz(e){if(e>0.9)return"danger";if(e>=0.7)return"warn";return"ok"}function ra(e){return e>=1000?`${(e/1000).toFixed(e>=1e4?0:1)}k`:String(e)}function vz(){let e=Li.value;if(!e)return null;let t=gm.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:`${ra(n.used)} of ${ra(n.total)} tokens of the agent's actual context window are used. Your ✦-pinned nodes account for ≈ ${ra(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: ≈ ${ra(t.used)} of a ${ra(t.total)}-token budget. When the agent's host reports its real context window, this meter switches to showing that instead.`};return i(Qe,{label:c.label,body:c.body,tapToOpen:!0,children:i("span",{class:`context-budget tone-${gz(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 yz(){let[e,t]=A(!1);if(Li.value)return null;return i(Qe,{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),tr().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 Fk(){let e=fn.value,t=Yt.value,n=oe.value,o=F.value.size,r=Je.value.size,s=li.value,a=Array.from(F.value.values()).filter((f)=>f.type==="trace").length,[c,l]=A("");H(()=>{let f=!1;return ct("/health").then((h)=>h.ok?h.json():null).then((h)=>{if(f||typeof h?.workspace!=="string"||!h.workspace)return;let v=h.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop();if(v)l(v)}).catch(()=>{}),()=>{f=!0}},[]);let u=zm.value,p=u??(e==="connected"&&!t?"syncing":e),d=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=bt();pi(f.width,f.height)};return i("div",{class:"top-bar",children:[i(Qe,{label:`Canvas status: ${p}`,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: ${p}`},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Ok,{fallbackName:c||"PMX Canvas"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:lo.value?lo.value.slice(0,12):"…"},void 0,!1,void 0,this),i("span",{class:"top-bar-meta hud-collapsible-text",children:d},void 0,!1,void 0,this),i("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),i(fz,{},void 0,!1,void 0,this),i(hz,{},void 0,!1,void 0,this),i(vz,{},void 0,!1,void 0,this),i(hk,{},void 0,!1,void 0,this),!Se()&&i(yz,{},void 0,!1,void 0,this),i("div",{class:"top-bar-sep"},void 0,!1,void 0,this),Oe.value&&i(Qe,{label:"Export board",body:"One HTML file of this board that anyone can open, no install needed.",children:i("button",{type:"button",class:"present-button",onClick:()=>{Ui.value=!0},children:"Export"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Oe.value&&i(Qe,{label:"Present board",body:"Arrow keys or Space step through stops; Esc exits. Without a saved tour, groups are read top-to-bottom, left-to-right.",children:i("button",{type:"button",class:"present-button",onClick:()=>{Fn.value=!0},children:"Present"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Qe,{label:"Zoom out",shortcut:rt("−"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>di(0.8),"aria-label":"Zoom out",children:i(lx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Qe,{label:"Reset zoom",shortcut:rt("0"),children:i("button",{type:"button",class:"top-bar-zoom-label",onClick:()=>Fo({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(Qe,{label:"Zoom in",shortcut:rt("+"),children:i("button",{type:"button",class:"top-bar-btn",onClick:()=>di(1.25),"aria-label":"Zoom in",children:i(cx,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(Qe,{label:"Fit all",shortcut:"F",align:"end",children:i("button",{type:"button",class:"top-bar-btn",onClick:m,"aria-label":"Fit canvas",children:i(zc,{},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 or={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},board:{x:380,y:80,w:360,h:160},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 ia(e,t,n,o={}){let r=or[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 Fr=null,ca=null,ru=0,rr=null,bz=3000,xz=2000,Bk=5000,sa=!1,wo=null,Zi=null,sr=0,ir=null;function wz(){if(Se())return"poll";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 Wi=new Map;function la(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 su(e){if(!ca)return e;let t=ca.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 ua(e,t,n){return su(ia(e,t,n))}function _z(){return cl([...F.value.values()],or.markdown.w,or.markdown.h)}function qi(){if(!F.value.has("status-main"))po(ua("status-main","status",{phase:"idle",message:"",elapsed:0}))}function Sz(e,t){let n=`md-${la(e)}`;if(F.value.get(n))fe(n,{path:e,title:t}),je.value=n;else{let r=_z(),s=ua(n,"markdown",{path:e,title:t,content:"",rendered:""});s.position=r,po(s),pt(n)}}function kz(e){if(F.value.get("context-main"))fe("context-main",{cards:e});else if(e.length>0){let o=ua("context-main","context",{cards:e});po(o)}}function Tz(e){let t=e.url,n=`mcp-${la(t)}`;if(F.value.get(n))fe(n,e);else po(ua(n,"mcp-app",e)),pt(n)}function Cz(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(F.value.get(o)){fe(o,e);return}let{serverName:s,toolName:a}=e;if(s&&a){for(let[x,g]of F.value.entries())if(g.type==="mcp-app"&&g.data.mode==="ext-app"&&g.data.serverName===s&&g.data.toolName===a&&!g.data.toolResult){fe(x,{...e});return}}let{_x:c,_y:l,_width:u,_height:p}=e,d=or["mcp-app"],m=u??d.w,f=p??d.h,h=c===void 0||l===void 0?cl([...F.value.values()],m,f):null,v=su(ia(o,"mcp-app",{mode:"ext-app",...e},{position:{x:c??h?.x??d.x,y:l??h?.y??d.y},size:{width:m,height:f}}));po(v),pt(o,{recordHistory:!1})}function Ez(e){let t=e.startsWith("ext-app-")?e:`ext-app-${e}`;if(F.value.has(t))return t;let n=`ext-app-${e}`;if(n!==t&&F.value.has(n))return n;for(let[o,r]of F.value.entries())if(r.type==="mcp-app"&&r.data.mode==="ext-app"&&r.data.toolCallId===e)return o;return null}function qk(e){let t=typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null;if(t&&F.value.has(t))return t;if(typeof e.toolCallId!=="string"||!e.toolCallId)return null;return Ez(e.toolCallId)}function Gk(e,t){if(typeof e!=="string"||!e)return null;if(typeof t!=="string"||!t)return null;let n=null;for(let[o,r]of F.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 Vk(e){if(F.value.get("ledger-main"))fe("ledger-main",e);else{let o=ua("ledger-main","ledger",e);o.collapsed=!0,po(o)}}function qm(e){if(!Ls(e))return;if(document.documentElement.setAttribute("data-theme",e),Ri(),gt.value!==e)gt.value=e}function Az(e){return e==="markdown"||e==="mcp-app"||e==="webpage"||e==="json-render"||e==="graph"||e==="board"||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 Iz(e){return e==="relation"||e==="depends-on"||e==="flow"||e==="references"}function Gm(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 Xk(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 Pz(e){let t=Gm(e),n=Xk(e);return t&&n?{...t,...n}:null}function Nz(e){if(typeof e.id!=="string"||!e.id)return null;if(!Az(e.type))return null;let t=Gm(e.position),n=Xk(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,contentRevision:typeof e.contentRevision==="number"?e.contentRevision:0,...Hk(e.createdBy)?{createdBy:e.createdBy}:{},...Hk(e.lastEditedBy)?{lastEditedBy:e.lastEditedBy}:{},data:o}}function Hk(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.actor==="string"&&typeof t.source==="string"}function zz(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(!Iz(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 Rz(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)=>Gm(o)).filter((o)=>o!==null),n=Pz(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 jk="pmx-canvas-version-reload";function Mz(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(jk)===r)return;window.sessionStorage.setItem(jk,r)}catch{return}window.location.reload()}function $z(e){let t=Yo.value[0]?.id;if(bm(e),_t.value&&Yo.value[0]?.id!==t)er()}function Oz(e){hS(e)}var Uk=null,aa=0,Um=0,Zm=0;function Lz(e){Ep(e)}function Dz(){let e=++aa;ca=null,Yt.value=!1,tl(),Mb(),ac(),Hl(),Em({}),Dn.value=null,Vm();let t=Um,n=Zm;fb().then((o)=>{if(e===aa&&t===Um)Kk({layout:o})}),ne("fetchPinnedContext","/api/canvas/pinned-context",{}).then((o)=>{if(e===aa&&n===Zm)Jk({nodeIds:o.nodeIds})})}sb(Dz);function Fz(e){if(lo.value=e.sessionId||"",fn.value="connected",Pd().then(bs),_r.value+=1,Mz(e.version,e.bundleStamp),yb().then(bm),jl(),Uk?.(),!pc&&!Se())Uk=qw();if(ne("fetchHumanPresence","/api/canvas/human-presence",null).then(Ep),Vm().then(()=>{if(_t.value)er()}),typeof e.theme==="string"&&!Rm())qm(e.theme);if(e.ledgerSummary)Vk(e.ledgerSummary)}function Bz(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(Sz(t,n),e.ledgerSummary)Vk(e.ledgerSummary)}function Hz(e){qi(),fe("status-main",{message:typeof e.message==="string"?e.message:String(e.message??""),level:e.level??"ok",source:e.source})}function jz(e){qi(),fe("status-main",{phase:e.phase,detail:e.detail})}function Uz(e){let t=e.cards??[];kz(t)}function Zz(e){if(typeof e.url==="string"&&e.url)Tz({url:e.url,sourceServer:e.sourceServer,sourceTool:e.sourceTool,inferredType:e.inferredType,trustedDomain:e.trustedDomain,hostMode:e.hostMode??"hosted"})}function Wz(e){let t=e.sessions??[];for(let n of t){let o=n.url;if(!o)continue;let r=`mcp-${la(o)}`;if(F.value.has(r))fe(r,{sessionState:n.state,lastSeenAt:n.lastSeenAt})}}function qz(e){if(typeof e.url==="string"&&e.url){let t=`mcp-${la(e.url)}`;if(F.value.has(t))fe(t,{hostMode:"fallback",fallbackReason:e.reasonCode})}}function Gz(e){let n=F.value.get("context-main");if(!n)return;let o=(n.data.auxTabs??[]).concat(e);fe("context-main",{auxTabs:o})}function Vz(e){if(F.value.has("context-main"))if(e.mode==="all")fe("context-main",{auxTabs:[]});else{let o=F.value.get("context-main");if(!o)return;let r=(o.data.auxTabs??[]).filter((s)=>s.id!==e.id);fe("context-main",{auxTabs:r})}}function Xz(e){qi(),fe("status-main",{phase:"idle",lastCompletion:{tokenCount:e.tokenCount,artifactCount:e.artifactCount}})}function Kz(e){qi(),fe("status-main",{phase:"tooling",detail:`${e.name}`,activeTool:e.name})}function Jz(e){qi(),fe("status-main",{activeTool:null})}function Yz(e){if(e.state==="active"&&e.path){let n=`md-${la(e.path)}`;if(F.value.has(n))fe(n,{reviewActive:!0})}}function Qz(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;Cz({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 eR(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=qk(e)??Gk(e.serverName,e.toolName);if(!t)return;if(F.value.has(t))fe(t,{html:e.html})}function tR(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=qk(e)??Gk(e.serverName,e.toolName);if(!t)return;if(F.value.has(t)){if(e.success===!1){Do(t);return}fe(t,{toolResult:cm({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 nR(e){qi(),fe("status-main",{subagent:{state:e.state,name:e.agentDisplayName??e.agentName}})}function oR(e){let t=e.nodeId;if(!t)return;let n=e.text||"",{position:o,parentNodeId:r,contextNodeIds:s}=e;if(e.threadNodeId&&F.value.has(e.threadNodeId)){let a=e.threadNodeId,c=F.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"});fe(a,{turns:l,threadStatus:"pending"});return}if(!F.value.has(t)){let a=o??or.prompt;po(su(ia(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}}))),pt(t)}if(r&&F.value.has(r))ai({id:`edge-${r}-${t}`,from:r,to:t,type:"flow",style:"dashed"})}function rR(e){let{nodeId:t,status:n}=e;if(t&&F.value.has(t))fe(t,{status:n})}function iR(e){let{responseNodeId:t,promptNodeId:n}=e;if(!t)return;let o=n?F.value.get(n):void 0;if(o&&Array.isArray(o.data.turns)){Wi.set(t,n);let s=[...o.data.turns];s.push({role:"assistant",text:"",status:"streaming"}),fe(n,{turns:s,threadStatus:"streaming",_activeResponseId:t}),pt(n);return}let r=o?{x:o.position.x,y:o.position.y+o.size.height+24}:{x:or.response.x,y:or.response.y};if(!F.value.has(t))po(su(ia(t,"response",{content:"",status:"streaming",promptNodeId:n},{position:r})));if(n)ai({id:`edge-${n}-${t}`,from:n,to:t,type:"flow",animated:!0});pt(t)}function sR(e){let t=e.responseNodeId;if(!t)return;let n=Wi.get(t);if(n){let o=F.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";fe(n,{turns:r,threadStatus:"streaming"})}return}if(!F.value.has(t))return;fe(t,{content:e.content,status:"streaming"})}function aR(e){let t=e.responseNodeId;if(!t)return;let n=Wi.get(t);if(n){let s=F.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";fe(n,{turns:a,threadStatus:"answered",_activeResponseId:void 0})}Wi.delete(t);return}if(!F.value.has(t))return;fe(t,{content:e.content,status:"complete"});let r=F.value.get(t)?.data.promptNodeId;if(r){let s=`edge-${r}-${t}`,a=Je.value.get(s);if(a)Ub(s),ai({...a,animated:!1})}}function Kk(e){let t=e.layout;if(!t?.nodes)return;Um+=1;let n=!Yt.value;Yt.value=!0;let o=t.nodes.map(Nz).filter((c)=>c!==null),r=Array.isArray(t.edges)?t.edges.map(zz).filter((c)=>c!==null):Array.from(Je.value.values()),s=Array.isArray(t.annotations)?t.annotations.map(Rz).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)fo();Xb({...a?{viewport:a}:{},nodes:o,edges:r,...s?{annotations:s}:{}},{applyViewport:n}),Ad({event:"canvas-layout-update",data:e})}function cR(e){if(e<=1)return 500;if(e===2)return 1000;return Math.min(2500,1500+(e-3)*500)}function lR(e){if(Zd())return;let t=e.nodeId;if(t&&F.value.has(t)){if(e.noPan===!0){mo(t);return}pt(t)}}function uR(e){if(Zd())return;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;fo(),qb({x:n,y:o,scale:r})}function dR(e){if(F.value.get("context-main"))fe("context-main",{currentTokens:e.currentTokens,tokenLimit:e.tokenLimit,messagesLength:e.messagesLength,utilization:e.utilization,nearLimit:e.nearLimit})}function pR(e){li.value=e.enabled===!0}function mR(e){if(typeof e.theme==="string"&&!Rm())qm(e.theme)}function Jk(e){Zm+=1;let t=Array.isArray(e.nodeIds)?e.nodeIds.filter((n)=>typeof n==="string"):[];jb(t),Ad({event:"context-pins-changed",data:e}),jl()}function fR(){jl()}var iu=null,Wm=0;async function Vm(){let e=++Wm,t=aa,n=await vb();if(e===Wm&&t===aa)Dn.value=n}function Zk(){if(iu)clearTimeout(iu);Wm+=1,iu=setTimeout(()=>{if(iu=null,Vm(),_t.value)er()},150)}function hR(e){let t=e.intent;if(!t||typeof t.id!=="string"||typeof t.kind!=="string"||typeof t.expiresAt!=="number")return;Dw(t)}function gR(e){let t=typeof e.id==="string"?e.id:"";if(!t)return;if(e.settled===!0)Bw(t,typeof e.nodeId==="string"?e.nodeId:void 0);else Cp(t)}var Yk={connected:Fz,"workbench-open":Bz,"canvas-status":Hz,"execution-phase":jz,"context-cards":Uz,"mcp-app-candidate":Zz,"mcp-app-host-snapshot":Wz,"mcp-app-host-fallback":qz,"aux-open":Gz,"aux-close":Vz,"assistant-complete":Xz,"tool-start":Kz,"tool-complete":Jz,"review-state":Yz,"subagent-status":nR,"ext-app-open":Qz,"ext-app-update":eR,"ext-app-result":tR,"context-pins-changed":Jk,"context-status-changed":fR,"boards-changed":vr,"canvas-layout-update":Kk,"canvas-focus-node":lR,"canvas-viewport-update":uR,"context-usage":dR,"trace-state":pR,"theme-changed":mR,"canvas-prompt-created":oR,"canvas-prompt-status":rR,"canvas-response-start":iR,"canvas-response-delta":sR,"canvas-response-complete":aR,"ax-state-changed":Zk,"ax-event-created":Zk,"ax-intent":hR,"ax-intent-clear":gR,"agent-presence":$z,"human-presence":Lz,"agent-session-ended":Oz};function Qk(e,t){let n=Yk[e];if(!n)return;let o=n;try{o(t)}catch(r){console.warn(`[sse-bridge] Handler for "${e}" failed:`,r)}}function Wk(){sa=!0,sr+=1;let e=sr;fn.value="connecting";let t=null,n=!1,o=async()=>{if(e!==sr)return;try{let r=new URLSearchParams;if(Zi!==null)r.set("since",String(Zi));let s=lo.value;if(s)r.set("session",s);let a=r.toString(),c=await ct(`/api/workbench/poll${a?`?${a}`:""}`);if(e!==sr)return;if(!c.ok)throw Error(`poll failed with HTTP ${c.status}`);let l=await c.json();if(e!==sr)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){Zi=null,wo=setTimeout(()=>void o(),0);return}if(l.snapshot&&n)ca=Ud(),Yt.value=!1,ac(),tl(),Wi.clear();for(let p of l.events)Qk(p.event,p.payload);n=!0,Zi=l.seq,Sr.value=0,kr.value=0,fn.value="connected",wo=setTimeout(()=>void o(),xz)}catch(r){if(e!==sr)return;console.warn("[sse-bridge] poll transport error:",r),fn.value="disconnected",Sr.value+=1,kr.value=Bk,wo=setTimeout(()=>void o(),Bk)}};return o(),()=>{if(sr+=1,sa=!1,Zi=null,wo)clearTimeout(wo),wo=null}}function Xm(){if(JS(qm),ca=Ud(),Yt.value=!1,ac(),tl(),Wi.clear(),rr)clearTimeout(rr),rr=null;let e=wz();if(e==="poll"||sa)return Wk();let t=lo.value,n=t?`/api/workbench/events?session=${t}`:"/api/workbench/events";fn.value="connecting";let o=new EventSource(n);Fr=o;let r=!1;if(ir)clearTimeout(ir);if(ir=null,e!=="sse")ir=setTimeout(()=>{if(ir=null,r||Fr!==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(),Fr=null,Wk()},bz);for(let[s]of Object.entries(Yk))o.addEventListener(s,(a)=>{r=!0;try{Qk(s,JSON.parse(a.data))}catch(c){console.warn(`[sse-bridge] Failed to parse "${s}" event:`,c)}});return o.onopen=()=>{if(Fr!==o)return;ru=0,Sr.value=0,kr.value=0,fn.value="connected"},o.onerror=()=>{if(Fr!==o)return;fn.value="disconnected",o.close(),Fr=null,ru+=1;let s=cR(ru);Sr.value=ru,kr.value=s,rr=setTimeout(()=>{rr=null,Xm()},s)},()=>{if(rr)clearTimeout(rr),rr=null;if(ir)clearTimeout(ir),ir=null;if(sa){if(sr+=1,sa=!1,Zi=null,wo)clearTimeout(wo),wo=null}o.close(),Fr=null}}function Br(e,t){console.error(`[app] ${e} failed`,t)}function e0(){let[e,t]=A(!0),[n,o]=A(!1),[r,s]=A(!1),[a,c]=A(!1),[l,u]=A(!1),[p,d]=A(null),m=L(null),{menu:f,openNodeMenu:h,openCanvasMenu:v,openEdgeMenu:x,closeMenu:g}=ek(),b=Yt.value,I=$o.value&&Oe.value===null,R=_t.value,M=j(()=>t((W)=>!W),[]),_=j(()=>o((W)=>!W),[]),N=j(()=>o(!1),[]),w=j((W)=>d(W),[]),k=j((W,J)=>{Fo({x:W,y:J,scale:oe.value.scale},200)},[]);H(()=>Xm(),[]),H(()=>{let W=()=>c(!0);return window.addEventListener("pmx-open-board-link",W),()=>window.removeEventListener("pmx-open-board-link",W)},[]),H(()=>{let W=null,J=()=>{if(W!==null)window.clearTimeout(W);W=window.setTimeout(()=>{W=null,bs()},400)};return window.addEventListener("resize",J),()=>{if(W!==null)window.clearTimeout(W);window.removeEventListener("resize",J)}},[]),H(()=>{let W=(S)=>{let q=(S.metaKey||S.ctrlKey)&&!S.altKey;if(q&&S.key==="k"){S.preventDefault(),s((ue)=>!ue);return}if(S.key==="Escape"&&p){S.preventDefault(),d(null);return}if(S.key==="Escape"&&ot.value&&!Ln.value){S.preventDefault(),ho();return}if(S.key==="Escape"&&r){S.preventDefault(),s(!1);return}if(S.key==="Escape"&&l){S.preventDefault(),u(!1);return}let ie=S.target,ye=ie?.tagName;if(ye==="INPUT"||ye==="TEXTAREA"||ie?.isContentEditable)return;if(S.key===" "&&!S.repeat&&!q){S.preventDefault(),_s.value=!0;return}if(S.key==="?"||S.key==="/"&&S.shiftKey){S.preventDefault(),u((ue)=>!ue);return}if(q&&(S.key==="z"||S.key==="Z"))S.preventDefault(),Tm(S.shiftKey);else if(q&&(S.key==="y"||S.key==="Y"))S.preventDefault(),Tm(!0);else if(q&&S.key==="0")S.preventDefault(),Fo({x:0,y:0,scale:1},250);else if(q&&(S.key==="="||S.key==="+"))S.preventDefault(),di(1.25);else if(q&&S.key==="-")S.preventDefault(),di(0.8);else if(S.key==="Escape"){if(Ne.value.size>0||Kn.value!==null){Ut();return}je.value=null,g()}else if(S.key==="Tab")S.preventDefault(),Jb(S.shiftKey?-1:1);else if(S.key==="Delete"||S.key==="Backspace"){if(Kn.value!==null){let Pe=Kn.value;S.preventDefault(),Kn.value=null,xc(Pe).catch((ke)=>Br("delete-edge",ke));return}let ue=Ne.value.size>0?[...Ne.value]:je.value?[je.value]:[];if(ue.length===0)return;S.preventDefault();for(let Pe of ue)Oo(Pe).catch((ke)=>Br("delete",ke));Ut(),je.value=null}else if(je.value&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(S.key)){S.preventDefault();let ue=S.key.replace("Arrow","").toLowerCase();Yb(ue)}else if(!q&&!S.altKey){let ue=S.key.toLowerCase();if(ue==="v"&&!S.shiftKey)Qt.value="select";else if(ue==="c"&&!S.shiftKey&&!q)S.preventDefault(),Qt.value=Qt.value==="connect"?"select":"connect";else if(ue==="m"&&!S.shiftKey)S.preventDefault(),In({type:"markdown",title:"New note",width:520,height:360}).catch((Pe)=>Br("create markdown",Pe));else if(ue==="a"&&!S.shiftKey)S.preventDefault(),d((Pe)=>Pe==="pen"?null:"pen");else if(ue==="g"&&!S.shiftKey){S.preventDefault();let Pe=Array.from(Ne.value);if(Pe.length>=2)ii({title:"Group",childIds:Pe}).catch((ke)=>Br("group selection",ke)),Ut();else In({type:"group",title:"Group"}).catch((ke)=>Br("create group",ke))}else if(ue==="g"&&S.shiftKey){S.preventDefault();for(let Pe of Db())Do(Pe),si(Pe).catch((ke)=>Br("ungroup",ke));Ut()}else if(ue==="i"&&!S.shiftKey)S.preventDefault(),Dr("image");else if(ue==="w"&&!S.shiftKey)S.preventDefault(),Dr("webpage");else if(ue==="h"&&!S.shiftKey)S.preventDefault(),In({type:"html",title:"HTML surface"}).catch((Pe)=>Br("create html",Pe));else if(ue==="f"&&S.shiftKey)S.preventDefault(),Dr("file");else if(ue==="f"&&!S.shiftKey){S.preventDefault();let Pe=bt();pi(Pe.width,Pe.height)}}},J=(S)=>{if(S.key===" ")_s.value=!1},G=()=>{_s.value=!1};return document.addEventListener("keydown",W),document.addEventListener("keyup",J),window.addEventListener("blur",G),()=>{document.removeEventListener("keydown",W),document.removeEventListener("keyup",J),window.removeEventListener("blur",G)}},[p,g,r,l]),H(()=>{let W=window.setTimeout(()=>void bs(),250);return()=>window.clearTimeout(W)},[R]),H(()=>{if(!b)return;let W=window.__pmxCanvasBootstrapReady;if(typeof W==="function")W()},[b]);let z=Array.from(F.value.values()),X=bt();return i("div",{class:`app-shell${Fn.value?" is-presenting":""}`,"data-session-active":R?"true":"false",children:[i(tx,{},void 0,!1,void 0,this),i(ik,{minimapVisible:e,onToggleMinimap:M,snapshotOpen:n,onToggleSnapshot:_,snapshotBtnRef:m,onOpenPalette:()=>s(!0),onOpenShortcuts:()=>u((W)=>!W),annotationTool:p,onSetAnnotationTool:w},void 0,!1,void 0,this),i("div",{class:"app-main",children:[i(Fk,{},void 0,!1,void 0,this),i(VS,{},void 0,!1,void 0,this),i("div",{class:"canvas-region",ref:(W)=>Py(W),children:[i(qS,{onNodeContextMenu:h,onCanvasContextMenu:v,onEdgeContextMenu:x,annotationMode:p!==null,annotationTool:p},void 0,!1,void 0,this),i(_x,{},void 0,!1,void 0,this),i(wx,{},void 0,!1,void 0,this),i(gk,{},void 0,!1,void 0,this),i(vk,{},void 0,!1,void 0,this),I?i(mk,{},void 0,!1,void 0,this):b&&z.length===0&&lt.value.size===0&&i(sk,{onOpenPalette:()=>s(!0)},void 0,!1,void 0,this),Ne.value.size>0&&i(Ck,{},void 0,!1,void 0,this),R&&!Se()?i(GS,{},void 0,!1,void 0,this):Le.value.size>0&&i(ok,{},void 0,!1,void 0,this),i(Nk,{onOpenSnapshots:()=>o(!0)},void 0,!1,void 0,this),i(kx,{},void 0,!1,void 0,this),i(fk,{},void 0,!1,void 0,this),ot.value&&i(wk,{},void 0,!1,void 0,this),i($k,{open:n,onClose:N,anchorRef:m},void 0,!1,void 0,this),e&&!I&&i(Tk,{viewport:oe,nodes:F,edges:Je,onNavigate:k,containerWidth:X.width,containerHeight:X.height},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),R&&i(Ik,{},void 0,!1,void 0,this),f&&i(tk,{menu:f,onClose:g},void 0,!1,void 0,this),r&&i(YS,{onClose:()=>s(!1),onToggleMinimap:M},void 0,!1,void 0,this),a&&i(QS,{onClose:()=>c(!1)},void 0,!1,void 0,this),l&&i(zk,{onClose:()=>u(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}Nx();var t0=document.getElementById("app");if(t0)Qi(i(e0,{},void 0,!1,void 0,this),t0);