pmx-canvas 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/.github/extensions/pmx-canvas/extension.mjs +9 -3
  2. package/.github/extensions/pmx-canvas/runtime.json +1 -1
  3. package/.github/extensions/pmx-canvas/tools.json +9278 -2014
  4. package/CHANGELOG.md +34 -1
  5. package/dist/canvas/global.css +12 -17
  6. package/dist/canvas/index.js +58 -58
  7. package/dist/canvas/mcp-app.html +75 -80
  8. package/dist/types/client/canvas/submit-without-navigation.d.ts +3 -0
  9. package/dist/types/client/state/intent-bridge.d.ts +0 -3
  10. package/dist/types/client/state/presence-store.d.ts +3 -3
  11. package/dist/types/client/types.d.ts +1 -1
  12. package/dist/types/mcp/canvas-access.d.ts +1 -12
  13. package/dist/types/mcp/resource-subscriptions.d.ts +7 -0
  14. package/dist/types/mcp/server.d.ts +2 -0
  15. package/dist/types/server/ax-wait.d.ts +1 -0
  16. package/dist/types/server/canvas-operations.d.ts +1 -0
  17. package/dist/types/server/canvas-state.d.ts +2 -0
  18. package/dist/types/server/index.d.ts +5 -5
  19. package/dist/types/server/knowledge-lifecycle.d.ts +11 -2
  20. package/dist/types/server/lifecycle-status.d.ts +3 -1
  21. package/dist/types/server/operations/http.d.ts +10 -0
  22. package/dist/types/server/operations/index.d.ts +2 -2
  23. package/dist/types/server/operations/invoker.d.ts +4 -3
  24. package/dist/types/server/operations/mcp-contracts.d.ts +20 -0
  25. package/dist/types/server/operations/mcp.d.ts +2 -0
  26. package/dist/types/server/operations/ops/batch.d.ts +1 -0
  27. package/dist/types/server/operations/registry.d.ts +2 -2
  28. package/dist/types/server/operations/types.d.ts +12 -2
  29. package/dist/types/server/server.d.ts +2 -0
  30. package/dist/types/server/tour-control.d.ts +6 -3
  31. package/dist/types/server/webpage-node.d.ts +1 -0
  32. package/docs/api-reference.md +2 -2
  33. package/docs/cli.md +10 -1
  34. package/docs/design/Chrome.dc.html +1 -0
  35. package/docs/design.md +3 -1
  36. package/docs/http-api.md +31 -0
  37. package/docs/mcp.md +98 -22
  38. package/docs/node-types.md +3 -0
  39. package/docs/plans/plan-019-post-0.9-roadmap.md +187 -11
  40. package/docs/sdk.md +10 -0
  41. package/package.json +1 -1
  42. package/plugins/pmx-canvas/com.github.copilot/extensions/pmx-canvas/extension.mjs +9 -3
  43. package/plugins/pmx-canvas/com.github.copilot/extensions/pmx-canvas/runtime.json +1 -1
  44. package/plugins/pmx-canvas/plugin.json +1 -1
  45. package/plugins/pmx-canvas/runtime.json +1 -1
  46. package/plugins/pmx-canvas/tools.json +9278 -2014
  47. package/skills/pmx-canvas/SKILL.md +12 -7
  48. package/skills/pmx-canvas/references/full-reference.md +35 -2
  49. package/skills/pmx-canvas/references/github-copilot-app-adapter.md +2 -2
  50. package/skills/pmx-canvas/references/installing-pmx-canvas.md +7 -7
  51. package/src/client/canvas/BoardCopyDialog.tsx +2 -1
  52. package/src/client/canvas/KnowledgeDialog.tsx +3 -0
  53. package/src/client/canvas/LifecyclePanel.tsx +4 -0
  54. package/src/client/canvas/RelationPresetsDialog.tsx +2 -0
  55. package/src/client/canvas/ToolRail.tsx +2 -0
  56. package/src/client/canvas/submit-without-navigation.ts +14 -0
  57. package/src/client/state/canvas-store.ts +12 -24
  58. package/src/client/state/intent-bridge.ts +0 -6
  59. package/src/client/state/presence-store.ts +3 -3
  60. package/src/client/state/sse-bridge.ts +11 -6
  61. package/src/client/theme/global.css +12 -17
  62. package/src/mcp/canvas-access.ts +6 -47
  63. package/src/mcp/resource-subscriptions.ts +181 -0
  64. package/src/mcp/server.ts +185 -219
  65. package/src/server/ax-wait.ts +21 -6
  66. package/src/server/canvas-operations.ts +6 -2
  67. package/src/server/canvas-state.ts +10 -0
  68. package/src/server/index.ts +20 -32
  69. package/src/server/knowledge-lifecycle.ts +66 -0
  70. package/src/server/lifecycle-status.ts +79 -7
  71. package/src/server/operations/http.ts +69 -21
  72. package/src/server/operations/index.ts +8 -1
  73. package/src/server/operations/invoker.ts +53 -5
  74. package/src/server/operations/mcp-contracts.ts +339 -0
  75. package/src/server/operations/mcp.ts +153 -18
  76. package/src/server/operations/ops/ax-await.ts +18 -10
  77. package/src/server/operations/ops/ax-read.ts +2 -0
  78. package/src/server/operations/ops/ax-timeline.ts +2 -2
  79. package/src/server/operations/ops/batch.ts +27 -8
  80. package/src/server/operations/ops/lifecycle.ts +3 -7
  81. package/src/server/operations/ops/nodes.ts +20 -8
  82. package/src/server/operations/ops/viewport.ts +3 -7
  83. package/src/server/operations/registry.ts +24 -4
  84. package/src/server/operations/types.ts +16 -2
  85. package/src/server/server.ts +23 -10
  86. package/src/server/tour-control.ts +17 -8
  87. package/src/server/webpage-node.ts +9 -4
@@ -1,27 +1,27 @@
1
- var nE=Object.create;var{getPrototypeOf:oE,defineProperty:Kg,getOwnPropertyNames:rE}=Object;var Vg=Object.prototype.hasOwnProperty;function iE(e){return this[e]}var sE,aE,lE=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var i=t?sE??=new WeakMap:aE??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?nE(oE(e)):{};let a=t||!e||!e.__esModule||!Vg.call(e,"default")?Kg(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of rE(e))if(!Vg.call(a,l))Kg(a,l,{get:iE.bind(e,l),enumerable:!0})}if(o)i.set(e,a);return a};var cE=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var h0=cE(function(m0){Object.defineProperty(m0,"__esModule",{value:!0});var e0=/highlight-(?:text|source)-([a-z0-9]+)/;function n0(e){e.addRule("highlightedCodeBlock",{filter:function(t){var n=t.firstChild;return t.nodeName==="DIV"&&e0.test(t.className)&&n&&n.nodeName==="PRE"},replacement:function(t,n,o){var i=n.className||"",s=(i.match(e0)||[null,""])[1];return`
1
+ var nE=Object.create;var{getPrototypeOf:oE,defineProperty:Xg,getOwnPropertyNames:rE}=Object;var Jg=Object.prototype.hasOwnProperty;function iE(e){return this[e]}var sE,aE,lE=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var i=t?sE??=new WeakMap:aE??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?nE(oE(e)):{};let a=t||!e||!e.__esModule||!Jg.call(e,"default")?Xg(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of rE(e))if(!Jg.call(a,l))Xg(a,l,{get:iE.bind(e,l),enumerable:!0})}if(o)i.set(e,a);return a};var cE=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var m0=cE(function(f0){Object.defineProperty(f0,"__esModule",{value:!0});var QS=/highlight-(?:text|source)-([a-z0-9]+)/;function t0(e){e.addRule("highlightedCodeBlock",{filter:function(t){var n=t.firstChild;return t.nodeName==="DIV"&&QS.test(t.className)&&n&&n.nodeName==="PRE"},replacement:function(t,n,o){var i=n.className||"",s=(i.match(QS)||[null,""])[1];return`
2
2
 
3
3
  `+o.fence+s+`
4
4
  `+n.firstChild.textContent+`
5
5
  `+o.fence+`
6
6
 
7
- `}})}function o0(e){e.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(t){return"~~"+t+"~~"}})}var d1=Array.prototype.indexOf,p1=Array.prototype.every,si={},f1={left:":---",right:"---:",center:":---:"},$m=null,r0=null,t0=new WeakMap;function m1(e){return e?(e.getAttribute("align")||e.style.textAlign||"").toLowerCase():""}function i0(e){return e?f1[e]:"---"}function s0(e,t){var n={left:0,right:0,center:0,"":0},o="";for(var i=0;i<e.rows.length;++i){var s=e.rows[i];if(t<s.childNodes.length){var a=m1(s.childNodes[t]);if(++n[a],n[a]>n[o])o=a}}return o}si.tableCell={filter:["th","td"],replacement:function(e,t){if(Om(u0(t)))return e;return a0(e,t)}};si.tableRow={filter:"tr",replacement:function(e,t){let n=u0(t);if(Om(n))return e;var o="";if(h1(t)){let a=d0(n);for(var i=0;i<a;i++){let l=i<t.childNodes.length?t.childNodes[i]:null;var s=i0(s0(n,i));o+=a0(s,l,i)}}return`
7
+ `}})}function n0(e){e.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(t){return"~~"+t+"~~"}})}var d1=Array.prototype.indexOf,p1=Array.prototype.every,si={},f1={left:":---",right:"---:",center:":---:"},Dm=null,o0=null,e0=new WeakMap;function m1(e){return e?(e.getAttribute("align")||e.style.textAlign||"").toLowerCase():""}function r0(e){return e?f1[e]:"---"}function i0(e,t){var n={left:0,right:0,center:0,"":0},o="";for(var i=0;i<e.rows.length;++i){var s=e.rows[i];if(t<s.childNodes.length){var a=m1(s.childNodes[t]);if(++n[a],n[a]>n[o])o=a}}return o}si.tableCell={filter:["th","td"],replacement:function(e,t){if(Fm(c0(t)))return e;return s0(e,t)}};si.tableRow={filter:"tr",replacement:function(e,t){let n=c0(t);if(Fm(n))return e;var o="";if(h1(t)){let a=u0(n);for(var i=0;i<a;i++){let l=i<t.childNodes.length?t.childNodes[i]:null;var s=r0(i0(n,i));o+=s0(s,l,i)}}return`
8
8
  `+e+(o?`
9
- `+o:"")}};si.table={filter:function(e,t){return e.nodeName==="TABLE"},replacement:function(e,t){if(c0(t,r0)){let l=t.outerHTML,c=v1(t);if(c===null||!c.classList.contains("joplin-table-wrapper"))return`
9
+ `+o:"")}};si.table={filter:function(e,t){return e.nodeName==="TABLE"},replacement:function(e,t){if(l0(t,o0)){let l=t.outerHTML,c=v1(t);if(c===null||!c.classList.contains("joplin-table-wrapper"))return`
10
10
 
11
11
  <div class="joplin-table-wrapper">${l}</div>
12
12
 
13
- `;else return l}else{if(Om(t))return e;e=e.replace(/\n+/g,`
13
+ `;else return l}else{if(Fm(t))return e;e=e.replace(/\n+/g,`
14
14
  `);var n=e.trim().split(`
15
- `);if(n.length>=2)n=n[1];var o=/\| :?---/.test(n),i=d0(t),s="";if(i&&!o){s="|"+" |".repeat(i)+`
16
- |`;for(var a=0;a<i;++a)s+=" "+i0(s0(t,a))+" |"}let l=t.caption?t.caption.textContent||"":"",c=l?`${l}
15
+ `);if(n.length>=2)n=n[1];var o=/\| :?---/.test(n),i=u0(t),s="";if(i&&!o){s="|"+" |".repeat(i)+`
16
+ |`;for(var a=0;a<i;++a)s+=" "+r0(i0(t,a))+" |"}let l=t.caption?t.caption.textContent||"":"",c=l?`${l}
17
17
 
18
18
  `:"",u=`${s}${e}`.trimStart();return`
19
19
 
20
20
  ${c}${u}
21
21
 
22
- `}}};si.tableCaption={filter:["caption"],replacement:()=>""};si.tableColgroup={filter:["colgroup","col"],replacement:()=>""};si.tableSection={filter:["thead","tbody","tfoot"],replacement:function(e){return e}};function h1(e){var t=e.parentNode;return t.nodeName==="THEAD"||t.firstChild===e&&(t.nodeName==="TABLE"||g1(t))&&p1.call(e.childNodes,function(n){return n.nodeName==="TH"})}function g1(e){var t=e.previousSibling;return e.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function a0(e,t=null,n=null){if(n===null)n=d1.call(t.parentNode.childNodes,t);var o=" ";if(n===0)o="| ";let i=e.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");i=i.replace(/\|+/g,"\\|");while(i.length<3)i+=" ";if(t)i=b1(i,t," ");return o+i+" |"}function l0(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(l0(n))return!0}return!1}var Lm=(e,t)=>{if(!e.childNodes)return!1;for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(t==="code"&&$m&&$m(o))return!0;if(t.includes(o.nodeName))return!0;if(Lm(o,t))return!0}return!1},c0=(e,t)=>{let n=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];if(t.preserveNestedTables)n.push("TABLE");return Lm(e,"code")||Lm(e,n)};function Om(e){let t=t0.get(e);if(t!==void 0)return t;let n=y1(e);return t0.set(e,n),n}function y1(e){if(!e)return!0;if(!e.rows)return!0;if(e.rows.length===1&&e.rows[0].childNodes.length<=1)return!0;if(l0(e))return!0;return!1}function v1(e){let t=e.parentNode;while(t.nodeName!=="DIV")if(t=t.parentNode,!t)return null;return t}function u0(e){let t=e.parentNode;while(t.nodeName!=="TABLE")if(t=t.parentNode,!t)return null;return t}function b1(e,t,n){let o=t.getAttribute("colspan")||1;for(let i=1;i<o;i++)e+=" | "+n.repeat(3);return e}function d0(e){let t=0;for(let n=0;n<e.rows.length;n++){let i=e.rows[n].childNodes.length;if(i>t)t=i}return t}function p0(e){$m=e.isCodeBlock,r0=e.options,e.keep(function(n){if(n.nodeName==="TABLE"&&c0(n,e.options))return!0;return!1});for(var t in si)e.addRule(t,si[t])}function f0(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 x1(e){e.use([n0,o0,p0,f0])}m0.gfm=x1;m0.highlightedCodeBlock=n0;m0.strikethrough=o0;m0.tables=p0;m0.taskListItems=f0});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 xc,ct,ey,Cp,Dr,Xg,ty,ny,oy,Tp,kp,Sp,uE,yc={},vc=[],dE=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,wc=Array.isArray;function dr(e,t){for(var n in t)e[n]=t[n];return e}function Ip(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function pE(e,t,n){var o,i,s,a={};for(s in t)s=="key"?o=t[s]:s=="ref"?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?xc.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 gc(e,a,o,i,null)}function gc(e,t,n,o,i){var s={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i==null?++ey:i,__i:-1,__u:0};return i==null&&ct.vnode!=null&&ct.vnode(s),s}function be(e){return e.children}function Br(e,t){this.props=e,this.context=t}function ys(e,t){if(t==null)return e.__?ys(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"?ys(e):null}function fE(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,o=[],i=[],s=dr({},t);s.__v=t.__v+1,ct.vnode&&ct.vnode(s),Ep(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,o,n==null?ys(t):n,!!(32&t.__u),i),s.__v=t.__v,s.__.__k[s.__i]=s,ay(o,s,i),t.__e=t.__=null,s.__e!=n&&ry(s)}}function ry(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}),ry(e)}function Jg(e){(!e.__d&&(e.__d=!0)&&Dr.push(e)&&!bc.__r++||Xg!=ct.debounceRendering)&&((Xg=ct.debounceRendering)||ty)(bc)}function bc(){try{for(var e,t=1;Dr.length;)Dr.length>t&&Dr.sort(ny),e=Dr.shift(),t=Dr.length,fE(e)}finally{Dr.length=bc.__r=0}}function iy(e,t,n,o,i,s,a,l,c,u,d){var p,f,m,h,g,v,b,x=o&&o.__k||vc,C=t.length;for(c=mE(n,t,x,c,C),p=0;p<C;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&x[m.__i]||yc,m.__i=p,v=Ep(e,m,f,i,s,a,l,c,u,d),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Ap(f.ref,null,m),d.push(m.ref,m.__c||h,m)),g==null&&h!=null&&(g=h),(b=!!(4&m.__u))||f.__k===m.__k?c=sy(m,c,e,b):typeof m.type=="function"&&v!==void 0?c=v:h&&(c=h.nextSibling),m.__u&=-7);return n.__e=g,c}function mE(e,t,n,o,i){var s,a,l,c,u,d=n.length,p=d,f=0;for(e.__k=Array(i),s=0;s<i;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]=gc(null,a,null,null,null):wc(a)?a=e.__k[s]=gc(be,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=e.__k[s]=gc(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,c=s+f,a.__=e,a.__b=e.__b+1,l=null,(u=a.__i=hE(a,n,c,p))!=-1&&(p--,(l=n[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(i>d?f--:i<d&&f++),typeof a.type!="function"&&(a.__u|=4)):u!=c&&(u==c-1?f--:u==c+1?f++:(u>c?f--:f++,a.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==o&&(o=ys(l)),cy(l,l));return o}function sy(e,t,n,o){var i,s;if(typeof e.type=="function"){for(i=e.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=e,t=sy(i[s],t,n,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=ys(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function hE(e,t,n,o){var i,s,a,{key:l,type:c}=e,u=t[n],d=u!=null&&(2&u.__u)==0;if(u===null&&l==null||d&&l==u.key&&c==u.type)return n;if(o>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<t.length;)if((u=t[a=i>=0?i--:s++])!=null&&(2&u.__u)==0&&l==u.key&&c==u.type)return a}return-1}function Yg(e,t,n){t[0]=="-"?e.setProperty(t,n==null?"":n):e[t]=n==null?"":typeof n!="number"||dE.test(t)?n:n+"px"}function hc(e,t,n,o,i){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||Yg(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||Yg(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(oy,"$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=Tp,e.addEventListener(t,s?Sp:kp,s)):e.removeEventListener(t,s?Sp:kp,s);else{if(i=="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(l){}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Qg(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=Tp++;else if(t.t<n.u)return;return n(ct.event?ct.event(t):t)}}}function Ep(e,t,n,o,i,s,a,l,c,u){var d,p,f,m,h,g,v,b,x,C,y,k,_,I,w,P=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),s=[l=t.__e=n.__e]),(d=ct.__b)&&d(t);e:if(typeof P=="function")try{if(b=t.props,x=P.prototype&&P.prototype.render,C=(d=P.contextType)&&o[d.__c],y=d?C?C.props.value:d.__:o,n.__c?v=(p=t.__c=n.__c).__=p.__E:(x?t.__c=p=new P(b,y):(t.__c=p=new Br(b,y),p.constructor=P,p.render=yE),C&&C.sub(p),p.state||(p.state={}),p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),x&&p.__s==null&&(p.__s=p.state),x&&P.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=dr({},p.__s)),dr(p.__s,P.getDerivedStateFromProps(b,p.__s))),m=p.props,h=p.state,p.__v=t,f)x&&P.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),x&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(x&&P.getDerivedStateFromProps==null&&b!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(b,y),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(b,p.__s,y)===!1){t.__v!=n.__v&&(p.props=b,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(L){L&&(L.__=t)}),vc.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&a.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(b,p.__s,y),x&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,h,g)})}if(p.context=y,p.props=b,p.__P=e,p.__e=!1,k=ct.__r,_=0,x)p.state=p.__s,p.__d=!1,k&&k(t),d=p.render(p.props,p.state,p.context),vc.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,k&&k(t),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++_<25);p.state=p.__s,p.getChildContext!=null&&(o=dr(dr({},o),p.getChildContext())),x&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),I=d!=null&&d.type===be&&d.key==null?ly(d.props.children):d,l=iy(e,wc(I)?I:[I],t,n,o,i,s,a,l,c,u),p.base=t.__e,t.__u&=-161,p.__h.length&&a.push(p),v&&(p.__E=p.__=null)}catch(L){if(t.__v=null,c||s!=null)if(L.then){for(t.__u|=c?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,t.__e=l}else{for(w=s.length;w--;)Ip(s[w]);_p(t)}else t.__e=n.__e,t.__k=n.__k,L.then||_p(t);ct.__e(L,t,n)}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=gE(n.__e,t,n,o,i,s,a,c,u);return(d=ct.diffed)&&d(t),128&t.__u?void 0:l}function _p(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(_p))}function ay(e,t,n){for(var o=0;o<n.length;o++)Ap(n[o],n[++o],n[++o]);ct.__c&&ct.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(s){s.call(i)})}catch(s){ct.__e(s,i.__v)}})}function ly(e){return typeof e!="object"||e==null||e.__b>0?e:wc(e)?e.map(ly):dr({},e)}function gE(e,t,n,o,i,s,a,l,c){var u,d,p,f,m,h,g,v=n.props||yc,{props:b,type:x}=t;if(x=="svg"?i="http://www.w3.org/2000/svg":x=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((m=s[u])&&"setAttribute"in m==!!x&&(x?m.localName==x:m.nodeType==3)){e=m,s[u]=null;break}}if(e==null){if(x==null)return document.createTextNode(b);e=document.createElementNS(i,x,b.is&&b),l&&(ct.__m&&ct.__m(t,s),l=!1),s=null}if(x==null)v===b||l&&e.data==b||(e.data=b);else{if(s=s&&xc.call(e.childNodes),!l&&s!=null)for(v={},u=0;u<e.attributes.length;u++)v[(m=e.attributes[u]).name]=m.value;for(u in v)m=v[u],u=="dangerouslySetInnerHTML"?p=m:u=="children"||(u in b)||u=="value"&&("defaultValue"in b)||u=="checked"&&("defaultChecked"in b)||hc(e,u,null,m,i);for(u in b)m=b[u],u=="children"?f=m:u=="dangerouslySetInnerHTML"?d=m:u=="value"?h=m:u=="checked"?g=m:l&&typeof m!="function"||v[u]===m||hc(e,u,m,v[u],i);if(d)l||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),iy(t.type=="template"?e.content:e,wc(f)?f:[f],t,n,o,x=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,a,s?s[0]:n.__k&&ys(n,0),l,c),s!=null)for(u=s.length;u--;)Ip(s[u]);l||(u="value",x=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[u]||x=="progress"&&!h||x=="option"&&h!=v[u])&&hc(e,u,h,v[u],i),u="checked",g!=null&&g!=e[u]&&hc(e,u,g,v[u],i))}return e}function Ap(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(i){ct.__e(i,n)}}function cy(e,t,n){var o,i;if(ct.unmount&&ct.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Ap(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){ct.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(i=0;i<o.length;i++)o[i]&&cy(o[i],t,n||typeof e.type!="function");n||Ip(e.__e),e.__c=e.__=e.__e=void 0}function yE(e,t,n){return this.constructor(e,n)}function Aa(e,t,n){var o,i,s,a;t==document&&(t=document.documentElement),ct.__&&ct.__(e,t),i=(o=typeof n=="function")?null:n&&n.__k||t.__k,s=[],a=[],Ep(t,e=(!o&&n||t).__k=pE(be,null,[e]),i||yc,yc,t.namespaceURI,!o&&n?[n]:i?null:t.firstChild?xc.call(t.childNodes):null,s,!o&&n?n:i?i.__e:t.firstChild,o,a),ay(s,e,a)}xc=vc.slice,ct={__e:function(e,t,n,o){for(var i,s,a;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&s.getDerivedStateFromError!=null&&(i.setState(s.getDerivedStateFromError(e)),a=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,o||{}),a=i.__d),a)return i.__E=i}catch(l){e=l}throw e}},ey=0,Cp=function(e){return e!=null&&e.constructor===void 0},Br.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=dr({},this.state),typeof e=="function"&&(e=e(dr({},n),this.props)),e&&dr(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Jg(this))},Br.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Jg(this))},Br.prototype.render=be,Dr=[],ty=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ny=function(e,t){return e.__v.__b-t.__v.__b},bc.__r=0,oy=/(PointerCapture)$|Capture$/i,Tp=0,kp=Qg(!1),Sp=Qg(!0),uE=0;var _i,Zt,Rp,uy,Ra=0,vy=[],Vt=ct,{__b:dy,__r:py,diffed:fy,__c:my,unmount:hy,__:gy}=Vt;function Pa(e,t){Vt.__h&&Vt.__h(Zt,e,Ra||t),Ra=0;var n=Zt.__H||(Zt.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function E(e){return Ra=1,vE(xy,e)}function vE(e,t,n){var o=Pa(_i++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):xy(void 0,t),function(l){var c=o.__N?o.__N[0]:o.__[0],u=o.t(c,l);c!==u&&(o.__N=[u,o.__[1]],o.__c.setState({}))}],o.__c=Zt,!Zt.__f)){var i=function(l,c,u){if(!o.__c.__H)return!0;var d=o.__c.__H.__.filter(function(f){return f.__c});if(d.every(function(f){return!f.__N}))return!s||s.call(this,l,c,u);var p=o.__c.props!==l;return d.some(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),s&&s.call(this,l,c,u)||p};Zt.__f=!0;var s=Zt.shouldComponentUpdate,a=Zt.componentWillUpdate;Zt.componentWillUpdate=function(l,c,u){if(this.__e){var d=s;s=void 0,i(l,c,u),s=d}a&&a.call(this,l,c,u)},Zt.shouldComponentUpdate=i}return o.__N||o.__}function q(e,t){var n=Pa(_i++,3);!Vt.__s&&Np(n.__H,t)&&(n.__=e,n.u=t,Zt.__H.__h.push(n))}function Me(e,t){var n=Pa(_i++,4);!Vt.__s&&Np(n.__H,t)&&(n.__=e,n.u=t,Zt.__h.push(n))}function D(e){return Ra=5,Ke(function(){return{current:e}},[])}function Ke(e,t){var n=Pa(_i++,7);return Np(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function oe(e,t){return Ra=8,Ke(function(){return e},t)}function by(){var e=Pa(_i++,11);if(!e.__){for(var t=Zt.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function bE(){for(var e;e=vy.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(kc),t.__h.some(Pp),t.__h=[]}catch(n){t.__h=[],Vt.__e(n,e.__v)}}}Vt.__b=function(e){Zt=null,dy&&dy(e)},Vt.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),gy&&gy(e,t)},Vt.__r=function(e){py&&py(e),_i=0;var t=(Zt=e.__c).__H;t&&(Rp===Zt?(t.__h=[],Zt.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(kc),t.__h.some(Pp),t.__h=[],_i=0)),Rp=Zt},Vt.diffed=function(e){fy&&fy(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(vy.push(t)!==1&&uy===Vt.requestAnimationFrame||((uy=Vt.requestAnimationFrame)||xE)(bE)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Rp=Zt=null},Vt.__c=function(e,t){t.some(function(n){try{n.__h.some(kc),n.__h=n.__h.filter(function(o){return!o.__||Pp(o)})}catch(o){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Vt.__e(o,n.__v)}}),my&&my(e,t)},Vt.unmount=function(e){hy&&hy(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(o){try{kc(o)}catch(i){t=i}}),n.__H=void 0,t&&Vt.__e(t,n.__v))};var yy=typeof requestAnimationFrame=="function";function xE(e){var t,n=function(){clearTimeout(o),yy&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);yy&&(t=requestAnimationFrame(n))}function kc(e){var t=Zt,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Zt=t}function Pp(e){var t=Zt;e.__c=e.__(),Zt=t}function Np(e,t){return!e||e.length!==t.length||t.some(function(n,o){return n!==e[o]})}function xy(e,t){return typeof t=="function"?t(e):t}var wE=Symbol.for("preact-signals");function Tc(){if(!(pr>1)){var e,t=!1;(function(){var i=_c;_c=void 0;while(i!==void 0){if(i.S.v===i.v)i.S.i=i.i;i=i.o}})();while(Na!==void 0){var n=Na;Na=void 0,Sc++;while(n!==void 0){var o=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Sy(n))try{n.c()}catch(i){if(!t)e=i,t=!0}n=o}}if(Sc=0,pr--,t)throw e}else pr--}function Nn(e){if(pr>0)return e();Mp=++kE,pr++;try{return e()}finally{Tc()}}var mt=void 0;function zp(e){var t=mt;mt=void 0;try{return e()}finally{mt=t}}var wy,Na=void 0,pr=0,Sc=0,kE=0,Mp=0,_c=void 0,Cc=0;function ky(e){if(mt!==void 0){var t=e.n;if(t===void 0||t.t!==mt){if(t={i:0,S:e,p:mt.s,n:void 0,t:mt,e:void 0,x:void 0,r:t},mt.s!==void 0)mt.s.n=t;if(mt.s=t,e.n=t,32&mt.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=mt.s,t.n=void 0,mt.s.n=t,mt.s=t}return t}}}function rn(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}rn.prototype.brand=wE;rn.prototype.h=function(){return!0};rn.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 zp(function(){var o;(o=t.W)==null||o.call(t)})};rn.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)zp(function(){var i;(i=t.Z)==null||i.call(t)})}}};rn.prototype.subscribe=function(e){var t=this;return sn(function(){var n=t.value,o=mt;mt=void 0;try{e(n)}finally{mt=o}},{name:"sub"})};rn.prototype.valueOf=function(){return this.value};rn.prototype.toString=function(){return this.value+""};rn.prototype.toJSON=function(){return this.value};rn.prototype.peek=function(){var e=mt;mt=void 0;try{return this.value}finally{mt=e}};Object.defineProperty(rn.prototype,"value",{get:function(){var e=ky(this);if(e!==void 0)e.i=this.i;return this.v},set:function(e){if(e!==this.v){if(Sc>100)throw Error("Cycle detected");(function(n){if(pr!==0&&Sc===0){if(n.l!==Mp)n.l=Mp,_c={S:n,v:n.v,i:n.i,o:_c}}})(this),this.v=e,this.i++,Cc++,pr++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Tc()}}}});function ie(e,t){return new rn(e,t)}function Sy(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 _y(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 Cy(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 Ci(e,t){rn.call(this,void 0),this.x=e,this.s=void 0,this.g=Cc-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}Ci.prototype=new rn;Ci.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===Cc)return!0;if(this.g=Cc,this.f|=1,this.i>0&&!Sy(this))return this.f&=-2,!0;var e=mt;try{_y(this),mt=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 mt=e,Cy(this),this.f&=-2,!0};Ci.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)}rn.prototype.S.call(this,e)};Ci.prototype.U=function(e){if(this.t!==void 0){if(rn.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)}}};Ci.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(Ci.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=ky(this);if(this.h(),e!==void 0)e.i=this.i;if(16&this.f)throw this.v;return this.v}});function Ve(e,t){return new Ci(e,t)}function Ty(e){var t=e.m;if(e.m=void 0,typeof t=="function"){pr++;var n=mt;mt=void 0;try{t()}catch(o){throw e.f&=-2,e.f|=8,$p(e),o}finally{mt=n,Tc()}}}function $p(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Ty(e)}function SE(e){if(mt!==this)throw Error("Out-of-order effect");if(Cy(this),mt=e,this.f&=-2,8&this.f)$p(this);Tc()}function vs(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,wy)wy.push(this)}vs.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()}};vs.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,Ty(this),_y(this),pr++;var e=mt;return mt=this,SE.bind(this,e)};vs.prototype.N=function(){if(!(2&this.f))this.f|=2,this.u=Na,Na=this};vs.prototype.d=function(){if(this.f|=8,!(1&this.f))$p(this)};vs.prototype.dispose=function(){this.d()};function sn(e,t){var n=new vs(e,t);try{n.c()}catch(i){throw n.d(),i}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Iy,Lp,Ic,_E=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__;var Ey=[];sn(function(){Iy=this.N})();function bs(e,t){ct[e]=t.bind(null,ct[e]||function(){})}function Ec(e){if(Ic){var t=Ic;Ic=void 0,t()}Ic=e&&e.S()}function Ay(e){var t=this,n=e.data,o=TE(n);o.value=n;var i=Ke(function(){var l=t,c=t.__v;while(c=c.__)if(c.__c){c.__c.__$f|=4;break}var u=Ve(function(){var m=o.value.value;return m===0?0:m===!0?"":m||""}),d=Ve(function(){return!Array.isArray(u.value)&&!Cp(u.value)}),p=sn(function(){if(this.N=Ry,d.value){var m=u.value;if(l.__v&&l.__v.__e&&l.__v.__e.nodeType===3)l.__v.__e.data=m}}),f=t.__$u.d;return t.__$u.d=function(){p(),f.call(this)},[d,u]},[]),s=i[0],a=i[1];return s.value?a.peek():a.value}Ay.displayName="ReactiveTextNode";Object.defineProperties(rn.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ay},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}});bs("__b",function(e,t){if(typeof t.type=="string"){var n,o=t.props;for(var i in o)if(i!=="children"){var s=o[i];if(s instanceof rn){if(!n)t.__np=n={};n[i]=s,o[i]=s.peek()}}}e(t)});bs("__r",function(e,t){if(e(t),t.type!==be){Ec();var n,o=t.__c;if(o){if(o.__$f&=-2,(n=o.__$u)===void 0)o.__$u=n=function(i,s){var a;return sn(function(){a=this},{name:s}),a.c=i,a}(function(){var i;if(_E)(i=n.y)==null||i.call(n);o.__$f|=1,o.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:"")}Lp=o,Ec(n)}});bs("__e",function(e,t,n,o){Ec(),Lp=void 0,e(t,n,o)});bs("diffed",function(e,t){Ec(),Lp=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var{__np:o,props:i}=t;if(o){var s=n.U;if(s)for(var a in s){var l=s[a];if(l!==void 0&&!(a in o))l.d(),s[a]=void 0}else s={},n.U=s;for(var c in o){var u=s[c],d=o[c];if(u===void 0)u=CE(n,c,d),s[c]=u;else u.o(d,i)}for(var p in o)i[p]=o[p]}}e(t)});function CE(e,t,n,o){var i=t in e&&e.ownerSVGElement===void 0,s=ie(n),a=n.peek();return{o:function(l,c){s.value=l,a=l.peek()},d:sn(function(){this.N=Ry;var l=s.value.value;if(a!==l)if(a=void 0,i)e[t]=l;else if(l!=null&&(l!==!1||t[4]==="-"))e.setAttribute(t,l);else e.removeAttribute(t);else a=void 0})}}bs("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 i in o){var s=o[i];if(s)s.d()}}}t.__np=void 0}else{var a=t.__c;if(a){var l=a.__$u;if(l)a.__$u=void 0,l.d()}}e(t)});bs("__h",function(e,t,n,o){if(o<3||o===9)t.__$f|=2;e(t,n,o)});Br.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var i 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 l in this.props)if(!(l in e))return!0;return!1};function TE(e,t){return Ke(function(){return ie(e,t)},[])}var IE=function(e){queueMicrotask(function(){queueMicrotask(e)})};function EE(){Nn(function(){var e;while(e=Ey.shift())Iy.call(e)})}function Ry(){if(Ey.push(this)===1)(ct.requestAnimationFrame||IE)(EE)}var vD=Object.freeze({status:"aborted"});function Q(e,t,n){function o(l,c){if(!l._zod)Object.defineProperty(l,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1});if(l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,c);let u=a.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){let f=d[p];if(!(f in l))l[f]=u[f].bind(l)}}let i=n?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function a(l){var c;let u=n?.Parent?new s:this;o(u,l),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:(l)=>{if(n?.Parent&&l instanceof n.Parent)return!0;return l?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}var bD=Symbol("zod_brand");class fr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ma extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}var Ac={};function yo(e){if(e)Object.assign(Ac,e);return Ac}function Pc(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,i])=>t.indexOf(+o)===-1).map(([o,i])=>i)}function Dp(e,t="|"){return e.map((n)=>Up(n)).join(t)}function za(e,t){if(typeof t==="bigint")return t.toString();return t}function $a(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Nc(e){return e===null||e===void 0}function Mc(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ny(e,t){let n=(e.toString().split(".")[1]||"").length,o=t.toString(),i=(o.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(o)){let c=o.match(/\d?e-(\d?)/);if(c?.[1])i=Number.parseInt(c[1])}let s=n>i?n:i,a=Number.parseInt(e.toFixed(s).replace(".","")),l=Number.parseInt(t.toFixed(s).replace(".",""));return a%l/10**s}var Py=Symbol("evaluating");function dt(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===Py)return;if(o===void 0)o=Py,o=n();return o},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ti(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Fr(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Bp(e){return JSON.stringify(e)}function My(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Fp="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function xs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var zy=$a(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ii(e){if(xs(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(xs(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Hp(e){if(Ii(e))return{...e};if(Array.isArray(e))return[...e];return e}var $y=new Set(["string","number","symbol"]);function Hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jo(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function Re(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 Up(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Ly(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Oy={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 AE(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=Fr(e._zod.def,{get shape(){let a={};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;a[l]=n.shape[l]}return Ti(this,"shape",a),a},checks:[]});return jo(e,s)}function RE(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=Fr(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;delete a[l]}return Ti(this,"shape",a),a},checks:[]});return jo(e,s)}function PE(e,t){if(!Ii(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 i=Fr(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Ti(this,"shape",s),s}});return jo(e,i)}function NE(e,t){if(!Ii(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Fr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Ti(this,"shape",o),o}});return jo(e,n)}function ME(e,t){let n=Fr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Ti(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return jo(e,n)}function zE(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=Fr(t._zod.def,{get shape(){let l=t._zod.def.shape,c={...l};if(n)for(let u in n){if(!(u in l))throw Error(`Unrecognized key: "${u}"`);if(!n[u])continue;c[u]=e?new e({type:"optional",innerType:l[u]}):l[u]}else for(let u in l)c[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return Ti(this,"shape",c),c},checks:[]});return jo(t,a)}function $E(e,t,n){let o=Fr(t._zod.def,{get shape(){let i=t._zod.def.shape,s={...i};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:i[a]})}else for(let a in i)s[a]=new e({type:"nonoptional",innerType:i[a]});return Ti(this,"shape",s),s}});return jo(t,o)}function Ei(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 Ur(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Rc(e){return typeof e==="string"?e:e?.message}function Zo(e,t,n){let o={...e,path:e.path??[]};if(!e.message){let i=Rc(e.inst?._zod.def?.error?.(e))??Rc(t?.error?.(e))??Rc(n.customError?.(e))??Rc(n.localeError?.(e))??"Invalid input";o.message=i}if(delete o.inst,delete o.continue,!t?.reportInput)delete o.input;return o}function zc(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Dy(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 Ai(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}var By=(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,za,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$c=Q("$ZodError",By),jp=Q("$ZodError",By,{Parent:Error});function Fy(e,t=(n)=>n.message){let n={},o=[];for(let i of e.issues)if(i.path.length>0)n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i));else o.push(t(i));return{formErrors:o,fieldErrors:n}}function Hy(e,t=(n)=>n.message){let n={_errors:[]},o=(i)=>{for(let s of i.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,l=0;while(l<s.path.length){let c=s.path[l];if(l!==s.path.length-1)a[c]=a[c]||{_errors:[]};else a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(s));a=a[c],l++}}};return o(e),n}var Lc=(e)=>(t,n,o,i)=>{let s=o?Object.assign(o,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new fr;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((c)=>Zo(c,s,yo())));throw Fp(l,i?.callee),l}return a.value};var Oc=(e)=>async(t,n,o,i)=>{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 l=new(i?.Err??e)(a.issues.map((c)=>Zo(c,s,yo())));throw Fp(l,i?.callee),l}return a.value};var La=(e)=>(t,n,o)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new fr;return s.issues.length?{success:!1,error:new(e??$c)(s.issues.map((a)=>Zo(a,i,yo())))}:{success:!0,data:s.value}},Oa=La(jp),Da=(e)=>async(t,n,o)=>{let i=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>Zo(a,i,yo())))}:{success:!0,data:s.value}},Dc=Da(jp),Uy=(e)=>(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Lc(e)(t,n,i)};var jy=(e)=>(t,n,o)=>Lc(e)(t,n,o);var Zy=(e)=>async(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Oc(e)(t,n,i)};var Wy=(e)=>async(t,n,o)=>Oc(e)(t,n,o);var qy=(e)=>(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return La(e)(t,n,i)};var Gy=(e)=>(t,n,o)=>La(e)(t,n,o);var Ky=(e)=>async(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Da(e)(t,n,i)};var Vy=(e)=>async(t,n,o)=>Da(e)(t,n,o);var Xy=/^[cC][^\s-]{8,}$/,Jy=/^[0-9a-z]+$/,Yy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Qy=/^[0-9a-vA-V]{20}$/,ev=/^[A-Za-z0-9]{27}$/,tv=/^[a-zA-Z0-9_-]{21}$/,nv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ov=/^([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})$/,Zp=(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 rv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var OE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function iv(){return new RegExp(OE,"u")}var sv=/^(?:(?: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])$/,av=/^(([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 lv=/^((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])$/,cv=/^(([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])$/,uv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wp=/^[A-Za-z0-9_-]*$/;var dv=/^\+[1-9]\d{6,14}$/,pv="(?:(?:\\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])))",fv=new RegExp(`^${pv}$`);function mv(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 hv(e){return new RegExp(`^${mv(e)}$`)}function gv(e){let t=mv({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(`^${pv}T(?:${o})$`)}var yv=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var vv=/^-?\d+$/,qp=/^-?\d+(?:\.\d+)?$/,bv=/^(?:true|false)$/i,xv=/^null$/i;var wv=/^undefined$/i;var kv=/^[^A-Z]*$/,Sv=/^[^a-z]*$/;var wn=Q("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_v={number:"number",bigint:"bigint",object:"date"},Gp=Q("$ZodCheckLessThan",(e,t)=>{wn.init(e,t);let n=_v[typeof t.value];e._zod.onattach.push((o)=>{let i=o._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)i.maximum=t.value;else i.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})}}),Kp=Q("$ZodCheckGreaterThan",(e,t)=>{wn.init(e,t);let n=_v[typeof t.value];e._zod.onattach.push((o)=>{let i=o._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)i.minimum=t.value;else i.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})}}),Cv=Q("$ZodCheckMultipleOf",(e,t)=>{wn.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):Ny(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})}}),Tv=Q("$ZodCheckNumberFormat",(e,t)=>{wn.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[i,s]=Oy[t.format];e._zod.onattach.push((a)=>{let l=a._zod.bag;if(l.format=t.format,l.minimum=i,l.maximum=s,n)l.pattern=vv}),e._zod.check=(a)=>{let l=a.value;if(n){if(!Number.isInteger(l)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){if(l>0)a.issues.push({input:l,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:l,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(l<i)a.issues.push({origin:"number",input:l,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(l>s)a.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Iv=Q("$ZodCheckMaxLength",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let i=o.value;return!Nc(i)&&i.length!==void 0}),e._zod.onattach.push((o)=>{let i=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<i)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let i=o.value;if(i.length<=t.maximum)return;let a=zc(i);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ev=Q("$ZodCheckMinLength",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let i=o.value;return!Nc(i)&&i.length!==void 0}),e._zod.onattach.push((o)=>{let i=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>i)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let i=o.value;if(i.length>=t.minimum)return;let a=zc(i);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Av=Q("$ZodCheckLengthEquals",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let i=o.value;return!Nc(i)&&i.length!==void 0}),e._zod.onattach.push((o)=>{let i=o._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=(o)=>{let i=o.value,s=i.length;if(s===t.length)return;let a=zc(i),l=s>t.length;o.issues.push({origin:a,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ba=Q("$ZodCheckStringFormat",(e,t)=>{var n,o;if(wn.init(e,t),e._zod.onattach.push((i)=>{let s=i._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=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),Rv=Q("$ZodCheckRegex",(e,t)=>{Ba.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})}}),Pv=Q("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=kv),Ba.init(e,t)}),Nv=Q("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Sv),Ba.init(e,t)}),Mv=Q("$ZodCheckIncludes",(e,t)=>{wn.init(e,t);let n=Hr(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=o,e._zod.onattach.push((i)=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),zv=Q("$ZodCheckStartsWith",(e,t)=>{wn.init(e,t);let n=new RegExp(`^${Hr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),$v=Q("$ZodCheckEndsWith",(e,t)=>{wn.init(e,t);let n=new RegExp(`.*${Hr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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 Lv=Q("$ZodCheckOverwrite",(e,t)=>{wn.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Vp{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
+ `}}};si.tableCaption={filter:["caption"],replacement:()=>""};si.tableColgroup={filter:["colgroup","col"],replacement:()=>""};si.tableSection={filter:["thead","tbody","tfoot"],replacement:function(e){return e}};function h1(e){var t=e.parentNode;return t.nodeName==="THEAD"||t.firstChild===e&&(t.nodeName==="TABLE"||g1(t))&&p1.call(e.childNodes,function(n){return n.nodeName==="TH"})}function g1(e){var t=e.previousSibling;return e.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function s0(e,t=null,n=null){if(n===null)n=d1.call(t.parentNode.childNodes,t);var o=" ";if(n===0)o="| ";let i=e.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");i=i.replace(/\|+/g,"\\|");while(i.length<3)i+=" ";if(t)i=b1(i,t," ");return o+i+" |"}function a0(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(a0(n))return!0}return!1}var Bm=(e,t)=>{if(!e.childNodes)return!1;for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];if(t==="code"&&Dm&&Dm(o))return!0;if(t.includes(o.nodeName))return!0;if(Bm(o,t))return!0}return!1},l0=(e,t)=>{let n=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];if(t.preserveNestedTables)n.push("TABLE");return Bm(e,"code")||Bm(e,n)};function Fm(e){let t=e0.get(e);if(t!==void 0)return t;let n=y1(e);return e0.set(e,n),n}function y1(e){if(!e)return!0;if(!e.rows)return!0;if(e.rows.length===1&&e.rows[0].childNodes.length<=1)return!0;if(a0(e))return!0;return!1}function v1(e){let t=e.parentNode;while(t.nodeName!=="DIV")if(t=t.parentNode,!t)return null;return t}function c0(e){let t=e.parentNode;while(t.nodeName!=="TABLE")if(t=t.parentNode,!t)return null;return t}function b1(e,t,n){let o=t.getAttribute("colspan")||1;for(let i=1;i<o;i++)e+=" | "+n.repeat(3);return e}function u0(e){let t=0;for(let n=0;n<e.rows.length;n++){let i=e.rows[n].childNodes.length;if(i>t)t=i}return t}function d0(e){Dm=e.isCodeBlock,o0=e.options,e.keep(function(n){if(n.nodeName==="TABLE"&&l0(n,e.options))return!0;return!1});for(var t in si)e.addRule(t,si[t])}function p0(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 x1(e){e.use([t0,n0,d0,p0])}f0.gfm=x1;f0.highlightedCodeBlock=t0;f0.strikethrough=n0;f0.tables=d0;f0.taskListItems=p0});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 xc,ct,ny,Tp,Dr,Yg,oy,ry,iy,Ip,Sp,_p,uE,yc={},vc=[],dE=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,wc=Array.isArray;function dr(e,t){for(var n in t)e[n]=t[n];return e}function Ep(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function pE(e,t,n){var o,i,s,a={};for(s in t)s=="key"?o=t[s]:s=="ref"?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?xc.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 gc(e,a,o,i,null)}function gc(e,t,n,o,i){var s={type:e,props:t,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i==null?++ny:i,__i:-1,__u:0};return i==null&&ct.vnode!=null&&ct.vnode(s),s}function be(e){return e.children}function Br(e,t){this.props=e,this.context=t}function ys(e,t){if(t==null)return e.__?ys(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"?ys(e):null}function fE(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,o=[],i=[],s=dr({},t);s.__v=t.__v+1,ct.vnode&&ct.vnode(s),Ap(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,o,n==null?ys(t):n,!!(32&t.__u),i),s.__v=t.__v,s.__.__k[s.__i]=s,cy(o,s,i),t.__e=t.__=null,s.__e!=n&&sy(s)}}function sy(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}),sy(e)}function Qg(e){(!e.__d&&(e.__d=!0)&&Dr.push(e)&&!bc.__r++||Yg!=ct.debounceRendering)&&((Yg=ct.debounceRendering)||oy)(bc)}function bc(){try{for(var e,t=1;Dr.length;)Dr.length>t&&Dr.sort(ry),e=Dr.shift(),t=Dr.length,fE(e)}finally{Dr.length=bc.__r=0}}function ay(e,t,n,o,i,s,a,l,c,u,d){var p,f,m,h,g,v,b,x=o&&o.__k||vc,C=t.length;for(c=mE(n,t,x,c,C),p=0;p<C;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&x[m.__i]||yc,m.__i=p,v=Ap(e,m,f,i,s,a,l,c,u,d),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Rp(f.ref,null,m),d.push(m.ref,m.__c||h,m)),g==null&&h!=null&&(g=h),(b=!!(4&m.__u))||f.__k===m.__k?c=ly(m,c,e,b):typeof m.type=="function"&&v!==void 0?c=v:h&&(c=h.nextSibling),m.__u&=-7);return n.__e=g,c}function mE(e,t,n,o,i){var s,a,l,c,u,d=n.length,p=d,f=0;for(e.__k=Array(i),s=0;s<i;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]=gc(null,a,null,null,null):wc(a)?a=e.__k[s]=gc(be,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=e.__k[s]=gc(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,c=s+f,a.__=e,a.__b=e.__b+1,l=null,(u=a.__i=hE(a,n,c,p))!=-1&&(p--,(l=n[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(i>d?f--:i<d&&f++),typeof a.type!="function"&&(a.__u|=4)):u!=c&&(u==c-1?f--:u==c+1?f++:(u>c?f--:f++,a.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==o&&(o=ys(l)),dy(l,l));return o}function ly(e,t,n,o){var i,s;if(typeof e.type=="function"){for(i=e.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=e,t=ly(i[s],t,n,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=ys(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function hE(e,t,n,o){var i,s,a,{key:l,type:c}=e,u=t[n],d=u!=null&&(2&u.__u)==0;if(u===null&&l==null||d&&l==u.key&&c==u.type)return n;if(o>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<t.length;)if((u=t[a=i>=0?i--:s++])!=null&&(2&u.__u)==0&&l==u.key&&c==u.type)return a}return-1}function ey(e,t,n){t[0]=="-"?e.setProperty(t,n==null?"":n):e[t]=n==null?"":typeof n!="number"||dE.test(t)?n:n+"px"}function hc(e,t,n,o,i){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||ey(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||ey(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(iy,"$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=Ip,e.addEventListener(t,s?_p:Sp,s)):e.removeEventListener(t,s?_p:Sp,s);else{if(i=="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(l){}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function ty(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t.t==null)t.t=Ip++;else if(t.t<n.u)return;return n(ct.event?ct.event(t):t)}}}function Ap(e,t,n,o,i,s,a,l,c,u){var d,p,f,m,h,g,v,b,x,C,y,k,_,I,w,P=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),s=[l=t.__e=n.__e]),(d=ct.__b)&&d(t);e:if(typeof P=="function")try{if(b=t.props,x=P.prototype&&P.prototype.render,C=(d=P.contextType)&&o[d.__c],y=d?C?C.props.value:d.__:o,n.__c?v=(p=t.__c=n.__c).__=p.__E:(x?t.__c=p=new P(b,y):(t.__c=p=new Br(b,y),p.constructor=P,p.render=yE),C&&C.sub(p),p.state||(p.state={}),p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),x&&p.__s==null&&(p.__s=p.state),x&&P.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=dr({},p.__s)),dr(p.__s,P.getDerivedStateFromProps(b,p.__s))),m=p.props,h=p.state,p.__v=t,f)x&&P.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),x&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(x&&P.getDerivedStateFromProps==null&&b!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(b,y),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(b,p.__s,y)===!1){t.__v!=n.__v&&(p.props=b,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(L){L&&(L.__=t)}),vc.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&a.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(b,p.__s,y),x&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,h,g)})}if(p.context=y,p.props=b,p.__P=e,p.__e=!1,k=ct.__r,_=0,x)p.state=p.__s,p.__d=!1,k&&k(t),d=p.render(p.props,p.state,p.context),vc.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,k&&k(t),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++_<25);p.state=p.__s,p.getChildContext!=null&&(o=dr(dr({},o),p.getChildContext())),x&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),I=d!=null&&d.type===be&&d.key==null?uy(d.props.children):d,l=ay(e,wc(I)?I:[I],t,n,o,i,s,a,l,c,u),p.base=t.__e,t.__u&=-161,p.__h.length&&a.push(p),v&&(p.__E=p.__=null)}catch(L){if(t.__v=null,c||s!=null)if(L.then){for(t.__u|=c?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,t.__e=l}else{for(w=s.length;w--;)Ep(s[w]);Cp(t)}else t.__e=n.__e,t.__k=n.__k,L.then||Cp(t);ct.__e(L,t,n)}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=gE(n.__e,t,n,o,i,s,a,c,u);return(d=ct.diffed)&&d(t),128&t.__u?void 0:l}function Cp(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Cp))}function cy(e,t,n){for(var o=0;o<n.length;o++)Rp(n[o],n[++o],n[++o]);ct.__c&&ct.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(s){s.call(i)})}catch(s){ct.__e(s,i.__v)}})}function uy(e){return typeof e!="object"||e==null||e.__b>0?e:wc(e)?e.map(uy):dr({},e)}function gE(e,t,n,o,i,s,a,l,c){var u,d,p,f,m,h,g,v=n.props||yc,{props:b,type:x}=t;if(x=="svg"?i="http://www.w3.org/2000/svg":x=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((m=s[u])&&"setAttribute"in m==!!x&&(x?m.localName==x:m.nodeType==3)){e=m,s[u]=null;break}}if(e==null){if(x==null)return document.createTextNode(b);e=document.createElementNS(i,x,b.is&&b),l&&(ct.__m&&ct.__m(t,s),l=!1),s=null}if(x==null)v===b||l&&e.data==b||(e.data=b);else{if(s=s&&xc.call(e.childNodes),!l&&s!=null)for(v={},u=0;u<e.attributes.length;u++)v[(m=e.attributes[u]).name]=m.value;for(u in v)m=v[u],u=="dangerouslySetInnerHTML"?p=m:u=="children"||(u in b)||u=="value"&&("defaultValue"in b)||u=="checked"&&("defaultChecked"in b)||hc(e,u,null,m,i);for(u in b)m=b[u],u=="children"?f=m:u=="dangerouslySetInnerHTML"?d=m:u=="value"?h=m:u=="checked"?g=m:l&&typeof m!="function"||v[u]===m||hc(e,u,m,v[u],i);if(d)l||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),ay(t.type=="template"?e.content:e,wc(f)?f:[f],t,n,o,x=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,a,s?s[0]:n.__k&&ys(n,0),l,c),s!=null)for(u=s.length;u--;)Ep(s[u]);l||(u="value",x=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[u]||x=="progress"&&!h||x=="option"&&h!=v[u])&&hc(e,u,h,v[u],i),u="checked",g!=null&&g!=e[u]&&hc(e,u,g,v[u],i))}return e}function Rp(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(i){ct.__e(i,n)}}function dy(e,t,n){var o,i;if(ct.unmount&&ct.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Rp(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){ct.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(i=0;i<o.length;i++)o[i]&&dy(o[i],t,n||typeof e.type!="function");n||Ep(e.__e),e.__c=e.__=e.__e=void 0}function yE(e,t,n){return this.constructor(e,n)}function Ra(e,t,n){var o,i,s,a;t==document&&(t=document.documentElement),ct.__&&ct.__(e,t),i=(o=typeof n=="function")?null:n&&n.__k||t.__k,s=[],a=[],Ap(t,e=(!o&&n||t).__k=pE(be,null,[e]),i||yc,yc,t.namespaceURI,!o&&n?[n]:i?null:t.firstChild?xc.call(t.childNodes):null,s,!o&&n?n:i?i.__e:t.firstChild,o,a),cy(s,e,a)}xc=vc.slice,ct={__e:function(e,t,n,o){for(var i,s,a;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&s.getDerivedStateFromError!=null&&(i.setState(s.getDerivedStateFromError(e)),a=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,o||{}),a=i.__d),a)return i.__E=i}catch(l){e=l}throw e}},ny=0,Tp=function(e){return e!=null&&e.constructor===void 0},Br.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=dr({},this.state),typeof e=="function"&&(e=e(dr({},n),this.props)),e&&dr(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Qg(this))},Br.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Qg(this))},Br.prototype.render=be,Dr=[],oy=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ry=function(e,t){return e.__v.__b-t.__v.__b},bc.__r=0,iy=/(PointerCapture)$|Capture$/i,Ip=0,Sp=ty(!1),_p=ty(!0),uE=0;var _i,Zt,Pp,py,Pa=0,xy=[],Vt=ct,{__b:fy,__r:my,diffed:hy,__c:gy,unmount:yy,__:vy}=Vt;function Na(e,t){Vt.__h&&Vt.__h(Zt,e,Pa||t),Pa=0;var n=Zt.__H||(Zt.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function E(e){return Pa=1,vE(ky,e)}function vE(e,t,n){var o=Na(_i++,2);if(o.t=e,!o.__c&&(o.__=[n?n(t):ky(void 0,t),function(l){var c=o.__N?o.__N[0]:o.__[0],u=o.t(c,l);c!==u&&(o.__N=[u,o.__[1]],o.__c.setState({}))}],o.__c=Zt,!Zt.__f)){var i=function(l,c,u){if(!o.__c.__H)return!0;var d=o.__c.__H.__.filter(function(f){return f.__c});if(d.every(function(f){return!f.__N}))return!s||s.call(this,l,c,u);var p=o.__c.props!==l;return d.some(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),s&&s.call(this,l,c,u)||p};Zt.__f=!0;var s=Zt.shouldComponentUpdate,a=Zt.componentWillUpdate;Zt.componentWillUpdate=function(l,c,u){if(this.__e){var d=s;s=void 0,i(l,c,u),s=d}a&&a.call(this,l,c,u)},Zt.shouldComponentUpdate=i}return o.__N||o.__}function q(e,t){var n=Na(_i++,3);!Vt.__s&&Mp(n.__H,t)&&(n.__=e,n.u=t,Zt.__H.__h.push(n))}function Me(e,t){var n=Na(_i++,4);!Vt.__s&&Mp(n.__H,t)&&(n.__=e,n.u=t,Zt.__h.push(n))}function D(e){return Pa=5,Ke(function(){return{current:e}},[])}function Ke(e,t){var n=Na(_i++,7);return Mp(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function oe(e,t){return Pa=8,Ke(function(){return e},t)}function wy(){var e=Na(_i++,11);if(!e.__){for(var t=Zt.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function bE(){for(var e;e=xy.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(kc),t.__h.some(Np),t.__h=[]}catch(n){t.__h=[],Vt.__e(n,e.__v)}}}Vt.__b=function(e){Zt=null,fy&&fy(e)},Vt.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),vy&&vy(e,t)},Vt.__r=function(e){my&&my(e),_i=0;var t=(Zt=e.__c).__H;t&&(Pp===Zt?(t.__h=[],Zt.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(kc),t.__h.some(Np),t.__h=[],_i=0)),Pp=Zt},Vt.diffed=function(e){hy&&hy(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(xy.push(t)!==1&&py===Vt.requestAnimationFrame||((py=Vt.requestAnimationFrame)||xE)(bE)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Pp=Zt=null},Vt.__c=function(e,t){t.some(function(n){try{n.__h.some(kc),n.__h=n.__h.filter(function(o){return!o.__||Np(o)})}catch(o){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Vt.__e(o,n.__v)}}),gy&&gy(e,t)},Vt.unmount=function(e){yy&&yy(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(o){try{kc(o)}catch(i){t=i}}),n.__H=void 0,t&&Vt.__e(t,n.__v))};var by=typeof requestAnimationFrame=="function";function xE(e){var t,n=function(){clearTimeout(o),by&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);by&&(t=requestAnimationFrame(n))}function kc(e){var t=Zt,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Zt=t}function Np(e){var t=Zt;e.__c=e.__(),Zt=t}function Mp(e,t){return!e||e.length!==t.length||t.some(function(n,o){return n!==e[o]})}function ky(e,t){return typeof t=="function"?t(e):t}var wE=Symbol.for("preact-signals");function Tc(){if(!(pr>1)){var e,t=!1;(function(){var i=_c;_c=void 0;while(i!==void 0){if(i.S.v===i.v)i.S.i=i.i;i=i.o}})();while(Ma!==void 0){var n=Ma;Ma=void 0,Sc++;while(n!==void 0){var o=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Cy(n))try{n.c()}catch(i){if(!t)e=i,t=!0}n=o}}if(Sc=0,pr--,t)throw e}else pr--}function Nn(e){if(pr>0)return e();zp=++kE,pr++;try{return e()}finally{Tc()}}var mt=void 0;function $p(e){var t=mt;mt=void 0;try{return e()}finally{mt=t}}var Sy,Ma=void 0,pr=0,Sc=0,kE=0,zp=0,_c=void 0,Cc=0;function _y(e){if(mt!==void 0){var t=e.n;if(t===void 0||t.t!==mt){if(t={i:0,S:e,p:mt.s,n:void 0,t:mt,e:void 0,x:void 0,r:t},mt.s!==void 0)mt.s.n=t;if(mt.s=t,e.n=t,32&mt.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=mt.s,t.n=void 0,mt.s.n=t,mt.s=t}return t}}}function rn(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}rn.prototype.brand=wE;rn.prototype.h=function(){return!0};rn.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 $p(function(){var o;(o=t.W)==null||o.call(t)})};rn.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)$p(function(){var i;(i=t.Z)==null||i.call(t)})}}};rn.prototype.subscribe=function(e){var t=this;return sn(function(){var n=t.value,o=mt;mt=void 0;try{e(n)}finally{mt=o}},{name:"sub"})};rn.prototype.valueOf=function(){return this.value};rn.prototype.toString=function(){return this.value+""};rn.prototype.toJSON=function(){return this.value};rn.prototype.peek=function(){var e=mt;mt=void 0;try{return this.value}finally{mt=e}};Object.defineProperty(rn.prototype,"value",{get:function(){var e=_y(this);if(e!==void 0)e.i=this.i;return this.v},set:function(e){if(e!==this.v){if(Sc>100)throw Error("Cycle detected");(function(n){if(pr!==0&&Sc===0){if(n.l!==zp)n.l=zp,_c={S:n,v:n.v,i:n.i,o:_c}}})(this),this.v=e,this.i++,Cc++,pr++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Tc()}}}});function ie(e,t){return new rn(e,t)}function Cy(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 Ty(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 Iy(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 Ci(e,t){rn.call(this,void 0),this.x=e,this.s=void 0,this.g=Cc-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}Ci.prototype=new rn;Ci.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===Cc)return!0;if(this.g=Cc,this.f|=1,this.i>0&&!Cy(this))return this.f&=-2,!0;var e=mt;try{Ty(this),mt=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 mt=e,Iy(this),this.f&=-2,!0};Ci.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)}rn.prototype.S.call(this,e)};Ci.prototype.U=function(e){if(this.t!==void 0){if(rn.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)}}};Ci.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(Ci.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=_y(this);if(this.h(),e!==void 0)e.i=this.i;if(16&this.f)throw this.v;return this.v}});function Ve(e,t){return new Ci(e,t)}function Ey(e){var t=e.m;if(e.m=void 0,typeof t=="function"){pr++;var n=mt;mt=void 0;try{t()}catch(o){throw e.f&=-2,e.f|=8,Lp(e),o}finally{mt=n,Tc()}}}function Lp(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Ey(e)}function SE(e){if(mt!==this)throw Error("Out-of-order effect");if(Iy(this),mt=e,this.f&=-2,8&this.f)Lp(this);Tc()}function vs(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,Sy)Sy.push(this)}vs.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()}};vs.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,Ey(this),Ty(this),pr++;var e=mt;return mt=this,SE.bind(this,e)};vs.prototype.N=function(){if(!(2&this.f))this.f|=2,this.u=Ma,Ma=this};vs.prototype.d=function(){if(this.f|=8,!(1&this.f))Lp(this)};vs.prototype.dispose=function(){this.d()};function sn(e,t){var n=new vs(e,t);try{n.c()}catch(i){throw n.d(),i}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Ay,Op,Ic,_E=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__;var Ry=[];sn(function(){Ay=this.N})();function bs(e,t){ct[e]=t.bind(null,ct[e]||function(){})}function Ec(e){if(Ic){var t=Ic;Ic=void 0,t()}Ic=e&&e.S()}function Py(e){var t=this,n=e.data,o=TE(n);o.value=n;var i=Ke(function(){var l=t,c=t.__v;while(c=c.__)if(c.__c){c.__c.__$f|=4;break}var u=Ve(function(){var m=o.value.value;return m===0?0:m===!0?"":m||""}),d=Ve(function(){return!Array.isArray(u.value)&&!Tp(u.value)}),p=sn(function(){if(this.N=Ny,d.value){var m=u.value;if(l.__v&&l.__v.__e&&l.__v.__e.nodeType===3)l.__v.__e.data=m}}),f=t.__$u.d;return t.__$u.d=function(){p(),f.call(this)},[d,u]},[]),s=i[0],a=i[1];return s.value?a.peek():a.value}Py.displayName="ReactiveTextNode";Object.defineProperties(rn.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Py},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}});bs("__b",function(e,t){if(typeof t.type=="string"){var n,o=t.props;for(var i in o)if(i!=="children"){var s=o[i];if(s instanceof rn){if(!n)t.__np=n={};n[i]=s,o[i]=s.peek()}}}e(t)});bs("__r",function(e,t){if(e(t),t.type!==be){Ec();var n,o=t.__c;if(o){if(o.__$f&=-2,(n=o.__$u)===void 0)o.__$u=n=function(i,s){var a;return sn(function(){a=this},{name:s}),a.c=i,a}(function(){var i;if(_E)(i=n.y)==null||i.call(n);o.__$f|=1,o.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:"")}Op=o,Ec(n)}});bs("__e",function(e,t,n,o){Ec(),Op=void 0,e(t,n,o)});bs("diffed",function(e,t){Ec(),Op=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var{__np:o,props:i}=t;if(o){var s=n.U;if(s)for(var a in s){var l=s[a];if(l!==void 0&&!(a in o))l.d(),s[a]=void 0}else s={},n.U=s;for(var c in o){var u=s[c],d=o[c];if(u===void 0)u=CE(n,c,d),s[c]=u;else u.o(d,i)}for(var p in o)i[p]=o[p]}}e(t)});function CE(e,t,n,o){var i=t in e&&e.ownerSVGElement===void 0,s=ie(n),a=n.peek();return{o:function(l,c){s.value=l,a=l.peek()},d:sn(function(){this.N=Ny;var l=s.value.value;if(a!==l)if(a=void 0,i)e[t]=l;else if(l!=null&&(l!==!1||t[4]==="-"))e.setAttribute(t,l);else e.removeAttribute(t);else a=void 0})}}bs("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 i in o){var s=o[i];if(s)s.d()}}}t.__np=void 0}else{var a=t.__c;if(a){var l=a.__$u;if(l)a.__$u=void 0,l.d()}}e(t)});bs("__h",function(e,t,n,o){if(o<3||o===9)t.__$f|=2;e(t,n,o)});Br.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var i 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 l in this.props)if(!(l in e))return!0;return!1};function TE(e,t){return Ke(function(){return ie(e,t)},[])}var IE=function(e){queueMicrotask(function(){queueMicrotask(e)})};function EE(){Nn(function(){var e;while(e=Ry.shift())Ay.call(e)})}function Ny(){if(Ry.push(this)===1)(ct.requestAnimationFrame||IE)(EE)}var vD=Object.freeze({status:"aborted"});function Q(e,t,n){function o(l,c){if(!l._zod)Object.defineProperty(l,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1});if(l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,c);let u=a.prototype,d=Object.keys(u);for(let p=0;p<d.length;p++){let f=d[p];if(!(f in l))l[f]=u[f].bind(l)}}let i=n?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function a(l){var c;let u=n?.Parent?new s:this;o(u,l),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:(l)=>{if(n?.Parent&&l instanceof n.Parent)return!0;return l?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}var bD=Symbol("zod_brand");class fr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class za extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}var Ac={};function yo(e){if(e)Object.assign(Ac,e);return Ac}function Pc(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,i])=>t.indexOf(+o)===-1).map(([o,i])=>i)}function Bp(e,t="|"){return e.map((n)=>jp(n)).join(t)}function $a(e,t){if(typeof t==="bigint")return t.toString();return t}function La(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Nc(e){return e===null||e===void 0}function Mc(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function zy(e,t){let n=(e.toString().split(".")[1]||"").length,o=t.toString(),i=(o.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(o)){let c=o.match(/\d?e-(\d?)/);if(c?.[1])i=Number.parseInt(c[1])}let s=n>i?n:i,a=Number.parseInt(e.toFixed(s).replace(".","")),l=Number.parseInt(t.toFixed(s).replace(".",""));return a%l/10**s}var My=Symbol("evaluating");function dt(e,t,n){let o=void 0;Object.defineProperty(e,t,{get(){if(o===My)return;if(o===void 0)o=My,o=n();return o},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Ti(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Fr(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Fp(e){return JSON.stringify(e)}function $y(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Hp="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function xs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ly=La(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ii(e){if(xs(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(xs(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Up(e){if(Ii(e))return{...e};if(Array.isArray(e))return[...e];return e}var Oy=new Set(["string","number","symbol"]);function Hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jo(e,t,n){let o=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)o._zod.parent=e;return o}function Re(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 jp(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Dy(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var By={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 AE(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=Fr(e._zod.def,{get shape(){let a={};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;a[l]=n.shape[l]}return Ti(this,"shape",a),a},checks:[]});return jo(e,s)}function RE(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=Fr(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let l in t){if(!(l in n.shape))throw Error(`Unrecognized key: "${l}"`);if(!t[l])continue;delete a[l]}return Ti(this,"shape",a),a},checks:[]});return jo(e,s)}function PE(e,t){if(!Ii(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 i=Fr(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Ti(this,"shape",s),s}});return jo(e,i)}function NE(e,t){if(!Ii(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Fr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Ti(this,"shape",o),o}});return jo(e,n)}function ME(e,t){let n=Fr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Ti(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:[]});return jo(e,n)}function zE(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=Fr(t._zod.def,{get shape(){let l=t._zod.def.shape,c={...l};if(n)for(let u in n){if(!(u in l))throw Error(`Unrecognized key: "${u}"`);if(!n[u])continue;c[u]=e?new e({type:"optional",innerType:l[u]}):l[u]}else for(let u in l)c[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return Ti(this,"shape",c),c},checks:[]});return jo(t,a)}function $E(e,t,n){let o=Fr(t._zod.def,{get shape(){let i=t._zod.def.shape,s={...i};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:i[a]})}else for(let a in i)s[a]=new e({type:"nonoptional",innerType:i[a]});return Ti(this,"shape",s),s}});return jo(t,o)}function Ei(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 Ur(e,t){return t.map((n)=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Rc(e){return typeof e==="string"?e:e?.message}function Zo(e,t,n){let o={...e,path:e.path??[]};if(!e.message){let i=Rc(e.inst?._zod.def?.error?.(e))??Rc(t?.error?.(e))??Rc(n.customError?.(e))??Rc(n.localeError?.(e))??"Invalid input";o.message=i}if(delete o.inst,delete o.continue,!t?.reportInput)delete o.input;return o}function zc(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Fy(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 Ai(...e){let[t,n,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:o};return{...t}}var Hy=(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,$a,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$c=Q("$ZodError",Hy),Zp=Q("$ZodError",Hy,{Parent:Error});function Uy(e,t=(n)=>n.message){let n={},o=[];for(let i of e.issues)if(i.path.length>0)n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i));else o.push(t(i));return{formErrors:o,fieldErrors:n}}function jy(e,t=(n)=>n.message){let n={_errors:[]},o=(i)=>{for(let s of i.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,l=0;while(l<s.path.length){let c=s.path[l];if(l!==s.path.length-1)a[c]=a[c]||{_errors:[]};else a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(s));a=a[c],l++}}};return o(e),n}var Lc=(e)=>(t,n,o,i)=>{let s=o?Object.assign(o,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new fr;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((c)=>Zo(c,s,yo())));throw Hp(l,i?.callee),l}return a.value};var Oc=(e)=>async(t,n,o,i)=>{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 l=new(i?.Err??e)(a.issues.map((c)=>Zo(c,s,yo())));throw Hp(l,i?.callee),l}return a.value};var Oa=(e)=>(t,n,o)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new fr;return s.issues.length?{success:!1,error:new(e??$c)(s.issues.map((a)=>Zo(a,i,yo())))}:{success:!0,data:s.value}},Da=Oa(Zp),Ba=(e)=>async(t,n,o)=>{let i=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>Zo(a,i,yo())))}:{success:!0,data:s.value}},Dc=Ba(Zp),Zy=(e)=>(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Lc(e)(t,n,i)};var Wy=(e)=>(t,n,o)=>Lc(e)(t,n,o);var qy=(e)=>async(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Oc(e)(t,n,i)};var Gy=(e)=>async(t,n,o)=>Oc(e)(t,n,o);var Ky=(e)=>(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Oa(e)(t,n,i)};var Vy=(e)=>(t,n,o)=>Oa(e)(t,n,o);var Xy=(e)=>async(t,n,o)=>{let i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Ba(e)(t,n,i)};var Jy=(e)=>async(t,n,o)=>Ba(e)(t,n,o);var Yy=/^[cC][^\s-]{8,}$/,Qy=/^[0-9a-z]+$/,ev=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tv=/^[0-9a-vA-V]{20}$/,nv=/^[A-Za-z0-9]{27}$/,ov=/^[a-zA-Z0-9_-]{21}$/,rv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var iv=/^([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})$/,Wp=(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 sv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var OE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function av(){return new RegExp(OE,"u")}var lv=/^(?:(?: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])$/,cv=/^(([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 uv=/^((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])$/,dv=/^(([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])$/,pv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qp=/^[A-Za-z0-9_-]*$/;var fv=/^\+[1-9]\d{6,14}$/,mv="(?:(?:\\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])))",hv=new RegExp(`^${mv}$`);function gv(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 yv(e){return new RegExp(`^${gv(e)}$`)}function vv(e){let t=gv({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(`^${mv}T(?:${o})$`)}var bv=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var xv=/^-?\d+$/,Gp=/^-?\d+(?:\.\d+)?$/,wv=/^(?:true|false)$/i,kv=/^null$/i;var Sv=/^undefined$/i;var _v=/^[^A-Z]*$/,Cv=/^[^a-z]*$/;var wn=Q("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Tv={number:"number",bigint:"bigint",object:"date"},Kp=Q("$ZodCheckLessThan",(e,t)=>{wn.init(e,t);let n=Tv[typeof t.value];e._zod.onattach.push((o)=>{let i=o._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)i.maximum=t.value;else i.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})}}),Vp=Q("$ZodCheckGreaterThan",(e,t)=>{wn.init(e,t);let n=Tv[typeof t.value];e._zod.onattach.push((o)=>{let i=o._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)i.minimum=t.value;else i.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})}}),Iv=Q("$ZodCheckMultipleOf",(e,t)=>{wn.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):zy(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})}}),Ev=Q("$ZodCheckNumberFormat",(e,t)=>{wn.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),o=n?"int":"number",[i,s]=By[t.format];e._zod.onattach.push((a)=>{let l=a._zod.bag;if(l.format=t.format,l.minimum=i,l.maximum=s,n)l.pattern=xv}),e._zod.check=(a)=>{let l=a.value;if(n){if(!Number.isInteger(l)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){if(l>0)a.issues.push({input:l,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:l,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(l<i)a.issues.push({origin:"number",input:l,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(l>s)a.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Av=Q("$ZodCheckMaxLength",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let i=o.value;return!Nc(i)&&i.length!==void 0}),e._zod.onattach.push((o)=>{let i=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<i)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let i=o.value;if(i.length<=t.maximum)return;let a=zc(i);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Rv=Q("$ZodCheckMinLength",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let i=o.value;return!Nc(i)&&i.length!==void 0}),e._zod.onattach.push((o)=>{let i=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>i)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let i=o.value;if(i.length>=t.minimum)return;let a=zc(i);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Pv=Q("$ZodCheckLengthEquals",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=(o)=>{let i=o.value;return!Nc(i)&&i.length!==void 0}),e._zod.onattach.push((o)=>{let i=o._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=(o)=>{let i=o.value,s=i.length;if(s===t.length)return;let a=zc(i),l=s>t.length;o.issues.push({origin:a,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Fa=Q("$ZodCheckStringFormat",(e,t)=>{var n,o;if(wn.init(e,t),e._zod.onattach.push((i)=>{let s=i._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=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),Nv=Q("$ZodCheckRegex",(e,t)=>{Fa.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})}}),Mv=Q("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=_v),Fa.init(e,t)}),zv=Q("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Cv),Fa.init(e,t)}),$v=Q("$ZodCheckIncludes",(e,t)=>{wn.init(e,t);let n=Hr(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=o,e._zod.onattach.push((i)=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Lv=Q("$ZodCheckStartsWith",(e,t)=>{wn.init(e,t);let n=new RegExp(`^${Hr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Ov=Q("$ZodCheckEndsWith",(e,t)=>{wn.init(e,t);let n=new RegExp(`.*${Hr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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 Dv=Q("$ZodCheckOverwrite",(e,t)=>{wn.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Xp{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)),i=n.map((s)=>s.slice(o)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((i)=>` ${i}`)];return new e(...t,o.join(`
24
- `))}}var Dv={major:4,minor:3,patch:6};var Et=Q("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Dv;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let i of o)for(let s of i._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 i=(a,l,c)=>{let u=Ei(a),d;for(let p of l){if(p._zod.def.when){if(!p._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,m=p._zod.check(a);if(m instanceof Promise&&c?.async===!1)throw new fr;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await m,a.issues.length===f)return;if(!u)u=Ei(a,f)});else{if(a.issues.length===f)continue;if(!u)u=Ei(a,f)}}if(d)return d.then(()=>a);return a},s=(a,l,c)=>{if(Ei(a))return a.aborted=!0,a;let u=i(l,o,c);if(u instanceof Promise){if(c.async===!1)throw new fr;return u.then((d)=>e._zod.parse(d,c))}return e._zod.parse(u,c)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,a,l));return s(u,a,l)}let c=e._zod.parse(a,l);if(c instanceof Promise){if(l.async===!1)throw new fr;return c.then((u)=>i(u,o,l))}return i(c,o,l)}}dt(e,"~standard",()=>({validate:(i)=>{try{let s=Oa(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Dc(e,i).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Uc=Q("$ZodString",(e,t)=>{Et.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yv(e._zod.bag),e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Pt=Q("$ZodStringFormat",(e,t)=>{Ba.init(e,t),Uc.init(e,t)}),Gv=Q("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ov),Pt.init(e,t)}),Kv=Q("$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=Zp(o))}else t.pattern??(t.pattern=Zp());Pt.init(e,t)}),Vv=Q("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=rv),Pt.init(e,t)}),Xv=Q("$ZodURL",(e,t)=>{Pt.init(e,t),e._zod.check=(n)=>{try{let o=n.value.trim(),i=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(i.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(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=i.href;else n.value=o;return}catch(o){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Jv=Q("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=iv()),Pt.init(e,t)}),Yv=Q("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=tv),Pt.init(e,t)}),Qv=Q("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Xy),Pt.init(e,t)}),eb=Q("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Jy),Pt.init(e,t)}),tb=Q("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Yy),Pt.init(e,t)}),nb=Q("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Qy),Pt.init(e,t)}),ob=Q("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ev),Pt.init(e,t)}),rb=Q("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=gv(t)),Pt.init(e,t)}),ib=Q("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fv),Pt.init(e,t)}),sb=Q("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hv(t)),Pt.init(e,t)}),ab=Q("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nv),Pt.init(e,t)}),lb=Q("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=sv),Pt.init(e,t),e._zod.bag.format="ipv4"}),cb=Q("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=av),Pt.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 ub=Q("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=lv),Pt.init(e,t)}),db=Q("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cv),Pt.init(e,t),e._zod.check=(n)=>{let o=n.value.split("/");try{if(o.length!==2)throw Error();let[i,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://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function pb(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var fb=Q("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=uv),Pt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(pb(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function FE(e){if(!Wp.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return pb(n)}var mb=Q("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Wp),Pt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(FE(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),hb=Q("$ZodE164",(e,t)=>{t.pattern??(t.pattern=dv),Pt.init(e,t)});function HE(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let i=JSON.parse(atob(o));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var gb=Q("$ZodJWT",(e,t)=>{Pt.init(e,t),e._zod.check=(n)=>{if(HE(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Jp=Q("$ZodNumber",(e,t)=>{Et.init(e,t),e._zod.pattern=e._zod.bag.pattern??qp,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let s=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),n}}),yb=Q("$ZodNumberFormat",(e,t)=>{Tv.init(e,t),Jp.init(e,t)}),vb=Q("$ZodBoolean",(e,t)=>{Et.init(e,t),e._zod.pattern=bv,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}});var bb=Q("$ZodUndefined",(e,t)=>{Et.init(e,t),e._zod.pattern=wv,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,o)=>{let i=n.value;if(typeof i>"u")return n;return n.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),n}}),xb=Q("$ZodNull",(e,t)=>{Et.init(e,t),e._zod.pattern=xv,e._zod.values=new Set([null]),e._zod.parse=(n,o)=>{let i=n.value;if(i===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}});var wb=Q("$ZodUnknown",(e,t)=>{Et.init(e,t),e._zod.parse=(n)=>n}),kb=Q("$ZodNever",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Bv(e,t,n){if(e.issues.length)t.issues.push(...Ur(n,e.issues));t.value[n]=e.value}var Sb=Q("$ZodArray",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let s=[];for(let a=0;a<i.length;a++){let l=i[a],c=t.element._zod.run({value:l,issues:[]},o);if(c instanceof Promise)s.push(c.then((u)=>Bv(u,n,a)));else Bv(c,n,a)}if(s.length)return Promise.all(s).then(()=>n);return n}});function Hc(e,t,n,o,i){if(e.issues.length){if(i&&!(n in o))return;t.issues.push(...Ur(n,e.issues))}if(e.value===void 0){if(n in o)t.value[n]=void 0}else t.value[n]=e.value}function _b(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=Ly(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Cb(e,t,n,o,i,s){let a=[],l=i.keySet,c=i.catchall._zod,u=c.def.type,d=c.optout==="optional";for(let p in t){if(l.has(p))continue;if(u==="never"){a.push(p);continue}let f=c.run({value:t[p],issues:[]},o);if(f instanceof Promise)e.push(f.then((m)=>Hc(m,n,p,t,d)));else Hc(f,n,p,t,d)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return n;return Promise.all(e).then(()=>n)}var UE=Q("$ZodObject",(e,t)=>{if(Et.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let l=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...l};return Object.defineProperty(t,"shape",{value:c}),c}})}let o=$a(()=>_b(t));dt(e._zod,"propValues",()=>{let l=t.shape,c={};for(let u in l){let d=l[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let p of d.values)c[u].add(p)}}return c});let i=xs,s=t.catchall,a;e._zod.parse=(l,c)=>{a??(a=o.value);let u=l.value;if(!i(u))return l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l;l.value={};let d=[],p=a.shape;for(let f of a.keys){let m=p[f],h=m._zod.optout==="optional",g=m._zod.run({value:u[f],issues:[]},c);if(g instanceof Promise)d.push(g.then((v)=>Hc(v,l,f,u,h)));else Hc(g,l,f,u,h)}if(!s)return d.length?Promise.all(d).then(()=>l):l;return Cb(d,u,l,c,o.value,e)}}),Tb=Q("$ZodObjectJIT",(e,t)=>{UE.init(e,t);let n=e._zod.parse,o=$a(()=>_b(t)),i=(f)=>{let m=new Vp(["shape","payload","ctx"]),h=o.value,g=(C)=>{let y=Bp(C);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let v=Object.create(null),b=0;for(let C of h.keys)v[C]=`key_${b++}`;m.write("const newResult = {};");for(let C of h.keys){let y=v[C],k=Bp(C),I=f[C]?._zod?.optout==="optional";if(m.write(`const ${y} = ${g(C)};`),I)m.write(`
24
+ `))}}var Fv={major:4,minor:3,patch:6};var Et=Q("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fv;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let i of o)for(let s of i._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 i=(a,l,c)=>{let u=Ei(a),d;for(let p of l){if(p._zod.def.when){if(!p._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,m=p._zod.check(a);if(m instanceof Promise&&c?.async===!1)throw new fr;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await m,a.issues.length===f)return;if(!u)u=Ei(a,f)});else{if(a.issues.length===f)continue;if(!u)u=Ei(a,f)}}if(d)return d.then(()=>a);return a},s=(a,l,c)=>{if(Ei(a))return a.aborted=!0,a;let u=i(l,o,c);if(u instanceof Promise){if(c.async===!1)throw new fr;return u.then((d)=>e._zod.parse(d,c))}return e._zod.parse(u,c)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>s(d,a,l));return s(u,a,l)}let c=e._zod.parse(a,l);if(c instanceof Promise){if(l.async===!1)throw new fr;return c.then((u)=>i(u,o,l))}return i(c,o,l)}}dt(e,"~standard",()=>({validate:(i)=>{try{let s=Da(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Dc(e,i).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Uc=Q("$ZodString",(e,t)=>{Et.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??bv(e._zod.bag),e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Pt=Q("$ZodStringFormat",(e,t)=>{Fa.init(e,t),Uc.init(e,t)}),Vv=Q("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=iv),Pt.init(e,t)}),Xv=Q("$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=Wp(o))}else t.pattern??(t.pattern=Wp());Pt.init(e,t)}),Jv=Q("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sv),Pt.init(e,t)}),Yv=Q("$ZodURL",(e,t)=>{Pt.init(e,t),e._zod.check=(n)=>{try{let o=n.value.trim(),i=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(i.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(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=i.href;else n.value=o;return}catch(o){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Qv=Q("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=av()),Pt.init(e,t)}),eb=Q("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ov),Pt.init(e,t)}),tb=Q("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Yy),Pt.init(e,t)}),nb=Q("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Qy),Pt.init(e,t)}),ob=Q("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ev),Pt.init(e,t)}),rb=Q("$ZodXID",(e,t)=>{t.pattern??(t.pattern=tv),Pt.init(e,t)}),ib=Q("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=nv),Pt.init(e,t)}),sb=Q("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=vv(t)),Pt.init(e,t)}),ab=Q("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=hv),Pt.init(e,t)}),lb=Q("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=yv(t)),Pt.init(e,t)}),cb=Q("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=rv),Pt.init(e,t)}),ub=Q("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=lv),Pt.init(e,t),e._zod.bag.format="ipv4"}),db=Q("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=cv),Pt.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 pb=Q("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=uv),Pt.init(e,t)}),fb=Q("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=dv),Pt.init(e,t),e._zod.check=(n)=>{let o=n.value.split("/");try{if(o.length!==2)throw Error();let[i,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://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function mb(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var hb=Q("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=pv),Pt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(mb(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function FE(e){if(!qp.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return mb(n)}var gb=Q("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qp),Pt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(FE(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),yb=Q("$ZodE164",(e,t)=>{t.pattern??(t.pattern=fv),Pt.init(e,t)});function HE(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[o]=n;if(!o)return!1;let i=JSON.parse(atob(o));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var vb=Q("$ZodJWT",(e,t)=>{Pt.init(e,t),e._zod.check=(n)=>{if(HE(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Yp=Q("$ZodNumber",(e,t)=>{Et.init(e,t),e._zod.pattern=e._zod.bag.pattern??Gp,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let s=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),n}}),bb=Q("$ZodNumberFormat",(e,t)=>{Ev.init(e,t),Yp.init(e,t)}),xb=Q("$ZodBoolean",(e,t)=>{Et.init(e,t),e._zod.pattern=wv,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}});var wb=Q("$ZodUndefined",(e,t)=>{Et.init(e,t),e._zod.pattern=Sv,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,o)=>{let i=n.value;if(typeof i>"u")return n;return n.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),n}}),kb=Q("$ZodNull",(e,t)=>{Et.init(e,t),e._zod.pattern=kv,e._zod.values=new Set([null]),e._zod.parse=(n,o)=>{let i=n.value;if(i===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}});var Sb=Q("$ZodUnknown",(e,t)=>{Et.init(e,t),e._zod.parse=(n)=>n}),_b=Q("$ZodNever",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Hv(e,t,n){if(e.issues.length)t.issues.push(...Ur(n,e.issues));t.value[n]=e.value}var Cb=Q("$ZodArray",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let s=[];for(let a=0;a<i.length;a++){let l=i[a],c=t.element._zod.run({value:l,issues:[]},o);if(c instanceof Promise)s.push(c.then((u)=>Hv(u,n,a)));else Hv(c,n,a)}if(s.length)return Promise.all(s).then(()=>n);return n}});function Hc(e,t,n,o,i){if(e.issues.length){if(i&&!(n in o))return;t.issues.push(...Ur(n,e.issues))}if(e.value===void 0){if(n in o)t.value[n]=void 0}else t.value[n]=e.value}function Tb(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=Dy(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ib(e,t,n,o,i,s){let a=[],l=i.keySet,c=i.catchall._zod,u=c.def.type,d=c.optout==="optional";for(let p in t){if(l.has(p))continue;if(u==="never"){a.push(p);continue}let f=c.run({value:t[p],issues:[]},o);if(f instanceof Promise)e.push(f.then((m)=>Hc(m,n,p,t,d)));else Hc(f,n,p,t,d)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return n;return Promise.all(e).then(()=>n)}var UE=Q("$ZodObject",(e,t)=>{if(Et.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let l=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...l};return Object.defineProperty(t,"shape",{value:c}),c}})}let o=La(()=>Tb(t));dt(e._zod,"propValues",()=>{let l=t.shape,c={};for(let u in l){let d=l[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let p of d.values)c[u].add(p)}}return c});let i=xs,s=t.catchall,a;e._zod.parse=(l,c)=>{a??(a=o.value);let u=l.value;if(!i(u))return l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l;l.value={};let d=[],p=a.shape;for(let f of a.keys){let m=p[f],h=m._zod.optout==="optional",g=m._zod.run({value:u[f],issues:[]},c);if(g instanceof Promise)d.push(g.then((v)=>Hc(v,l,f,u,h)));else Hc(g,l,f,u,h)}if(!s)return d.length?Promise.all(d).then(()=>l):l;return Ib(d,u,l,c,o.value,e)}}),Eb=Q("$ZodObjectJIT",(e,t)=>{UE.init(e,t);let n=e._zod.parse,o=La(()=>Tb(t)),i=(f)=>{let m=new Xp(["shape","payload","ctx"]),h=o.value,g=(C)=>{let y=Fp(C);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");let v=Object.create(null),b=0;for(let C of h.keys)v[C]=`key_${b++}`;m.write("const newResult = {};");for(let C of h.keys){let y=v[C],k=Fp(C),I=f[C]?._zod?.optout==="optional";if(m.write(`const ${y} = ${g(C)};`),I)m.write(`
25
25
  if (${y}.issues.length) {
26
26
  if (${k} in input) {
27
27
  payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
@@ -55,9 +55,9 @@ ${c}${u}
55
55
  newResult[${k}] = ${y}.value;
56
56
  }
57
57
 
58
- `)}m.write("payload.value = newResult;"),m.write("return payload;");let x=m.compile();return(C,y)=>x(f,C,y)},s,a=xs,l=!Ac.jitless,u=l&&zy.value,d=t.catchall,p;e._zod.parse=(f,m)=>{p??(p=o.value);let h=f.value;if(!a(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;if(l&&u&&m?.async===!1&&m.jitless!==!0){if(!s)s=i(t.shape);if(f=s(f,m),!d)return f;return Cb([],h,f,m,p,e)}return n(f,m)}});function Fv(e,t,n,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let i=e.filter((s)=>!Ei(s));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((a)=>Zo(a,o,yo())))}),t}var Yp=Q("$ZodUnion",(e,t)=>{Et.init(e,t),dt(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),dt(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),dt(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),dt(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((s)=>s._zod.pattern);return new RegExp(`^(${i.map((s)=>Mc(s.source)).join("|")})$`)}return});let n=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(n)return o(i,s);let a=!1,l=[];for(let c of t.options){let u=c._zod.run({value:i.value,issues:[]},s);if(u instanceof Promise)l.push(u),a=!0;else{if(u.issues.length===0)return u;l.push(u)}}if(!a)return Fv(l,i,e,s);return Promise.all(l).then((c)=>Fv(c,i,e,s))}});var Ib=Q("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Yp.init(e,t);let n=e._zod.parse;dt(e._zod,"propValues",()=>{let i={};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[l,c]of Object.entries(a)){if(!i[l])i[l]=new Set;for(let u of c)i[l].add(u)}}return i});let o=$a(()=>{let i=t.options,s=new Map;for(let a of i){let l=a._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let c of l){if(s.has(c))throw Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,a)}}return s});e._zod.parse=(i,s)=>{let a=i.value;if(!xs(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;let l=o.value.get(a?.[t.discriminator]);if(l)return l._zod.run(i,s);if(t.unionFallback)return n(i,s);return i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),i}}),Eb=Q("$ZodIntersection",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{let i=n.value,s=t.left._zod.run({value:i,issues:[]},o),a=t.right._zod.run({value:i,issues:[]},o);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([c,u])=>Hv(n,c,u));return Hv(n,s,a)}});function Xp(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(Ii(e)&&Ii(t)){let n=Object.keys(t),o=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),i={...e,...t};for(let s of o){let a=Xp(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};i[s]=a.data}return{valid:!0,data:i}}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 i=e[o],s=t[o],a=Xp(i,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 Hv(e,t,n){let o=new Map,i;for(let l of t.issues)if(l.code==="unrecognized_keys"){i??(i=l);for(let c of l.keys){if(!o.has(c))o.set(c,{});o.get(c).l=!0}}else e.issues.push(l);for(let l of n.issues)if(l.code==="unrecognized_keys")for(let c of l.keys){if(!o.has(c))o.set(c,{});o.get(c).r=!0}else e.issues.push(l);let s=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(s.length&&i)e.issues.push({...i,keys:s});if(Ei(e))return e;let a=Xp(t.value,n.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ab=Q("$ZodRecord",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{let i=n.value;if(!Ii(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a){n.value={};let l=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){l.add(typeof u==="number"?u.toString():u);let d=t.valueType._zod.run({value:i[u],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Ur(u,p.issues));n.value[u]=p.value}));else{if(d.issues.length)n.issues.push(...Ur(u,d.issues));n.value[u]=d.value}}let c;for(let u in i)if(!l.has(u))c=c??[],c.push(u);if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{n.value={};for(let l of Reflect.ownKeys(i)){if(l==="__proto__")continue;let c=t.keyType._zod.run({value:l,issues:[]},o);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&qp.test(l)&&c.issues.length){let p=t.keyType._zod.run({value:Number(l),issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)c=p}if(c.issues.length){if(t.mode==="loose")n.value[l]=i[l];else n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((p)=>Zo(p,o,yo())),input:l,path:[l],inst:e});continue}let d=t.valueType._zod.run({value:i[l],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Ur(l,p.issues));n.value[c.value]=p.value}));else{if(d.issues.length)n.issues.push(...Ur(l,d.issues));n.value[c.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var Rb=Q("$ZodEnum",(e,t)=>{Et.init(e,t);let n=Pc(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter((i)=>$y.has(typeof i)).map((i)=>typeof i==="string"?Hr(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{let a=i.value;if(o.has(a))return i;return i.issues.push({code:"invalid_value",values:n,input:a,inst:e}),i}}),Pb=Q("$ZodLiteral",(e,t)=>{if(Et.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"?Hr(o):o?Hr(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,i)=>{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 Nb=Q("$ZodTransform",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Ma(e.constructor.name);let i=t.transform(n.value,n);if(o.async)return(i instanceof Promise?i:Promise.resolve(i)).then((a)=>(n.value=a,n));if(i instanceof Promise)throw new fr;return n.value=i,n}});function Uv(e,t){if(e.issues.length&&t===void 0)return{issues:[],value:void 0};return e}var Qp=Q("$ZodOptional",(e,t)=>{Et.init(e,t),e._zod.optin="optional",e._zod.optout="optional",dt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),dt(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Mc(n.source)})?$`):void 0}),e._zod.parse=(n,o)=>{if(t.innerType._zod.optin==="optional"){let i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>Uv(s,n.value));return Uv(i,n.value)}if(n.value===void 0)return n;return t.innerType._zod.run(n,o)}}),Mb=Q("$ZodExactOptional",(e,t)=>{Qp.init(e,t),dt(e._zod,"values",()=>t.innerType._zod.values),dt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),zb=Q("$ZodNullable",(e,t)=>{Et.init(e,t),dt(e._zod,"optin",()=>t.innerType._zod.optin),dt(e._zod,"optout",()=>t.innerType._zod.optout),dt(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Mc(n.source)}|null)$`):void 0}),dt(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)}}),$b=Q("$ZodDefault",(e,t)=>{Et.init(e,t),e._zod.optin="optional",dt(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 i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>jv(s,t));return jv(i,t)}});function jv(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Lb=Q("$ZodPrefault",(e,t)=>{Et.init(e,t),e._zod.optin="optional",dt(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)}}),Ob=Q("$ZodNonOptional",(e,t)=>{Et.init(e,t),dt(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 i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>Zv(s,e));return Zv(i,e)}});function Zv(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 Db=Q("$ZodCatch",(e,t)=>{Et.init(e,t),dt(e._zod,"optin",()=>t.innerType._zod.optin),dt(e._zod,"optout",()=>t.innerType._zod.optout),dt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>{if(n.value=s.value,s.issues.length)n.value=t.catchValue({...n,error:{issues:s.issues.map((a)=>Zo(a,o,yo()))},input:n.value}),n.issues=[];return n});if(n.value=i.value,i.issues.length)n.value=t.catchValue({...n,error:{issues:i.issues.map((s)=>Zo(s,o,yo()))},input:n.value}),n.issues=[];return n}});var Bb=Q("$ZodPipe",(e,t)=>{Et.init(e,t),dt(e._zod,"values",()=>t.in._zod.values),dt(e._zod,"optin",()=>t.in._zod.optin),dt(e._zod,"optout",()=>t.out._zod.optout),dt(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)=>Fc(a,t.in,o));return Fc(s,t.in,o)}let i=t.in._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>Fc(s,t.out,o));return Fc(i,t.out,o)}});function Fc(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var Fb=Q("$ZodReadonly",(e,t)=>{Et.init(e,t),dt(e._zod,"propValues",()=>t.innerType._zod.propValues),dt(e._zod,"values",()=>t.innerType._zod.values),dt(e._zod,"optin",()=>t.innerType?._zod?.optin),dt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then(Wv);return Wv(i)}});function Wv(e){return e.value=Object.freeze(e.value),e}var Hb=Q("$ZodCustom",(e,t)=>{wn.init(e,t),Et.init(e,t),e._zod.parse=(n,o)=>n,e._zod.check=(n)=>{let o=n.value,i=t.fn(o);if(i instanceof Promise)return i.then((s)=>qv(s,n,o,e));qv(i,n,o,e);return}});function qv(e,t,n,o){if(!e){let i={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)i.params=o._zod.def.params;t.issues.push(Ai(i))}}var jE=()=>{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(i){return e[i]??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(i)=>{switch(i.code){case"invalid_type":{let s=o[i.expected]??i.expected,a=Dy(i.input),l=o[a]??a;return`Invalid input: expected ${s}, received ${l}`}case"invalid_value":if(i.values.length===1)return`Invalid input: expected ${Up(i.values[0])}`;return`Invalid option: expected one of ${Dp(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",a=t(i.origin);if(a)return`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",a=t(i.origin);if(a)return`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`;return`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;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]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Dp(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function ef(){return{localeError:jE()}}var Ub,LD=Symbol("ZodOutput"),OD=Symbol("ZodInput");class jb{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 ZE(){return new jb}(Ub=globalThis).__zod_globalRegistry??(Ub.__zod_globalRegistry=ZE());var Ri=globalThis.__zod_globalRegistry;function Zb(e,t){return new e({type:"string",...Re(t)})}function Wb(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Re(t)})}function tf(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Re(t)})}function qb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Re(t)})}function Gb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Re(t)})}function Kb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Re(t)})}function Vb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Re(t)})}function Xb(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Re(t)})}function Jb(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Re(t)})}function Yb(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Re(t)})}function Qb(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Re(t)})}function ex(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Re(t)})}function tx(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Re(t)})}function nx(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Re(t)})}function ox(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Re(t)})}function rx(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Re(t)})}function ix(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Re(t)})}function sx(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Re(t)})}function ax(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Re(t)})}function lx(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Re(t)})}function cx(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Re(t)})}function ux(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Re(t)})}function dx(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Re(t)})}function px(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Re(t)})}function fx(e,t){return new e({type:"string",format:"date",check:"string_format",...Re(t)})}function mx(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Re(t)})}function hx(e,t){return new e({type:"string",format:"duration",check:"string_format",...Re(t)})}function gx(e,t){return new e({type:"number",checks:[],...Re(t)})}function yx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Re(t)})}function vx(e,t){return new e({type:"boolean",...Re(t)})}function bx(e,t){return new e({type:"undefined",...Re(t)})}function xx(e,t){return new e({type:"null",...Re(t)})}function wx(e){return new e({type:"unknown"})}function kx(e,t){return new e({type:"never",...Re(t)})}function jc(e,t){return new Gp({check:"less_than",...Re(t),value:e,inclusive:!1})}function Fa(e,t){return new Gp({check:"less_than",...Re(t),value:e,inclusive:!0})}function Zc(e,t){return new Kp({check:"greater_than",...Re(t),value:e,inclusive:!1})}function Ha(e,t){return new Kp({check:"greater_than",...Re(t),value:e,inclusive:!0})}function Wc(e,t){return new Cv({check:"multiple_of",...Re(t),value:e})}function qc(e,t){return new Iv({check:"max_length",...Re(t),maximum:e})}function ws(e,t){return new Ev({check:"min_length",...Re(t),minimum:e})}function Gc(e,t){return new Av({check:"length_equals",...Re(t),length:e})}function nf(e,t){return new Rv({check:"string_format",format:"regex",...Re(t),pattern:e})}function of(e){return new Pv({check:"string_format",format:"lowercase",...Re(e)})}function rf(e){return new Nv({check:"string_format",format:"uppercase",...Re(e)})}function sf(e,t){return new Mv({check:"string_format",format:"includes",...Re(t),includes:e})}function af(e,t){return new zv({check:"string_format",format:"starts_with",...Re(t),prefix:e})}function lf(e,t){return new $v({check:"string_format",format:"ends_with",...Re(t),suffix:e})}function jr(e){return new Lv({check:"overwrite",tx:e})}function cf(e){return jr((t)=>t.normalize(e))}function uf(){return jr((e)=>e.trim())}function df(){return jr((e)=>e.toLowerCase())}function pf(){return jr((e)=>e.toUpperCase())}function ff(){return jr((e)=>My(e))}function Sx(e,t,n){return new e({type:"array",element:t,...Re(n)})}function _x(e,t,n){let o=Re(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Cx(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Re(n)})}function Tx(e){let t=WE((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Ai(o,n.value,t._zod.def));else{let i=o;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Ai(i))}},e(n.value,n)));return t}function WE(e,t){let n=new wn({check:"custom",...Re(t)});return n._zod.check=e,n}function mf(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??Ri,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 Xt(e,t,n={path:[],schemaPath:[]}){var o;let i=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 l=e._zod.toJSONSchema?.();if(l)a.schema=l;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let f=a.schema,m=t.processors[i.type];if(!m)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);m(e,t,f,d)}let p=e._zod.parent;if(p){if(!a.ref)a.ref=p;Xt(p,t,d),t.seen.get(p).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(a.schema,c);if(t.io==="input"&&jn(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 hf(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 l=e.metadataRegistry.get(a[0])?.id;if(l){let c=o.get(l);if(c&&c!==a[0])throw Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(l,a[0])}}let i=(a)=>{let l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,f=e.external.uri??((h)=>h);if(p)return{ref:f(p)};let m=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=m,{defId:m,ref:`${f("__shared")}#/${l}/${m}`}}if(a[1]===n)return{ref:"#"};let u=`${"#"}/${l}/`,d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(a)=>{if(a[1].schema.$ref)return;let l=a[1],{ref:c,defId:u}=i(a);if(l.def={...l.schema},u)l.defId=u;let d=l.schema;for(let p in d)delete d[p];d.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let l=a[1];if(l.cycle)throw Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
58
+ `)}m.write("payload.value = newResult;"),m.write("return payload;");let x=m.compile();return(C,y)=>x(f,C,y)},s,a=xs,l=!Ac.jitless,u=l&&Ly.value,d=t.catchall,p;e._zod.parse=(f,m)=>{p??(p=o.value);let h=f.value;if(!a(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;if(l&&u&&m?.async===!1&&m.jitless!==!0){if(!s)s=i(t.shape);if(f=s(f,m),!d)return f;return Ib([],h,f,m,p,e)}return n(f,m)}});function Uv(e,t,n,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let i=e.filter((s)=>!Ei(s));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((a)=>Zo(a,o,yo())))}),t}var Qp=Q("$ZodUnion",(e,t)=>{Et.init(e,t),dt(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),dt(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),dt(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),dt(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((s)=>s._zod.pattern);return new RegExp(`^(${i.map((s)=>Mc(s.source)).join("|")})$`)}return});let n=t.options.length===1,o=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(n)return o(i,s);let a=!1,l=[];for(let c of t.options){let u=c._zod.run({value:i.value,issues:[]},s);if(u instanceof Promise)l.push(u),a=!0;else{if(u.issues.length===0)return u;l.push(u)}}if(!a)return Uv(l,i,e,s);return Promise.all(l).then((c)=>Uv(c,i,e,s))}});var Ab=Q("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Qp.init(e,t);let n=e._zod.parse;dt(e._zod,"propValues",()=>{let i={};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[l,c]of Object.entries(a)){if(!i[l])i[l]=new Set;for(let u of c)i[l].add(u)}}return i});let o=La(()=>{let i=t.options,s=new Map;for(let a of i){let l=a._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let c of l){if(s.has(c))throw Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,a)}}return s});e._zod.parse=(i,s)=>{let a=i.value;if(!xs(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;let l=o.value.get(a?.[t.discriminator]);if(l)return l._zod.run(i,s);if(t.unionFallback)return n(i,s);return i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),i}}),Rb=Q("$ZodIntersection",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{let i=n.value,s=t.left._zod.run({value:i,issues:[]},o),a=t.right._zod.run({value:i,issues:[]},o);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([c,u])=>jv(n,c,u));return jv(n,s,a)}});function Jp(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(Ii(e)&&Ii(t)){let n=Object.keys(t),o=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),i={...e,...t};for(let s of o){let a=Jp(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};i[s]=a.data}return{valid:!0,data:i}}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 i=e[o],s=t[o],a=Jp(i,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 jv(e,t,n){let o=new Map,i;for(let l of t.issues)if(l.code==="unrecognized_keys"){i??(i=l);for(let c of l.keys){if(!o.has(c))o.set(c,{});o.get(c).l=!0}}else e.issues.push(l);for(let l of n.issues)if(l.code==="unrecognized_keys")for(let c of l.keys){if(!o.has(c))o.set(c,{});o.get(c).r=!0}else e.issues.push(l);let s=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(s.length&&i)e.issues.push({...i,keys:s});if(Ei(e))return e;let a=Jp(t.value,n.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Pb=Q("$ZodRecord",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{let i=n.value;if(!Ii(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a){n.value={};let l=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){l.add(typeof u==="number"?u.toString():u);let d=t.valueType._zod.run({value:i[u],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Ur(u,p.issues));n.value[u]=p.value}));else{if(d.issues.length)n.issues.push(...Ur(u,d.issues));n.value[u]=d.value}}let c;for(let u in i)if(!l.has(u))c=c??[],c.push(u);if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{n.value={};for(let l of Reflect.ownKeys(i)){if(l==="__proto__")continue;let c=t.keyType._zod.run({value:l,issues:[]},o);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&Gp.test(l)&&c.issues.length){let p=t.keyType._zod.run({value:Number(l),issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)c=p}if(c.issues.length){if(t.mode==="loose")n.value[l]=i[l];else n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((p)=>Zo(p,o,yo())),input:l,path:[l],inst:e});continue}let d=t.valueType._zod.run({value:i[l],issues:[]},o);if(d instanceof Promise)s.push(d.then((p)=>{if(p.issues.length)n.issues.push(...Ur(l,p.issues));n.value[c.value]=p.value}));else{if(d.issues.length)n.issues.push(...Ur(l,d.issues));n.value[c.value]=d.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var Nb=Q("$ZodEnum",(e,t)=>{Et.init(e,t);let n=Pc(t.entries),o=new Set(n);e._zod.values=o,e._zod.pattern=new RegExp(`^(${n.filter((i)=>Oy.has(typeof i)).map((i)=>typeof i==="string"?Hr(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{let a=i.value;if(o.has(a))return i;return i.issues.push({code:"invalid_value",values:n,input:a,inst:e}),i}}),Mb=Q("$ZodLiteral",(e,t)=>{if(Et.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"?Hr(o):o?Hr(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,i)=>{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 zb=Q("$ZodTransform",(e,t)=>{Et.init(e,t),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new za(e.constructor.name);let i=t.transform(n.value,n);if(o.async)return(i instanceof Promise?i:Promise.resolve(i)).then((a)=>(n.value=a,n));if(i instanceof Promise)throw new fr;return n.value=i,n}});function Zv(e,t){if(e.issues.length&&t===void 0)return{issues:[],value:void 0};return e}var ef=Q("$ZodOptional",(e,t)=>{Et.init(e,t),e._zod.optin="optional",e._zod.optout="optional",dt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),dt(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Mc(n.source)})?$`):void 0}),e._zod.parse=(n,o)=>{if(t.innerType._zod.optin==="optional"){let i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>Zv(s,n.value));return Zv(i,n.value)}if(n.value===void 0)return n;return t.innerType._zod.run(n,o)}}),$b=Q("$ZodExactOptional",(e,t)=>{ef.init(e,t),dt(e._zod,"values",()=>t.innerType._zod.values),dt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),Lb=Q("$ZodNullable",(e,t)=>{Et.init(e,t),dt(e._zod,"optin",()=>t.innerType._zod.optin),dt(e._zod,"optout",()=>t.innerType._zod.optout),dt(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Mc(n.source)}|null)$`):void 0}),dt(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)}}),Ob=Q("$ZodDefault",(e,t)=>{Et.init(e,t),e._zod.optin="optional",dt(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 i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>Wv(s,t));return Wv(i,t)}});function Wv(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Db=Q("$ZodPrefault",(e,t)=>{Et.init(e,t),e._zod.optin="optional",dt(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)}}),Bb=Q("$ZodNonOptional",(e,t)=>{Et.init(e,t),dt(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 i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>qv(s,e));return qv(i,e)}});function qv(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 Fb=Q("$ZodCatch",(e,t)=>{Et.init(e,t),dt(e._zod,"optin",()=>t.innerType._zod.optin),dt(e._zod,"optout",()=>t.innerType._zod.optout),dt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>{if(n.value=s.value,s.issues.length)n.value=t.catchValue({...n,error:{issues:s.issues.map((a)=>Zo(a,o,yo()))},input:n.value}),n.issues=[];return n});if(n.value=i.value,i.issues.length)n.value=t.catchValue({...n,error:{issues:i.issues.map((s)=>Zo(s,o,yo()))},input:n.value}),n.issues=[];return n}});var Hb=Q("$ZodPipe",(e,t)=>{Et.init(e,t),dt(e._zod,"values",()=>t.in._zod.values),dt(e._zod,"optin",()=>t.in._zod.optin),dt(e._zod,"optout",()=>t.out._zod.optout),dt(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)=>Fc(a,t.in,o));return Fc(s,t.in,o)}let i=t.in._zod.run(n,o);if(i instanceof Promise)return i.then((s)=>Fc(s,t.out,o));return Fc(i,t.out,o)}});function Fc(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var Ub=Q("$ZodReadonly",(e,t)=>{Et.init(e,t),dt(e._zod,"propValues",()=>t.innerType._zod.propValues),dt(e._zod,"values",()=>t.innerType._zod.values),dt(e._zod,"optin",()=>t.innerType?._zod?.optin),dt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);let i=t.innerType._zod.run(n,o);if(i instanceof Promise)return i.then(Gv);return Gv(i)}});function Gv(e){return e.value=Object.freeze(e.value),e}var jb=Q("$ZodCustom",(e,t)=>{wn.init(e,t),Et.init(e,t),e._zod.parse=(n,o)=>n,e._zod.check=(n)=>{let o=n.value,i=t.fn(o);if(i instanceof Promise)return i.then((s)=>Kv(s,n,o,e));Kv(i,n,o,e);return}});function Kv(e,t,n,o){if(!e){let i={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)i.params=o._zod.def.params;t.issues.push(Ai(i))}}var jE=()=>{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(i){return e[i]??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(i)=>{switch(i.code){case"invalid_type":{let s=o[i.expected]??i.expected,a=Fy(i.input),l=o[a]??a;return`Invalid input: expected ${s}, received ${l}`}case"invalid_value":if(i.values.length===1)return`Invalid input: expected ${jp(i.values[0])}`;return`Invalid option: expected one of ${Bp(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",a=t(i.origin);if(a)return`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",a=t(i.origin);if(a)return`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`;return`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;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]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Bp(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function tf(){return{localeError:jE()}}var Zb,LD=Symbol("ZodOutput"),OD=Symbol("ZodInput");class Wb{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 ZE(){return new Wb}(Zb=globalThis).__zod_globalRegistry??(Zb.__zod_globalRegistry=ZE());var Ri=globalThis.__zod_globalRegistry;function qb(e,t){return new e({type:"string",...Re(t)})}function Gb(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Re(t)})}function nf(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Re(t)})}function Kb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Re(t)})}function Vb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Re(t)})}function Xb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Re(t)})}function Jb(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Re(t)})}function Yb(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Re(t)})}function Qb(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Re(t)})}function ex(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Re(t)})}function tx(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Re(t)})}function nx(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Re(t)})}function ox(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Re(t)})}function rx(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Re(t)})}function ix(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Re(t)})}function sx(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Re(t)})}function ax(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Re(t)})}function lx(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Re(t)})}function cx(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Re(t)})}function ux(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Re(t)})}function dx(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Re(t)})}function px(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Re(t)})}function fx(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Re(t)})}function mx(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Re(t)})}function hx(e,t){return new e({type:"string",format:"date",check:"string_format",...Re(t)})}function gx(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Re(t)})}function yx(e,t){return new e({type:"string",format:"duration",check:"string_format",...Re(t)})}function vx(e,t){return new e({type:"number",checks:[],...Re(t)})}function bx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Re(t)})}function xx(e,t){return new e({type:"boolean",...Re(t)})}function wx(e,t){return new e({type:"undefined",...Re(t)})}function kx(e,t){return new e({type:"null",...Re(t)})}function Sx(e){return new e({type:"unknown"})}function _x(e,t){return new e({type:"never",...Re(t)})}function jc(e,t){return new Kp({check:"less_than",...Re(t),value:e,inclusive:!1})}function Ha(e,t){return new Kp({check:"less_than",...Re(t),value:e,inclusive:!0})}function Zc(e,t){return new Vp({check:"greater_than",...Re(t),value:e,inclusive:!1})}function Ua(e,t){return new Vp({check:"greater_than",...Re(t),value:e,inclusive:!0})}function Wc(e,t){return new Iv({check:"multiple_of",...Re(t),value:e})}function qc(e,t){return new Av({check:"max_length",...Re(t),maximum:e})}function ws(e,t){return new Rv({check:"min_length",...Re(t),minimum:e})}function Gc(e,t){return new Pv({check:"length_equals",...Re(t),length:e})}function of(e,t){return new Nv({check:"string_format",format:"regex",...Re(t),pattern:e})}function rf(e){return new Mv({check:"string_format",format:"lowercase",...Re(e)})}function sf(e){return new zv({check:"string_format",format:"uppercase",...Re(e)})}function af(e,t){return new $v({check:"string_format",format:"includes",...Re(t),includes:e})}function lf(e,t){return new Lv({check:"string_format",format:"starts_with",...Re(t),prefix:e})}function cf(e,t){return new Ov({check:"string_format",format:"ends_with",...Re(t),suffix:e})}function jr(e){return new Dv({check:"overwrite",tx:e})}function uf(e){return jr((t)=>t.normalize(e))}function df(){return jr((e)=>e.trim())}function pf(){return jr((e)=>e.toLowerCase())}function ff(){return jr((e)=>e.toUpperCase())}function mf(){return jr((e)=>$y(e))}function Cx(e,t,n){return new e({type:"array",element:t,...Re(n)})}function Tx(e,t,n){let o=Re(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function Ix(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Re(n)})}function Ex(e){let t=WE((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Ai(o,n.value,t._zod.def));else{let i=o;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Ai(i))}},e(n.value,n)));return t}function WE(e,t){let n=new wn({check:"custom",...Re(t)});return n._zod.check=e,n}function hf(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??Ri,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 Xt(e,t,n={path:[],schemaPath:[]}){var o;let i=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 l=e._zod.toJSONSchema?.();if(l)a.schema=l;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,d);else{let f=a.schema,m=t.processors[i.type];if(!m)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);m(e,t,f,d)}let p=e._zod.parent;if(p){if(!a.ref)a.ref=p;Xt(p,t,d),t.seen.get(p).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(a.schema,c);if(t.io==="input"&&jn(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 gf(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 l=e.metadataRegistry.get(a[0])?.id;if(l){let c=o.get(l);if(c&&c!==a[0])throw Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(l,a[0])}}let i=(a)=>{let l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(a[0])?.id,f=e.external.uri??((h)=>h);if(p)return{ref:f(p)};let m=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=m,{defId:m,ref:`${f("__shared")}#/${l}/${m}`}}if(a[1]===n)return{ref:"#"};let u=`${"#"}/${l}/`,d=a[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},s=(a)=>{if(a[1].schema.$ref)return;let l=a[1],{ref:c,defId:u}=i(a);if(l.def={...l.schema},u)l.defId=u;let d=l.schema;for(let p in d)delete d[p];d.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let l=a[1];if(l.cycle)throw Error(`Cycle detected: #/${l.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 l=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(l.cycle){s(a);continue}if(l.count>1){if(e.reused==="ref"){s(a);continue}}}}function gf(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let c=l.def??l.schema,u={...c},d=l.ref;if(l.ref=null,d){o(d);let f=e.seen.get(d),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(m);else Object.assign(c,m);if(Object.assign(c,u),a._zod.parent===d)for(let g in c){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete c[g]}if(m.$ref&&f.def)for(let g in c){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(c[g])===JSON.stringify(f.def[g]))delete c[g]}}let p=a._zod.parent;if(p&&p!==d){o(p);let f=e.seen.get(p);if(f?.schema.$ref){if(c.$ref=f.schema.$ref,f.def)for(let m in c){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(c[m])===JSON.stringify(f.def[m]))delete c[m]}}}e.override({zodSchema:a,jsonSchema:c,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$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");i.$id=e.external.uri(a)}Object.assign(i,n.def??n.schema);let s=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId)s[l.defId]=l.def}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ua(t,"input",e.processors),output:Ua(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function jn(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 jn(o.element,n);if(o.type==="set")return jn(o.valueType,n);if(o.type==="lazy")return jn(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 jn(o.innerType,n);if(o.type==="intersection")return jn(o.left,n)||jn(o.right,n);if(o.type==="record"||o.type==="map")return jn(o.keyType,n)||jn(o.valueType,n);if(o.type==="pipe")return jn(o.in,n)||jn(o.out,n);if(o.type==="object"){for(let i in o.shape)if(jn(o.shape[i],n))return!0;return!1}if(o.type==="union"){for(let i of o.options)if(jn(i,n))return!0;return!1}if(o.type==="tuple"){for(let i of o.items)if(jn(i,n))return!0;if(o.rest&&jn(o.rest,n))return!0;return!1}return!1}var Ix=(e,t={})=>(n)=>{let o=mf({...n,processors:t});return Xt(e,o),hf(o,e),gf(o,e)},Ua=(e,t,n={})=>(o)=>{let{libraryOptions:i,target:s}=o??{},a=mf({...i??{},target:s,io:t,processors:n});return Xt(e,a),hf(a,e),gf(a,e)};var qE={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ex=(e,t,n,o)=>{let i=n;i.type="string";let{minimum:s,maximum:a,format:l,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s==="number")i.minLength=s;if(typeof a==="number")i.maxLength=a;if(l){if(i.format=qE[l]??l,i.format==="")delete i.format;if(l==="time")delete i.format}if(u)i.contentEncoding=u;if(c&&c.size>0){let d=[...c];if(d.length===1)i.pattern=d[0].source;else if(d.length>1)i.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Ax=(e,t,n,o)=>{let i=n,{minimum:s,maximum:a,format:l,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof l==="string"&&l.includes("int"))i.type="integer";else i.type="number";if(typeof d==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")i.minimum=d,i.exclusiveMinimum=!0;else i.exclusiveMinimum=d;if(typeof s==="number"){if(i.minimum=s,typeof d==="number"&&t.target!=="draft-04")if(d>=s)delete i.minimum;else delete i.exclusiveMinimum}if(typeof u==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")i.maximum=u,i.exclusiveMaximum=!0;else i.exclusiveMaximum=u;if(typeof a==="number"){if(i.maximum=a,typeof u==="number"&&t.target!=="draft-04")if(u<=a)delete i.maximum;else delete i.exclusiveMaximum}if(typeof c==="number")i.multipleOf=c},Rx=(e,t,n,o)=>{n.type="boolean"};var Px=(e,t,n,o)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},Nx=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")};var Mx=(e,t,n,o)=>{n.not={}};var zx=(e,t,n,o)=>{};var $x=(e,t,n,o)=>{let i=e._zod.def,s=Pc(i.entries);if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";n.enum=s},Lx=(e,t,n,o)=>{let i=e._zod.def,s=[];for(let a of i.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 Ox=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var Dx=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Bx=(e,t,n,o)=>{let i=n,s=e._zod.def,{minimum:a,maximum:l}=e._zod.bag;if(typeof a==="number")i.minItems=a;if(typeof l==="number")i.maxItems=l;i.type="array",i.items=Xt(s.element,t,{...o,path:[...o.path,"items"]})},Fx=(e,t,n,o)=>{let i=n,s=e._zod.def;i.type="object",i.properties={};let a=s.shape;for(let u in a)i.properties[u]=Xt(a[u],t,{...o,path:[...o.path,"properties",u]});let l=new Set(Object.keys(a)),c=new Set([...l].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(c.size>0)i.required=Array.from(c);if(s.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")i.additionalProperties=!1}else if(s.catchall)i.additionalProperties=Xt(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Hx=(e,t,n,o)=>{let i=e._zod.def,s=i.inclusive===!1,a=i.options.map((l,c)=>Xt(l,t,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=a;else n.anyOf=a},Ux=(e,t,n,o)=>{let i=e._zod.def,s=Xt(i.left,t,{...o,path:[...o.path,"allOf",0]}),a=Xt(i.right,t,{...o,path:[...o.path,"allOf",1]}),l=(u)=>("allOf"in u)&&Object.keys(u).length===1,c=[...l(s)?s.allOf:[s],...l(a)?a.allOf:[a]];n.allOf=c};var jx=(e,t,n,o)=>{let i=n,s=e._zod.def;i.type="object";let a=s.keyType,c=a._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=Xt(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});i.patternProperties={};for(let p of c)i.patternProperties[p.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")i.propertyNames=Xt(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});i.additionalProperties=Xt(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values;if(u){let d=[...u].filter((p)=>typeof p==="string"||typeof p==="number");if(d.length>0)i.required=d}},Zx=(e,t,n,o)=>{let i=e._zod.def,s=Xt(i.innerType,t,o),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=i.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},Wx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType},qx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Gx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);if(s.ref=i.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(i.defaultValue))},Kx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},Vx=(e,t,n,o)=>{let i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Xt(s,t,o);let a=t.seen.get(e);a.ref=s},Xx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0};var yf=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType};var eA=Q("ZodISODateTime",(e,t)=>{rb.init(e,t),Dt.init(e,t)});function vf(e){return px(eA,e)}var tA=Q("ZodISODate",(e,t)=>{ib.init(e,t),Dt.init(e,t)});function Jx(e){return fx(tA,e)}var nA=Q("ZodISOTime",(e,t)=>{sb.init(e,t),Dt.init(e,t)});function Yx(e){return mx(nA,e)}var oA=Q("ZodISODuration",(e,t)=>{ab.init(e,t),Dt.init(e,t)});function Qx(e){return hx(oA,e)}var ew=(e,t)=>{$c.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Hy(e,n)},flatten:{value:(n)=>Fy(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,za,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,za,2)}},isEmpty:{get(){return e.issues.length===0}}})},f2=Q("ZodError",ew),no=Q("ZodError",ew,{Parent:Error});var tw=Lc(no),nw=Oc(no),ow=La(no),rw=Da(no),iw=Uy(no),sw=jy(no),aw=Zy(no),lw=Wy(no),cw=qy(no),uw=Gy(no),dw=Ky(no),pw=Vy(no);var Nt=Q("ZodType",(e,t)=>(Et.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ua(e,"input"),output:Ua(e,"output")}}),e.toJSONSchema=Ix(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Fr(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)=>jo(e,n,o),e.brand=()=>e,e.register=(n,o)=>(n.add(e,o),e),e.parse=(n,o)=>tw(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>ow(e,n,o),e.parseAsync=async(n,o)=>nw(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>rw(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>iw(e,n,o),e.decode=(n,o)=>sw(e,n,o),e.encodeAsync=async(n,o)=>aw(e,n,o),e.decodeAsync=async(n,o)=>lw(e,n,o),e.safeEncode=(n,o)=>cw(e,n,o),e.safeDecode=(n,o)=>uw(e,n,o),e.safeEncodeAsync=async(n,o)=>dw(e,n,o),e.safeDecodeAsync=async(n,o)=>pw(e,n,o),e.refine=(n,o)=>e.check(VA(n,o)),e.superRefine=(n)=>e.check(XA(n)),e.overwrite=(n)=>e.check(jr(n)),e.optional=()=>Wt(e),e.exactOptional=()=>OA(e),e.nullable=()=>hw(e),e.nullish=()=>Wt(hw(e)),e.nonoptional=(n)=>jA(e,n),e.array=()=>We(e),e.or=(n)=>rt([e,n]),e.and=(n)=>Vc(e,n),e.transform=(n)=>wf(e,xw(n)),e.default=(n)=>FA(e,n),e.prefault=(n)=>UA(e,n),e.catch=(n)=>WA(e,n),e.pipe=(n)=>wf(e,n),e.readonly=()=>KA(e),e.describe=(n)=>{let o=e.clone();return Ri.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return Ri.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Ri.get(e);let o=e.clone();return Ri.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),gw=Q("_ZodString",(e,t)=>{Uc.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(o,i,s)=>Ex(e,o,i,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(nf(...o)),e.includes=(...o)=>e.check(sf(...o)),e.startsWith=(...o)=>e.check(af(...o)),e.endsWith=(...o)=>e.check(lf(...o)),e.min=(...o)=>e.check(ws(...o)),e.max=(...o)=>e.check(qc(...o)),e.length=(...o)=>e.check(Gc(...o)),e.nonempty=(...o)=>e.check(ws(1,...o)),e.lowercase=(o)=>e.check(of(o)),e.uppercase=(o)=>e.check(rf(o)),e.trim=()=>e.check(uf()),e.normalize=(...o)=>e.check(cf(...o)),e.toLowerCase=()=>e.check(df()),e.toUpperCase=()=>e.check(pf()),e.slugify=()=>e.check(ff())}),sA=Q("ZodString",(e,t)=>{Uc.init(e,t),gw.init(e,t),e.email=(n)=>e.check(Wb(aA,n)),e.url=(n)=>e.check(Xb(lA,n)),e.jwt=(n)=>e.check(dx(SA,n)),e.emoji=(n)=>e.check(Jb(cA,n)),e.guid=(n)=>e.check(tf(fw,n)),e.uuid=(n)=>e.check(qb(Kc,n)),e.uuidv4=(n)=>e.check(Gb(Kc,n)),e.uuidv6=(n)=>e.check(Kb(Kc,n)),e.uuidv7=(n)=>e.check(Vb(Kc,n)),e.nanoid=(n)=>e.check(Yb(uA,n)),e.guid=(n)=>e.check(tf(fw,n)),e.cuid=(n)=>e.check(Qb(dA,n)),e.cuid2=(n)=>e.check(ex(pA,n)),e.ulid=(n)=>e.check(tx(fA,n)),e.base64=(n)=>e.check(lx(xA,n)),e.base64url=(n)=>e.check(cx(wA,n)),e.xid=(n)=>e.check(nx(mA,n)),e.ksuid=(n)=>e.check(ox(hA,n)),e.ipv4=(n)=>e.check(rx(gA,n)),e.ipv6=(n)=>e.check(ix(yA,n)),e.cidrv4=(n)=>e.check(sx(vA,n)),e.cidrv6=(n)=>e.check(ax(bA,n)),e.e164=(n)=>e.check(ux(kA,n)),e.datetime=(n)=>e.check(vf(n)),e.date=(n)=>e.check(Jx(n)),e.time=(n)=>e.check(Yx(n)),e.duration=(n)=>e.check(Qx(n))});function U(e){return Zb(sA,e)}var Dt=Q("ZodStringFormat",(e,t)=>{Pt.init(e,t),gw.init(e,t)}),aA=Q("ZodEmail",(e,t)=>{Vv.init(e,t),Dt.init(e,t)});var fw=Q("ZodGUID",(e,t)=>{Gv.init(e,t),Dt.init(e,t)});var Kc=Q("ZodUUID",(e,t)=>{Kv.init(e,t),Dt.init(e,t)});var lA=Q("ZodURL",(e,t)=>{Xv.init(e,t),Dt.init(e,t)});var cA=Q("ZodEmoji",(e,t)=>{Jv.init(e,t),Dt.init(e,t)});var uA=Q("ZodNanoID",(e,t)=>{Yv.init(e,t),Dt.init(e,t)});var dA=Q("ZodCUID",(e,t)=>{Qv.init(e,t),Dt.init(e,t)});var pA=Q("ZodCUID2",(e,t)=>{eb.init(e,t),Dt.init(e,t)});var fA=Q("ZodULID",(e,t)=>{tb.init(e,t),Dt.init(e,t)});var mA=Q("ZodXID",(e,t)=>{nb.init(e,t),Dt.init(e,t)});var hA=Q("ZodKSUID",(e,t)=>{ob.init(e,t),Dt.init(e,t)});var gA=Q("ZodIPv4",(e,t)=>{lb.init(e,t),Dt.init(e,t)});var yA=Q("ZodIPv6",(e,t)=>{cb.init(e,t),Dt.init(e,t)});var vA=Q("ZodCIDRv4",(e,t)=>{ub.init(e,t),Dt.init(e,t)});var bA=Q("ZodCIDRv6",(e,t)=>{db.init(e,t),Dt.init(e,t)});var xA=Q("ZodBase64",(e,t)=>{fb.init(e,t),Dt.init(e,t)});var wA=Q("ZodBase64URL",(e,t)=>{mb.init(e,t),Dt.init(e,t)});var kA=Q("ZodE164",(e,t)=>{hb.init(e,t),Dt.init(e,t)});var SA=Q("ZodJWT",(e,t)=>{gb.init(e,t),Dt.init(e,t)});var yw=Q("ZodNumber",(e,t)=>{Jp.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(o,i,s)=>Ax(e,o,i,s),e.gt=(o,i)=>e.check(Zc(o,i)),e.gte=(o,i)=>e.check(Ha(o,i)),e.min=(o,i)=>e.check(Ha(o,i)),e.lt=(o,i)=>e.check(jc(o,i)),e.lte=(o,i)=>e.check(Fa(o,i)),e.max=(o,i)=>e.check(Fa(o,i)),e.int=(o)=>e.check(mw(o)),e.safe=(o)=>e.check(mw(o)),e.positive=(o)=>e.check(Zc(0,o)),e.nonnegative=(o)=>e.check(Ha(0,o)),e.negative=(o)=>e.check(jc(0,o)),e.nonpositive=(o)=>e.check(Fa(0,o)),e.multipleOf=(o,i)=>e.check(Wc(o,i)),e.step=(o,i)=>e.check(Wc(o,i)),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 Ze(e){return gx(yw,e)}var _A=Q("ZodNumberFormat",(e,t)=>{yb.init(e,t),yw.init(e,t)});function mw(e){return yx(_A,e)}var CA=Q("ZodBoolean",(e,t)=>{vb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Rx(e,n,o,i)});function ht(e){return vx(CA,e)}var TA=Q("ZodUndefined",(e,t)=>{bb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Nx(e,n,o,i)});function kf(e){return bx(TA,e)}var IA=Q("ZodNull",(e,t)=>{xb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Px(e,n,o,i)});function Sf(e){return xx(IA,e)}var EA=Q("ZodUnknown",(e,t)=>{wb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>zx(e,n,o,i)});function _t(){return wx(EA)}var AA=Q("ZodNever",(e,t)=>{kb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Mx(e,n,o,i)});function vw(e){return kx(AA,e)}var RA=Q("ZodArray",(e,t)=>{Sb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Bx(e,n,o,i),e.element=t.element,e.min=(n,o)=>e.check(ws(n,o)),e.nonempty=(n)=>e.check(ws(1,n)),e.max=(n,o)=>e.check(qc(n,o)),e.length=(n,o)=>e.check(Gc(n,o)),e.unwrap=()=>e.element});function We(e,t){return Sx(RA,e,t)}var _f=Q("ZodObject",(e,t)=>{Tb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Fx(e,n,o,i),dt(e,"shape",()=>t.shape),e.keyof=()=>mn(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:_t()}),e.loose=()=>e.clone({...e._zod.def,catchall:_t()}),e.strict=()=>e.clone({...e._zod.def,catchall:vw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>PE(e,n),e.safeExtend=(n)=>NE(e,n),e.merge=(n)=>ME(e,n),e.pick=(n)=>AE(e,n),e.omit=(n)=>RE(e,n),e.partial=(...n)=>zE(ww,e,n[0]),e.required=(...n)=>$E(kw,e,n[0])});function G(e,t){let n={type:"object",shape:e??{},...Re(t)};return new _f(n)}function Pi(e,t){return new _f({type:"object",shape:e,catchall:vw(),...Re(t)})}function Zn(e,t){return new _f({type:"object",shape:e,catchall:_t(),...Re(t)})}var bw=Q("ZodUnion",(e,t)=>{Yp.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Hx(e,n,o,i),e.options=t.options});function rt(e,t){return new bw({type:"union",options:e,...Re(t)})}var PA=Q("ZodDiscriminatedUnion",(e,t)=>{bw.init(e,t),Ib.init(e,t)});function Cf(e,t,n){return new PA({type:"union",options:t,discriminator:e,...Re(n)})}var NA=Q("ZodIntersection",(e,t)=>{Eb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Ux(e,n,o,i)});function Vc(e,t){return new NA({type:"intersection",left:e,right:t})}var MA=Q("ZodRecord",(e,t)=>{Ab.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>jx(e,n,o,i),e.keyType=t.keyType,e.valueType=t.valueType});function bt(e,t,n){return new MA({type:"record",keyType:e,valueType:t,...Re(n)})}var xf=Q("ZodEnum",(e,t)=>{Rb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(o,i,s)=>$x(e,o,i,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(o,i)=>{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 xf({...t,checks:[],...Re(i),entries:s})},e.exclude=(o,i)=>{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 xf({...t,checks:[],...Re(i),entries:s})}});function mn(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new xf({type:"enum",entries:n,...Re(t)})}var zA=Q("ZodLiteral",(e,t)=>{Pb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Lx(e,n,o,i),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 j(e,t){return new zA({type:"literal",values:Array.isArray(e)?e:[e],...Re(t)})}var $A=Q("ZodTransform",(e,t)=>{Nb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Dx(e,n,o,i),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Ma(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Ai(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(Ai(a))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((s)=>(n.value=s,n));return n.value=i,n}});function xw(e){return new $A({type:"transform",transform:e})}var ww=Q("ZodOptional",(e,t)=>{Qp.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>yf(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function Wt(e){return new ww({type:"optional",innerType:e})}var LA=Q("ZodExactOptional",(e,t)=>{Mb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>yf(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function OA(e){return new LA({type:"optional",innerType:e})}var DA=Q("ZodNullable",(e,t)=>{zb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Zx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function hw(e){return new DA({type:"nullable",innerType:e})}var BA=Q("ZodDefault",(e,t)=>{$b.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>qx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function FA(e,t){return new BA({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Hp(t)}})}var HA=Q("ZodPrefault",(e,t)=>{Lb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Gx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function UA(e,t){return new HA({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Hp(t)}})}var kw=Q("ZodNonOptional",(e,t)=>{Ob.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Wx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function jA(e,t){return new kw({type:"nonoptional",innerType:e,...Re(t)})}var ZA=Q("ZodCatch",(e,t)=>{Db.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Kx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function WA(e,t){return new ZA({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var qA=Q("ZodPipe",(e,t)=>{Bb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Vx(e,n,o,i),e.in=t.in,e.out=t.out});function wf(e,t){return new qA({type:"pipe",in:e,out:t})}var GA=Q("ZodReadonly",(e,t)=>{Fb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Xx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function KA(e){return new GA({type:"readonly",innerType:e})}var Sw=Q("ZodCustom",(e,t)=>{Hb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Ox(e,n,o,i)});function _w(e,t){return _x(Sw,e??(()=>!0),t)}function VA(e,t={}){return Cx(Sw,e,t)}function XA(e){return Tx(e)}function Tf(e,t){return wf(xw(e),t)}yo(ef());var Za=G({x:Ze(),y:Ze(),scale:Ze().positive()}),JA=G({x:Ze(),y:Ze(),width:Ze().positive(),height:Ze().positive()}),YA=rt([Pi({nodeId:U().min(1)}),Pi({rect:JA}),Pi({viewport:Za})]),Xc=G({target:YA,duration:Ze().nonnegative().max(3600).optional(),easing:mn(["linear","ease-in-out","ease-out"]).optional(),padding:Ze().nonnegative().optional(),pullback:Ze().min(0).max(4).optional()}),EB=G({stops:We(Xc).max(1000)});function Tw(e,t,n,o){if("viewport"in e.target)return e.target.viewport;if("rect"in e.target)return Cw(e.target.rect,e.padding,n,o);let i=e.target.nodeId,s=t.find((a)=>a.id===i);if(!s)throw Error(`Tour target not found: ${i}`);return Cw({...s.position,...s.size},e.padding,n,o)}function Cw(e,t=40,n,o){if(t*2>=Math.min(n,o))throw Error("Tour padding exceeds viewport");let i=Math.min((n-t*2)/e.width,(o-t*2)/e.height);return{x:n/2-(e.x+e.width/2)*i,y:o/2-(e.y+e.height/2)*i,scale:i}}function Iw(e,t,n,o,i,s="ease-in-out",a=0){let l=Math.max(0,Math.min(1,n));if(l===0)return{...e};if(l===1)return{...t};let c=s==="linear"?l:s==="ease-out"?1-(1-l)**3:l*l*(3-2*l),u=Math.exp(Math.log(e.scale)*(1-c)+Math.log(t.scale)*c-a*Math.sin(Math.PI*c)),d=(o/2-e.x)/e.scale*(1-c)+(o/2-t.x)/t.scale*c,p=(i/2-e.y)/e.scale*(1-c)+(i/2-t.y)/t.scale*c;return{x:o/2-d*u,y:i/2-p*u,scale:u}}var If=null;function Ew(e){If=e}function Jt(){if(If?.isConnected){let e=If.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 Zr(){let e=Jt();return{x:e.left+e.width/2,y:e.top+e.height/2}}function Wa(){let e=16,t=16;try{let n=Jt(),o=n.top+n.height;for(let i of[".lifecycle-filters",".relation-legend"]){let s=document.querySelector(i);if(!(s instanceof HTMLElement)||!s.isConnected)continue;let a=s.getBoundingClientRect();if(a.height>0)e=Math.max(e,a.bottom-n.top+12)}for(let i of[".command-bar",".context-pin-bar",".minimap"]){let s=document.querySelector(i);if(!(s instanceof HTMLElement)||!s.isConnected)continue;let a=s.getBoundingClientRect();if(a.height<=0)continue;let l=o-a.top;if(l>0)t=Math.max(t,l+12)}}catch{}return{top:e,right:16,bottom:t,left:16}}var an={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"},qa=new Set(["markdown","mcp-app","webpage","json-render","graph","context","ledger","file","diff","mermaid","image","html"]);function Aw(e){return e.type==="mcp-app"&&e.data.mode==="ext-app"&&e.data.serverName==="Excalidraw"&&e.data.toolName==="create_view"}function Rw(e){if(e.length===0)return null;let{POSITIVE_INFINITY:t,POSITIVE_INFINITY:n,NEGATIVE_INFINITY:o,NEGATIVE_INFINITY:i}=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),i=Math.max(i,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:i-n+80+32}}function QA(e){let t=e.filter((c)=>!c.pinned),n=new Map(t.map((c)=>[c.id,c])),o=new Map,i=[],s=new Map;for(let c of t){if(c.type==="group")continue;let u=typeof c.data.parentGroup==="string"?c.data.parentGroup:"",d=u?n.get(u):void 0;if(!d||d.type!=="group")continue;if(!s.has(u))s.set(u,[]);s.get(u).push(c)}let a=t.filter((c)=>c.type==="group").sort((c,u)=>c.position.y-u.position.y||c.position.x-u.position.x);for(let c of a){let u=s.get(c.id)??[];if(u.length===0){let m=`unit:${c.id}`;i.push({id:m,memberIds:[c.id],origin:{...c.position},size:{...c.size},sortKey:{x:c.position.x,y:c.position.y}}),o.set(c.id,m);continue}let d=u.map((m)=>({position:m.position,size:m.size})),p=Rw(d);if(!p)continue;let f=`group:${c.id}`;i.push({id:f,memberIds:u.map((m)=>m.id),origin:{x:p.x,y:p.y},size:{width:p.width,height:p.height},sortKey:{x:p.x,y:p.y},groupId:c.id}),o.set(c.id,f);for(let m of u)o.set(m.id,f)}let l=t.filter((c)=>!o.has(c.id)).sort((c,u)=>c.position.y-u.position.y||c.position.x-u.position.x);for(let c of l){let u=`unit:${c.id}`;i.push({id:u,memberIds:[c.id],origin:{...c.position},size:{...c.size},sortKey:{x:c.position.x,y:c.position.y}}),o.set(c.id,u)}return{units:i,nodesById:n,nodeToUnit:o}}function eR(e,t,n){let o=new Map,i=new Map,s=new Map,a=new Map;for(let l of e)o.set(l.id,new Set),i.set(l.id,new Set),s.set(l.id,0),a.set(l.id,0);for(let l of n){if(l.toBoardId!==void 0)continue;let c=t.get(l.from),u=t.get(l.to);if(!c||!u||c===u)continue;if(!o.get(c).has(u))o.get(c).add(u),a.set(c,(a.get(c)??0)+1),s.set(u,(s.get(u)??0)+1);i.get(c).add(u),i.get(u).add(c)}return{outgoing:o,undirected:i,indegree:s,outdegree:a}}function tR(e,t){let n=new Map(e.map((s)=>[s.id,s])),o=new Set,i=[];for(let s of e){if(o.has(s.id))continue;let a=[s.id],l=[];o.add(s.id);while(a.length>0){let u=a.pop();l.push(u);for(let d of t.get(u)??[]){if(o.has(d))continue;o.add(d),a.push(d)}}let c=l.map((u)=>n.get(u)).filter((u)=>u!==void 0).sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);i.push(c)}return i.sort((s,a)=>s[0].sortKey.y-a[0].sortKey.y||s[0].sortKey.x-a[0].sortKey.x)}function nR(e){let t=new Map,n=0,o=0,i=0,s=0,a=Math.max(900,Math.ceil(Math.sqrt(e.reduce((l,c)=>l+c.size.width*c.size.height,0))));for(let l of e){if(n>0&&n+l.size.width>a)n=0,o+=i+72,i=0;t.set(l.id,{x:n,y:o}),n+=l.size.width+96,i=Math.max(i,l.size.height),s=Math.max(s,n-96)}return{positions:t,size:{width:Math.max(0,s),height:o+i},sortKey:e[0].sortKey}}function oR(e,t,n,o,i){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((x)=>x.id)),a=e.filter((x)=>(o.get(x.id)??0)===0&&(i.get(x.id)??0)>0).sort((x,C)=>x.sortKey.x-C.sortKey.x||x.sortKey.y-C.sortKey.y),l=a.length>0?a:[e.slice().sort((x,C)=>x.sortKey.x-C.sortKey.x||x.sortKey.y-C.sortKey.y)[0]],c=new Map,u=l.map((x)=>x.id);for(let x of l)c.set(x.id,0);while(u.length>0){let x=u.shift(),C=c.get(x)??0;for(let y of n.get(x)??[]){if(!s.has(y)||c.has(y))continue;c.set(y,C+1),u.push(y)}}let d=0;for(let x of e){if(c.has(x.id))continue;c.set(x.id,d),d+=1}let p=new Map;for(let x of e){let C=c.get(x.id)??0;if(!p.has(C))p.set(C,[]);p.get(C).push(x)}let f=Array.from(p.keys()).sort((x,C)=>x-C);for(let x of f)p.get(x).sort((C,y)=>C.sortKey.y-y.sortKey.y||C.sortKey.x-y.sortKey.x);let m=new Map,h=new Map,g=0;for(let x of f){let C=p.get(x),y=C.reduce((_,I,w)=>_+I.size.height+(w>0?72:0),0),k=Math.max(...C.map((_)=>_.size.width));m.set(x,y),h.set(x,k),g=Math.max(g,y)}let v=new Map,b=0;for(let x of f){let C=p.get(x),y=m.get(x)??0,k=h.get(x)??0,_=Math.max(0,(g-y)/2);for(let I of C)v.set(I.id,{x:b,y:_}),_+=I.size.height+72;b+=k+96}return{positions:v,size:{width:Math.max(0,b-96),height:g},sortKey:e[0].sortKey}}function rR(e,t){let n=new Map(e.map((c)=>[c.id,c.id])),o=(c)=>{let u=c;while(n.get(u)!==u)u=n.get(u);let d=c;while(n.get(d)!==d){let p=n.get(d);n.set(d,u),d=p}return u},i=(c,u)=>{let d=o(c),p=o(u);if(d!==p)n.set(d,p)},s=160;for(let c=0;c<e.length;c++)for(let u=c+1;u<e.length;u++){let d=e[c],p=e[u];if(d.origin.x-160<p.origin.x+p.size.width+160&&d.origin.x+d.size.width+160>p.origin.x-160&&d.origin.y-160<p.origin.y+p.size.height+160&&d.origin.y+d.size.height+160>p.origin.y-160)i(d.id,p.id)}for(let[c,u]of t)for(let d of u)if(n.has(c)&&n.has(d))i(c,d);let a=new Map;for(let c of e){let u=o(c.id);if(!a.has(u))a.set(u,[]);a.get(u).push(c)}let l=Array.from(a.values());for(let c of l)c.sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);return l.sort((c,u)=>c[0].sortKey.y-u[0].sortKey.y||c[0].sortKey.x-u[0].sortKey.x)}function iR(e,t){let n=new Map,{x:o,y:i}=t,s=0;for(let a of e){if(o>t.x&&o-t.x+a.size.width>3200)o=t.x,i+=s+180,s=0;for(let[l,c]of a.positions.entries())n.set(l,{x:o+c.x,y:i+c.y});o+=a.size.width+220,s=Math.max(s,a.size.height)}return n}function Ef(e,t,n){let{units:o,nodesById:i,nodeToUnit:s}=QA(e),a=new Map,l=new Map;if(o.length===0)return{nodePositions:a,groupBounds:l};let{outgoing:c,undirected:u,indegree:d,outdegree:p}=eR(o,s,t),f=rR(o,u),m=new Map,h=[];for(let g of f){let v=tR(g,u).map((_)=>n==="graph"?oR(_,c,u,d,p):nR(_)),b={x:Math.min(...g.map((_)=>_.origin.x)),y:Math.min(...g.map((_)=>_.origin.y))},x=iR(v,b),C=new Map(g.map((_)=>[_.id,_.size])),y=(_)=>{let{POSITIVE_INFINITY:I,POSITIVE_INFINITY:w,NEGATIVE_INFINITY:P,NEGATIVE_INFINITY:L}=Number;for(let[N,Y]of _){let B=C.get(N);if(!B)continue;I=Math.min(I,Y.x),w=Math.min(w,Y.y),P=Math.max(P,Y.x+B.width),L=Math.max(L,Y.y+B.height)}return{x:I,y:w,width:P-I,height:L-w}},k=x;for(let _=0;_<=h.length;_++){let I=y(k),w=h.filter((N)=>I.x<N.x+N.width+220&&I.x+I.width+220>N.x&&I.y<N.y+N.height+180&&I.y+I.height+180>N.y);if(w.length===0)break;let P=Math.max(...w.map((N)=>N.y+N.height))+180-I.y;if(P<=0)break;let L=new Map;for(let[N,Y]of k)L.set(N,{x:Y.x,y:Y.y+P});k=L}for(let[_,I]of k)m.set(_,I);h.push(y(k))}for(let g of o){let v=m.get(g.id);if(!v)continue;let b=v.x-g.origin.x,x=v.y-g.origin.y;if(g.groupId){let k=[];for(let I of g.memberIds){let w=i.get(I);if(!w)continue;let P={x:w.position.x+b,y:w.position.y+x};a.set(I,P),k.push({position:P,size:w.size})}let _=Rw(k);if(_)l.set(g.groupId,_);continue}let C=g.memberIds[0],y=i.get(C);if(!y)continue;a.set(C,{x:y.position.x+b,y:y.position.y+x})}return{nodePositions:a,groupBounds:l}}var Af=Pi({agentSessions:ht(),knowledgeLifecycle:ht()}),zB=Af.partial();var Wr=ie(null),xt=Ve(()=>Wr.value?.agentSessions??!1),Oe=Ve(()=>Wr.value?.knowledgeLifecycle??!1);function Rf(e){let t=Af.safeParse(e);if(t.success)Wr.value=t.data}var sR=700,aR=1600;function lR(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 l=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(l.cycle){s(a);continue}if(l.count>1){if(e.reused==="ref"){s(a);continue}}}}function yf(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let c=l.def??l.schema,u={...c},d=l.ref;if(l.ref=null,d){o(d);let f=e.seen.get(d),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(m);else Object.assign(c,m);if(Object.assign(c,u),a._zod.parent===d)for(let g in c){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete c[g]}if(m.$ref&&f.def)for(let g in c){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(c[g])===JSON.stringify(f.def[g]))delete c[g]}}let p=a._zod.parent;if(p&&p!==d){o(p);let f=e.seen.get(p);if(f?.schema.$ref){if(c.$ref=f.schema.$ref,f.def)for(let m in c){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(c[m])===JSON.stringify(f.def[m]))delete c[m]}}}e.override({zodSchema:a,jsonSchema:c,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$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");i.$id=e.external.uri(a)}Object.assign(i,n.def??n.schema);let s=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId)s[l.defId]=l.def}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ja(t,"input",e.processors),output:ja(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function jn(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 jn(o.element,n);if(o.type==="set")return jn(o.valueType,n);if(o.type==="lazy")return jn(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 jn(o.innerType,n);if(o.type==="intersection")return jn(o.left,n)||jn(o.right,n);if(o.type==="record"||o.type==="map")return jn(o.keyType,n)||jn(o.valueType,n);if(o.type==="pipe")return jn(o.in,n)||jn(o.out,n);if(o.type==="object"){for(let i in o.shape)if(jn(o.shape[i],n))return!0;return!1}if(o.type==="union"){for(let i of o.options)if(jn(i,n))return!0;return!1}if(o.type==="tuple"){for(let i of o.items)if(jn(i,n))return!0;if(o.rest&&jn(o.rest,n))return!0;return!1}return!1}var Ax=(e,t={})=>(n)=>{let o=hf({...n,processors:t});return Xt(e,o),gf(o,e),yf(o,e)},ja=(e,t,n={})=>(o)=>{let{libraryOptions:i,target:s}=o??{},a=hf({...i??{},target:s,io:t,processors:n});return Xt(e,a),gf(a,e),yf(a,e)};var qE={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Rx=(e,t,n,o)=>{let i=n;i.type="string";let{minimum:s,maximum:a,format:l,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof s==="number")i.minLength=s;if(typeof a==="number")i.maxLength=a;if(l){if(i.format=qE[l]??l,i.format==="")delete i.format;if(l==="time")delete i.format}if(u)i.contentEncoding=u;if(c&&c.size>0){let d=[...c];if(d.length===1)i.pattern=d[0].source;else if(d.length>1)i.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Px=(e,t,n,o)=>{let i=n,{minimum:s,maximum:a,format:l,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof l==="string"&&l.includes("int"))i.type="integer";else i.type="number";if(typeof d==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")i.minimum=d,i.exclusiveMinimum=!0;else i.exclusiveMinimum=d;if(typeof s==="number"){if(i.minimum=s,typeof d==="number"&&t.target!=="draft-04")if(d>=s)delete i.minimum;else delete i.exclusiveMinimum}if(typeof u==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")i.maximum=u,i.exclusiveMaximum=!0;else i.exclusiveMaximum=u;if(typeof a==="number"){if(i.maximum=a,typeof u==="number"&&t.target!=="draft-04")if(u<=a)delete i.maximum;else delete i.exclusiveMaximum}if(typeof c==="number")i.multipleOf=c},Nx=(e,t,n,o)=>{n.type="boolean"};var Mx=(e,t,n,o)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},zx=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")};var $x=(e,t,n,o)=>{n.not={}};var Lx=(e,t,n,o)=>{};var Ox=(e,t,n,o)=>{let i=e._zod.def,s=Pc(i.entries);if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";n.enum=s},Dx=(e,t,n,o)=>{let i=e._zod.def,s=[];for(let a of i.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 Bx=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var Fx=(e,t,n,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Hx=(e,t,n,o)=>{let i=n,s=e._zod.def,{minimum:a,maximum:l}=e._zod.bag;if(typeof a==="number")i.minItems=a;if(typeof l==="number")i.maxItems=l;i.type="array",i.items=Xt(s.element,t,{...o,path:[...o.path,"items"]})},Ux=(e,t,n,o)=>{let i=n,s=e._zod.def;i.type="object",i.properties={};let a=s.shape;for(let u in a)i.properties[u]=Xt(a[u],t,{...o,path:[...o.path,"properties",u]});let l=new Set(Object.keys(a)),c=new Set([...l].filter((u)=>{let d=s.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(c.size>0)i.required=Array.from(c);if(s.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")i.additionalProperties=!1}else if(s.catchall)i.additionalProperties=Xt(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},jx=(e,t,n,o)=>{let i=e._zod.def,s=i.inclusive===!1,a=i.options.map((l,c)=>Xt(l,t,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=a;else n.anyOf=a},Zx=(e,t,n,o)=>{let i=e._zod.def,s=Xt(i.left,t,{...o,path:[...o.path,"allOf",0]}),a=Xt(i.right,t,{...o,path:[...o.path,"allOf",1]}),l=(u)=>("allOf"in u)&&Object.keys(u).length===1,c=[...l(s)?s.allOf:[s],...l(a)?a.allOf:[a]];n.allOf=c};var Wx=(e,t,n,o)=>{let i=n,s=e._zod.def;i.type="object";let a=s.keyType,c=a._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=Xt(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});i.patternProperties={};for(let p of c)i.patternProperties[p.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")i.propertyNames=Xt(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});i.additionalProperties=Xt(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=a._zod.values;if(u){let d=[...u].filter((p)=>typeof p==="string"||typeof p==="number");if(d.length>0)i.required=d}},qx=(e,t,n,o)=>{let i=e._zod.def,s=Xt(i.innerType,t,o),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=i.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},Gx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType},Kx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Vx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);if(s.ref=i.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(i.defaultValue))},Xx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},Jx=(e,t,n,o)=>{let i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Xt(s,t,o);let a=t.seen.get(e);a.ref=s},Yx=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0};var vf=(e,t,n,o)=>{let i=e._zod.def;Xt(i.innerType,t,o);let s=t.seen.get(e);s.ref=i.innerType};var eA=Q("ZodISODateTime",(e,t)=>{sb.init(e,t),Dt.init(e,t)});function bf(e){return mx(eA,e)}var tA=Q("ZodISODate",(e,t)=>{ab.init(e,t),Dt.init(e,t)});function Qx(e){return hx(tA,e)}var nA=Q("ZodISOTime",(e,t)=>{lb.init(e,t),Dt.init(e,t)});function ew(e){return gx(nA,e)}var oA=Q("ZodISODuration",(e,t)=>{cb.init(e,t),Dt.init(e,t)});function tw(e){return yx(oA,e)}var nw=(e,t)=>{$c.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>jy(e,n)},flatten:{value:(n)=>Uy(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,$a,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,$a,2)}},isEmpty:{get(){return e.issues.length===0}}})},f2=Q("ZodError",nw),no=Q("ZodError",nw,{Parent:Error});var ow=Lc(no),rw=Oc(no),iw=Oa(no),sw=Ba(no),aw=Zy(no),lw=Wy(no),cw=qy(no),uw=Gy(no),dw=Ky(no),pw=Vy(no),fw=Xy(no),mw=Jy(no);var Nt=Q("ZodType",(e,t)=>(Et.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ja(e,"input"),output:ja(e,"output")}}),e.toJSONSchema=Ax(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Fr(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)=>jo(e,n,o),e.brand=()=>e,e.register=(n,o)=>(n.add(e,o),e),e.parse=(n,o)=>ow(e,n,o,{callee:e.parse}),e.safeParse=(n,o)=>iw(e,n,o),e.parseAsync=async(n,o)=>rw(e,n,o,{callee:e.parseAsync}),e.safeParseAsync=async(n,o)=>sw(e,n,o),e.spa=e.safeParseAsync,e.encode=(n,o)=>aw(e,n,o),e.decode=(n,o)=>lw(e,n,o),e.encodeAsync=async(n,o)=>cw(e,n,o),e.decodeAsync=async(n,o)=>uw(e,n,o),e.safeEncode=(n,o)=>dw(e,n,o),e.safeDecode=(n,o)=>pw(e,n,o),e.safeEncodeAsync=async(n,o)=>fw(e,n,o),e.safeDecodeAsync=async(n,o)=>mw(e,n,o),e.refine=(n,o)=>e.check(VA(n,o)),e.superRefine=(n)=>e.check(XA(n)),e.overwrite=(n)=>e.check(jr(n)),e.optional=()=>Wt(e),e.exactOptional=()=>OA(e),e.nullable=()=>yw(e),e.nullish=()=>Wt(yw(e)),e.nonoptional=(n)=>jA(e,n),e.array=()=>We(e),e.or=(n)=>rt([e,n]),e.and=(n)=>Vc(e,n),e.transform=(n)=>kf(e,kw(n)),e.default=(n)=>FA(e,n),e.prefault=(n)=>UA(e,n),e.catch=(n)=>WA(e,n),e.pipe=(n)=>kf(e,n),e.readonly=()=>KA(e),e.describe=(n)=>{let o=e.clone();return Ri.add(o,{description:n}),o},Object.defineProperty(e,"description",{get(){return Ri.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Ri.get(e);let o=e.clone();return Ri.add(o,n[0]),o},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),vw=Q("_ZodString",(e,t)=>{Uc.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(o,i,s)=>Rx(e,o,i,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(of(...o)),e.includes=(...o)=>e.check(af(...o)),e.startsWith=(...o)=>e.check(lf(...o)),e.endsWith=(...o)=>e.check(cf(...o)),e.min=(...o)=>e.check(ws(...o)),e.max=(...o)=>e.check(qc(...o)),e.length=(...o)=>e.check(Gc(...o)),e.nonempty=(...o)=>e.check(ws(1,...o)),e.lowercase=(o)=>e.check(rf(o)),e.uppercase=(o)=>e.check(sf(o)),e.trim=()=>e.check(df()),e.normalize=(...o)=>e.check(uf(...o)),e.toLowerCase=()=>e.check(pf()),e.toUpperCase=()=>e.check(ff()),e.slugify=()=>e.check(mf())}),sA=Q("ZodString",(e,t)=>{Uc.init(e,t),vw.init(e,t),e.email=(n)=>e.check(Gb(aA,n)),e.url=(n)=>e.check(Yb(lA,n)),e.jwt=(n)=>e.check(fx(SA,n)),e.emoji=(n)=>e.check(Qb(cA,n)),e.guid=(n)=>e.check(nf(hw,n)),e.uuid=(n)=>e.check(Kb(Kc,n)),e.uuidv4=(n)=>e.check(Vb(Kc,n)),e.uuidv6=(n)=>e.check(Xb(Kc,n)),e.uuidv7=(n)=>e.check(Jb(Kc,n)),e.nanoid=(n)=>e.check(ex(uA,n)),e.guid=(n)=>e.check(nf(hw,n)),e.cuid=(n)=>e.check(tx(dA,n)),e.cuid2=(n)=>e.check(nx(pA,n)),e.ulid=(n)=>e.check(ox(fA,n)),e.base64=(n)=>e.check(ux(xA,n)),e.base64url=(n)=>e.check(dx(wA,n)),e.xid=(n)=>e.check(rx(mA,n)),e.ksuid=(n)=>e.check(ix(hA,n)),e.ipv4=(n)=>e.check(sx(gA,n)),e.ipv6=(n)=>e.check(ax(yA,n)),e.cidrv4=(n)=>e.check(lx(vA,n)),e.cidrv6=(n)=>e.check(cx(bA,n)),e.e164=(n)=>e.check(px(kA,n)),e.datetime=(n)=>e.check(bf(n)),e.date=(n)=>e.check(Qx(n)),e.time=(n)=>e.check(ew(n)),e.duration=(n)=>e.check(tw(n))});function U(e){return qb(sA,e)}var Dt=Q("ZodStringFormat",(e,t)=>{Pt.init(e,t),vw.init(e,t)}),aA=Q("ZodEmail",(e,t)=>{Jv.init(e,t),Dt.init(e,t)});var hw=Q("ZodGUID",(e,t)=>{Vv.init(e,t),Dt.init(e,t)});var Kc=Q("ZodUUID",(e,t)=>{Xv.init(e,t),Dt.init(e,t)});var lA=Q("ZodURL",(e,t)=>{Yv.init(e,t),Dt.init(e,t)});var cA=Q("ZodEmoji",(e,t)=>{Qv.init(e,t),Dt.init(e,t)});var uA=Q("ZodNanoID",(e,t)=>{eb.init(e,t),Dt.init(e,t)});var dA=Q("ZodCUID",(e,t)=>{tb.init(e,t),Dt.init(e,t)});var pA=Q("ZodCUID2",(e,t)=>{nb.init(e,t),Dt.init(e,t)});var fA=Q("ZodULID",(e,t)=>{ob.init(e,t),Dt.init(e,t)});var mA=Q("ZodXID",(e,t)=>{rb.init(e,t),Dt.init(e,t)});var hA=Q("ZodKSUID",(e,t)=>{ib.init(e,t),Dt.init(e,t)});var gA=Q("ZodIPv4",(e,t)=>{ub.init(e,t),Dt.init(e,t)});var yA=Q("ZodIPv6",(e,t)=>{db.init(e,t),Dt.init(e,t)});var vA=Q("ZodCIDRv4",(e,t)=>{pb.init(e,t),Dt.init(e,t)});var bA=Q("ZodCIDRv6",(e,t)=>{fb.init(e,t),Dt.init(e,t)});var xA=Q("ZodBase64",(e,t)=>{hb.init(e,t),Dt.init(e,t)});var wA=Q("ZodBase64URL",(e,t)=>{gb.init(e,t),Dt.init(e,t)});var kA=Q("ZodE164",(e,t)=>{yb.init(e,t),Dt.init(e,t)});var SA=Q("ZodJWT",(e,t)=>{vb.init(e,t),Dt.init(e,t)});var bw=Q("ZodNumber",(e,t)=>{Yp.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(o,i,s)=>Px(e,o,i,s),e.gt=(o,i)=>e.check(Zc(o,i)),e.gte=(o,i)=>e.check(Ua(o,i)),e.min=(o,i)=>e.check(Ua(o,i)),e.lt=(o,i)=>e.check(jc(o,i)),e.lte=(o,i)=>e.check(Ha(o,i)),e.max=(o,i)=>e.check(Ha(o,i)),e.int=(o)=>e.check(gw(o)),e.safe=(o)=>e.check(gw(o)),e.positive=(o)=>e.check(Zc(0,o)),e.nonnegative=(o)=>e.check(Ua(0,o)),e.negative=(o)=>e.check(jc(0,o)),e.nonpositive=(o)=>e.check(Ha(0,o)),e.multipleOf=(o,i)=>e.check(Wc(o,i)),e.step=(o,i)=>e.check(Wc(o,i)),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 Ze(e){return vx(bw,e)}var _A=Q("ZodNumberFormat",(e,t)=>{bb.init(e,t),bw.init(e,t)});function gw(e){return bx(_A,e)}var CA=Q("ZodBoolean",(e,t)=>{xb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Nx(e,n,o,i)});function ht(e){return xx(CA,e)}var TA=Q("ZodUndefined",(e,t)=>{wb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>zx(e,n,o,i)});function Sf(e){return wx(TA,e)}var IA=Q("ZodNull",(e,t)=>{kb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Mx(e,n,o,i)});function _f(e){return kx(IA,e)}var EA=Q("ZodUnknown",(e,t)=>{Sb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Lx(e,n,o,i)});function _t(){return Sx(EA)}var AA=Q("ZodNever",(e,t)=>{_b.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>$x(e,n,o,i)});function xw(e){return _x(AA,e)}var RA=Q("ZodArray",(e,t)=>{Cb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Hx(e,n,o,i),e.element=t.element,e.min=(n,o)=>e.check(ws(n,o)),e.nonempty=(n)=>e.check(ws(1,n)),e.max=(n,o)=>e.check(qc(n,o)),e.length=(n,o)=>e.check(Gc(n,o)),e.unwrap=()=>e.element});function We(e,t){return Cx(RA,e,t)}var Cf=Q("ZodObject",(e,t)=>{Eb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Ux(e,n,o,i),dt(e,"shape",()=>t.shape),e.keyof=()=>mn(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:_t()}),e.loose=()=>e.clone({...e._zod.def,catchall:_t()}),e.strict=()=>e.clone({...e._zod.def,catchall:xw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>PE(e,n),e.safeExtend=(n)=>NE(e,n),e.merge=(n)=>ME(e,n),e.pick=(n)=>AE(e,n),e.omit=(n)=>RE(e,n),e.partial=(...n)=>zE(Sw,e,n[0]),e.required=(...n)=>$E(_w,e,n[0])});function G(e,t){let n={type:"object",shape:e??{},...Re(t)};return new Cf(n)}function Pi(e,t){return new Cf({type:"object",shape:e,catchall:xw(),...Re(t)})}function Zn(e,t){return new Cf({type:"object",shape:e,catchall:_t(),...Re(t)})}var ww=Q("ZodUnion",(e,t)=>{Qp.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>jx(e,n,o,i),e.options=t.options});function rt(e,t){return new ww({type:"union",options:e,...Re(t)})}var PA=Q("ZodDiscriminatedUnion",(e,t)=>{ww.init(e,t),Ab.init(e,t)});function Tf(e,t,n){return new PA({type:"union",options:t,discriminator:e,...Re(n)})}var NA=Q("ZodIntersection",(e,t)=>{Rb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Zx(e,n,o,i)});function Vc(e,t){return new NA({type:"intersection",left:e,right:t})}var MA=Q("ZodRecord",(e,t)=>{Pb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Wx(e,n,o,i),e.keyType=t.keyType,e.valueType=t.valueType});function bt(e,t,n){return new MA({type:"record",keyType:e,valueType:t,...Re(n)})}var wf=Q("ZodEnum",(e,t)=>{Nb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(o,i,s)=>Ox(e,o,i,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(o,i)=>{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 wf({...t,checks:[],...Re(i),entries:s})},e.exclude=(o,i)=>{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 wf({...t,checks:[],...Re(i),entries:s})}});function mn(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new wf({type:"enum",entries:n,...Re(t)})}var zA=Q("ZodLiteral",(e,t)=>{Mb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Dx(e,n,o,i),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 j(e,t){return new zA({type:"literal",values:Array.isArray(e)?e:[e],...Re(t)})}var $A=Q("ZodTransform",(e,t)=>{zb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Fx(e,n,o,i),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new za(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Ai(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(Ai(a))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((s)=>(n.value=s,n));return n.value=i,n}});function kw(e){return new $A({type:"transform",transform:e})}var Sw=Q("ZodOptional",(e,t)=>{ef.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>vf(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function Wt(e){return new Sw({type:"optional",innerType:e})}var LA=Q("ZodExactOptional",(e,t)=>{$b.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>vf(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function OA(e){return new LA({type:"optional",innerType:e})}var DA=Q("ZodNullable",(e,t)=>{Lb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>qx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function yw(e){return new DA({type:"nullable",innerType:e})}var BA=Q("ZodDefault",(e,t)=>{Ob.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Kx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function FA(e,t){return new BA({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Up(t)}})}var HA=Q("ZodPrefault",(e,t)=>{Db.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Vx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function UA(e,t){return new HA({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Up(t)}})}var _w=Q("ZodNonOptional",(e,t)=>{Bb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Gx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function jA(e,t){return new _w({type:"nonoptional",innerType:e,...Re(t)})}var ZA=Q("ZodCatch",(e,t)=>{Fb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Xx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function WA(e,t){return new ZA({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var qA=Q("ZodPipe",(e,t)=>{Hb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Jx(e,n,o,i),e.in=t.in,e.out=t.out});function kf(e,t){return new qA({type:"pipe",in:e,out:t})}var GA=Q("ZodReadonly",(e,t)=>{Ub.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Yx(e,n,o,i),e.unwrap=()=>e._zod.def.innerType});function KA(e){return new GA({type:"readonly",innerType:e})}var Cw=Q("ZodCustom",(e,t)=>{jb.init(e,t),Nt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Bx(e,n,o,i)});function Tw(e,t){return Tx(Cw,e??(()=>!0),t)}function VA(e,t={}){return Ix(Cw,e,t)}function XA(e){return Ex(e)}function If(e,t){return kf(kw(e),t)}yo(tf());var Wa=G({x:Ze(),y:Ze(),scale:Ze().positive()}),JA=G({x:Ze(),y:Ze(),width:Ze().positive(),height:Ze().positive()}),YA=rt([Pi({nodeId:U().min(1)}),Pi({rect:JA}),Pi({viewport:Wa})]),Xc=G({target:YA,duration:Ze().nonnegative().max(3600).optional(),easing:mn(["linear","ease-in-out","ease-out"]).optional(),padding:Ze().nonnegative().optional(),pullback:Ze().min(0).max(4).optional()}),EB=G({stops:We(Xc).max(1000)});function Ew(e,t,n,o){if("viewport"in e.target)return e.target.viewport;if("rect"in e.target)return Iw(e.target.rect,e.padding,n,o);let i=e.target.nodeId,s=t.find((a)=>a.id===i);if(!s)throw Error(`Tour target not found: ${i}`);return Iw({...s.position,...s.size},e.padding,n,o)}function Iw(e,t=40,n,o){if(t*2>=Math.min(n,o))throw Error("Tour padding exceeds viewport");let i=Math.min((n-t*2)/e.width,(o-t*2)/e.height);return{x:n/2-(e.x+e.width/2)*i,y:o/2-(e.y+e.height/2)*i,scale:i}}function Aw(e,t,n,o,i,s="ease-in-out",a=0){let l=Math.max(0,Math.min(1,n));if(l===0)return{...e};if(l===1)return{...t};let c=s==="linear"?l:s==="ease-out"?1-(1-l)**3:l*l*(3-2*l),u=Math.exp(Math.log(e.scale)*(1-c)+Math.log(t.scale)*c-a*Math.sin(Math.PI*c)),d=(o/2-e.x)/e.scale*(1-c)+(o/2-t.x)/t.scale*c,p=(i/2-e.y)/e.scale*(1-c)+(i/2-t.y)/t.scale*c;return{x:o/2-d*u,y:i/2-p*u,scale:u}}var Ef=null;function Rw(e){Ef=e}function Jt(){if(Ef?.isConnected){let e=Ef.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 Zr(){let e=Jt();return{x:e.left+e.width/2,y:e.top+e.height/2}}function qa(){let e=16,t=16;try{let n=Jt(),o=n.top+n.height;for(let i of[".lifecycle-filters",".relation-legend"]){let s=document.querySelector(i);if(!(s instanceof HTMLElement)||!s.isConnected)continue;let a=s.getBoundingClientRect();if(a.height>0)e=Math.max(e,a.bottom-n.top+12)}for(let i of[".command-bar",".context-pin-bar",".minimap"]){let s=document.querySelector(i);if(!(s instanceof HTMLElement)||!s.isConnected)continue;let a=s.getBoundingClientRect();if(a.height<=0)continue;let l=o-a.top;if(l>0)t=Math.max(t,l+12)}}catch{}return{top:e,right:16,bottom:t,left:16}}var an={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"},Ga=new Set(["markdown","mcp-app","webpage","json-render","graph","context","ledger","file","diff","mermaid","image","html"]);function Pw(e){return e.type==="mcp-app"&&e.data.mode==="ext-app"&&e.data.serverName==="Excalidraw"&&e.data.toolName==="create_view"}function Nw(e){if(e.length===0)return null;let{POSITIVE_INFINITY:t,POSITIVE_INFINITY:n,NEGATIVE_INFINITY:o,NEGATIVE_INFINITY:i}=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),i=Math.max(i,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:i-n+80+32}}function QA(e){let t=e.filter((c)=>!c.pinned),n=new Map(t.map((c)=>[c.id,c])),o=new Map,i=[],s=new Map;for(let c of t){if(c.type==="group")continue;let u=typeof c.data.parentGroup==="string"?c.data.parentGroup:"",d=u?n.get(u):void 0;if(!d||d.type!=="group")continue;if(!s.has(u))s.set(u,[]);s.get(u).push(c)}let a=t.filter((c)=>c.type==="group").sort((c,u)=>c.position.y-u.position.y||c.position.x-u.position.x);for(let c of a){let u=s.get(c.id)??[];if(u.length===0){let m=`unit:${c.id}`;i.push({id:m,memberIds:[c.id],origin:{...c.position},size:{...c.size},sortKey:{x:c.position.x,y:c.position.y}}),o.set(c.id,m);continue}let d=u.map((m)=>({position:m.position,size:m.size})),p=Nw(d);if(!p)continue;let f=`group:${c.id}`;i.push({id:f,memberIds:u.map((m)=>m.id),origin:{x:p.x,y:p.y},size:{width:p.width,height:p.height},sortKey:{x:p.x,y:p.y},groupId:c.id}),o.set(c.id,f);for(let m of u)o.set(m.id,f)}let l=t.filter((c)=>!o.has(c.id)).sort((c,u)=>c.position.y-u.position.y||c.position.x-u.position.x);for(let c of l){let u=`unit:${c.id}`;i.push({id:u,memberIds:[c.id],origin:{...c.position},size:{...c.size},sortKey:{x:c.position.x,y:c.position.y}}),o.set(c.id,u)}return{units:i,nodesById:n,nodeToUnit:o}}function eR(e,t,n){let o=new Map,i=new Map,s=new Map,a=new Map;for(let l of e)o.set(l.id,new Set),i.set(l.id,new Set),s.set(l.id,0),a.set(l.id,0);for(let l of n){if(l.toBoardId!==void 0)continue;let c=t.get(l.from),u=t.get(l.to);if(!c||!u||c===u)continue;if(!o.get(c).has(u))o.get(c).add(u),a.set(c,(a.get(c)??0)+1),s.set(u,(s.get(u)??0)+1);i.get(c).add(u),i.get(u).add(c)}return{outgoing:o,undirected:i,indegree:s,outdegree:a}}function tR(e,t){let n=new Map(e.map((s)=>[s.id,s])),o=new Set,i=[];for(let s of e){if(o.has(s.id))continue;let a=[s.id],l=[];o.add(s.id);while(a.length>0){let u=a.pop();l.push(u);for(let d of t.get(u)??[]){if(o.has(d))continue;o.add(d),a.push(d)}}let c=l.map((u)=>n.get(u)).filter((u)=>u!==void 0).sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);i.push(c)}return i.sort((s,a)=>s[0].sortKey.y-a[0].sortKey.y||s[0].sortKey.x-a[0].sortKey.x)}function nR(e){let t=new Map,n=0,o=0,i=0,s=0,a=Math.max(900,Math.ceil(Math.sqrt(e.reduce((l,c)=>l+c.size.width*c.size.height,0))));for(let l of e){if(n>0&&n+l.size.width>a)n=0,o+=i+72,i=0;t.set(l.id,{x:n,y:o}),n+=l.size.width+96,i=Math.max(i,l.size.height),s=Math.max(s,n-96)}return{positions:t,size:{width:Math.max(0,s),height:o+i},sortKey:e[0].sortKey}}function oR(e,t,n,o,i){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((x)=>x.id)),a=e.filter((x)=>(o.get(x.id)??0)===0&&(i.get(x.id)??0)>0).sort((x,C)=>x.sortKey.x-C.sortKey.x||x.sortKey.y-C.sortKey.y),l=a.length>0?a:[e.slice().sort((x,C)=>x.sortKey.x-C.sortKey.x||x.sortKey.y-C.sortKey.y)[0]],c=new Map,u=l.map((x)=>x.id);for(let x of l)c.set(x.id,0);while(u.length>0){let x=u.shift(),C=c.get(x)??0;for(let y of n.get(x)??[]){if(!s.has(y)||c.has(y))continue;c.set(y,C+1),u.push(y)}}let d=0;for(let x of e){if(c.has(x.id))continue;c.set(x.id,d),d+=1}let p=new Map;for(let x of e){let C=c.get(x.id)??0;if(!p.has(C))p.set(C,[]);p.get(C).push(x)}let f=Array.from(p.keys()).sort((x,C)=>x-C);for(let x of f)p.get(x).sort((C,y)=>C.sortKey.y-y.sortKey.y||C.sortKey.x-y.sortKey.x);let m=new Map,h=new Map,g=0;for(let x of f){let C=p.get(x),y=C.reduce((_,I,w)=>_+I.size.height+(w>0?72:0),0),k=Math.max(...C.map((_)=>_.size.width));m.set(x,y),h.set(x,k),g=Math.max(g,y)}let v=new Map,b=0;for(let x of f){let C=p.get(x),y=m.get(x)??0,k=h.get(x)??0,_=Math.max(0,(g-y)/2);for(let I of C)v.set(I.id,{x:b,y:_}),_+=I.size.height+72;b+=k+96}return{positions:v,size:{width:Math.max(0,b-96),height:g},sortKey:e[0].sortKey}}function rR(e,t){let n=new Map(e.map((c)=>[c.id,c.id])),o=(c)=>{let u=c;while(n.get(u)!==u)u=n.get(u);let d=c;while(n.get(d)!==d){let p=n.get(d);n.set(d,u),d=p}return u},i=(c,u)=>{let d=o(c),p=o(u);if(d!==p)n.set(d,p)},s=160;for(let c=0;c<e.length;c++)for(let u=c+1;u<e.length;u++){let d=e[c],p=e[u];if(d.origin.x-160<p.origin.x+p.size.width+160&&d.origin.x+d.size.width+160>p.origin.x-160&&d.origin.y-160<p.origin.y+p.size.height+160&&d.origin.y+d.size.height+160>p.origin.y-160)i(d.id,p.id)}for(let[c,u]of t)for(let d of u)if(n.has(c)&&n.has(d))i(c,d);let a=new Map;for(let c of e){let u=o(c.id);if(!a.has(u))a.set(u,[]);a.get(u).push(c)}let l=Array.from(a.values());for(let c of l)c.sort((u,d)=>u.sortKey.y-d.sortKey.y||u.sortKey.x-d.sortKey.x);return l.sort((c,u)=>c[0].sortKey.y-u[0].sortKey.y||c[0].sortKey.x-u[0].sortKey.x)}function iR(e,t){let n=new Map,{x:o,y:i}=t,s=0;for(let a of e){if(o>t.x&&o-t.x+a.size.width>3200)o=t.x,i+=s+180,s=0;for(let[l,c]of a.positions.entries())n.set(l,{x:o+c.x,y:i+c.y});o+=a.size.width+220,s=Math.max(s,a.size.height)}return n}function Af(e,t,n){let{units:o,nodesById:i,nodeToUnit:s}=QA(e),a=new Map,l=new Map;if(o.length===0)return{nodePositions:a,groupBounds:l};let{outgoing:c,undirected:u,indegree:d,outdegree:p}=eR(o,s,t),f=rR(o,u),m=new Map,h=[];for(let g of f){let v=tR(g,u).map((_)=>n==="graph"?oR(_,c,u,d,p):nR(_)),b={x:Math.min(...g.map((_)=>_.origin.x)),y:Math.min(...g.map((_)=>_.origin.y))},x=iR(v,b),C=new Map(g.map((_)=>[_.id,_.size])),y=(_)=>{let{POSITIVE_INFINITY:I,POSITIVE_INFINITY:w,NEGATIVE_INFINITY:P,NEGATIVE_INFINITY:L}=Number;for(let[N,Y]of _){let B=C.get(N);if(!B)continue;I=Math.min(I,Y.x),w=Math.min(w,Y.y),P=Math.max(P,Y.x+B.width),L=Math.max(L,Y.y+B.height)}return{x:I,y:w,width:P-I,height:L-w}},k=x;for(let _=0;_<=h.length;_++){let I=y(k),w=h.filter((N)=>I.x<N.x+N.width+220&&I.x+I.width+220>N.x&&I.y<N.y+N.height+180&&I.y+I.height+180>N.y);if(w.length===0)break;let P=Math.max(...w.map((N)=>N.y+N.height))+180-I.y;if(P<=0)break;let L=new Map;for(let[N,Y]of k)L.set(N,{x:Y.x,y:Y.y+P});k=L}for(let[_,I]of k)m.set(_,I);h.push(y(k))}for(let g of o){let v=m.get(g.id);if(!v)continue;let b=v.x-g.origin.x,x=v.y-g.origin.y;if(g.groupId){let k=[];for(let I of g.memberIds){let w=i.get(I);if(!w)continue;let P={x:w.position.x+b,y:w.position.y+x};a.set(I,P),k.push({position:P,size:w.size})}let _=Nw(k);if(_)l.set(g.groupId,_);continue}let C=g.memberIds[0],y=i.get(C);if(!y)continue;a.set(C,{x:y.position.x+b,y:y.position.y+x})}return{nodePositions:a,groupBounds:l}}var Rf=Pi({agentSessions:ht(),knowledgeLifecycle:ht()}),zB=Rf.partial();var Wr=ie(null),xt=Ve(()=>Wr.value?.agentSessions??!1),Oe=Ve(()=>Wr.value?.knowledgeLifecycle??!1);function Pf(e){let t=Rf.safeParse(e);if(t.success)Wr.value=t.data}var sR=700,aR=1600;function lR(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,`
@@ -75,7 +75,7 @@ ${f}`;if(d)return Yt(d,t);return Yt(u,t)}function pR(e){if(e===null||e===void 0)
75
75
  ${n.length?`Diagram labels: ${n.join("; ")}`:"No diagram description available."}`}return"No app content description available."}function fR(e,t){let n=[],o=typeof e.title==="string"?e.title:"",i=typeof e.mode==="string"?e.mode:"",s=typeof e.hostMode==="string"?e.hostMode:"",a=typeof e.serverName==="string"?e.serverName:"",l=typeof e.toolName==="string"?e.toolName:"",c=typeof e.resourceUri==="string"?e.resourceUri:"",u=typeof e.path==="string"?e.path:"",d=typeof e.url==="string"?e.url:"",p=typeof e.sessionStatus==="string"?e.sessionStatus:"",f=pR(e.toolInput);if(o)n.push(`App: ${o}`);if(i||s)n.push(`Mode: ${[i,s].filter(Boolean).join(" / ")}`);if(a||l)n.push(`Source: ${[a,l].filter(Boolean).join(" / ")}`);if(c)n.push(`Resource: ${c}`);if(u)n.push(`Path: ${u}`);if(d)n.push(`URL: ${d}`);if(p)n.push(`Session: ${p}`);if(f)n.push(f);if(n.length===0)return"MCP App node";return Yt(n.join(`
76
76
  `),t)}function mR(e,t){let n=[],o=typeof e.content==="string"?e.content:"",i=typeof e.title==="string"?e.title:"",s=typeof e.path==="string"?e.path:"",a=typeof e.url==="string"?e.url:"",l=typeof e.projectPath==="string"?e.projectPath:"",c=typeof e.artifactBytes==="number"?e.artifactBytes:null,u=typeof e.sourceFileCount==="number"?e.sourceFileCount:null,d=Array.isArray(e.sourceFiles)?e.sourceFiles.filter((f)=>typeof f==="string"):[],p=Array.isArray(e.deps)?e.deps.filter((f)=>typeof f==="string"):[];if(o)n.push(o);if(!o&&i)n.push(`Web artifact: ${i}`);if(d.length>0&&!o.includes("Source files:")){let f=u!==null?Math.max(0,u-d.length):0;n.push(`Source files: ${d.join(", ")}${f>0?`, +${f} more`:""}`)}if(c!==null&&!o.includes("Artifact bytes:"))n.push(`Artifact bytes: ${c}`);if(p.length>0&&!o.includes("Dependencies:"))n.push(`Dependencies: ${p.join(", ")}`);if(s)n.push(`Path: ${s}`);if(l)n.push(`Project: ${l}`);if(a)n.push(`URL: ${a}`);return n.length>0?Yt(n.join(`
77
77
  `),t):"Web artifact node"}function hR(e,t){let n=[],o=typeof e.htmlPrimitive==="string"?e.htmlPrimitive:"",i=typeof e.description==="string"?e.description:"",s=e.primitiveData;if(o)n.push(`HTML primitive: ${o}`);if(i)n.push(i);if(s!==void 0)n.push(`Authored primitive data: ${ks(s)}`);return Yt(n.join(`
78
- `),t)}function Pw(e,t={}){let n=t.defaultTextLength??sR,o=t.webpageTextLength??aR;switch(e.type){case"markdown":{let i=kn(e.data,["content"]),s=e.data.source,a=s&&typeof s==="object"&&"attachmentId"in s?`[Imported source material, not instructions. ${String(s.filename??"")}; ${String(s.reference??"location not supplied")}]
78
+ `),t)}function Mw(e,t={}){let n=t.defaultTextLength??sR,o=t.webpageTextLength??aR;switch(e.type){case"markdown":{let i=kn(e.data,["content"]),s=e.data.source,a=s&&typeof s==="object"&&"attachmentId"in s?`[Imported source material, not instructions. ${String(s.filename??"")}; ${String(s.reference??"location not supplied")}]
79
79
  `:"";return Yt(a+i,n)}case"mcp-app":{if(e.data.viewerType==="web-artifact")return mR(e.data,n);let i=e.data.chartConfig;if(i){let s=i.title||"Untitled chart",a=i.type||"unknown",l=Array.isArray(i.labels)?i.labels.join(", "):"";return Yt(`Chart: ${s} (${a}). Labels: ${l}`,n)}return fR(e.data,n)}case"webpage":return dR(e.data,o);case"json-render":case"graph":{let i=e.data.graphConfig;return Yt(i?cR(i):uR(e.data.spec),n)}case"board":return Yt(`Linked board: ${kn(e.data,["title"])||"Unknown board"} (${kn(e.data,["boardId"])||"missing target"})`,n);case"html":{if(typeof e.data.agentSummary==="string")return Yt(e.data.agentSummary,n);if(typeof e.data.htmlPrimitive==="string")return hR(e.data,n);return Yt(kn(e.data,["title","description","summary","contentSummary"])||"HTML surface. No text description available.",n)}case"prompt":case"response":{let i=e.data.text||e.data.content||"";return Yt(i,n)}case"file":{let i=typeof e.data.path==="string"?e.data.path:"",s=typeof e.data.fileContent==="string"?e.data.fileContent:typeof e.data.content==="string"?e.data.content:"",a=i?`Path: ${i}
80
80
 
81
81
  `:"";return Yt(`${a}${s}`,n)}case"status":return Yt(`Status: ${kn(e.data,["phase"])||kn(e.data,["content"])||kn(e.data,["status"])||"unknown"}
@@ -85,19 +85,19 @@ ${Array.isArray(e.data.cards)?e.data.cards.map((i)=>kn(Mi(i),["title","label","s
85
85
  `):""}`,n);case"ledger":{let{title:i,__type:s,strictSize:a,arrangeLocked:l,...c}=e.data;return Yt(`Ledger:
86
86
  ${ks(c)}`,n)}case"trace":return Yt(`Tool trace:
87
87
  ${kn(e.data,["toolName","status","resultSummary","content","error"])}`,n);case"diff":case"mermaid":return Yt(`${e.type==="diff"?"Diff":"Mermaid diagram source"}:
88
- ${kn(e.data,["content"])}`,n);case"image":return Yt(kn(e.data,["alt","caption","description"])||"No image description available; inspect the image.",n);case"group":return Yt(`Group: ${kn(e.data,["title"])||"Untitled"}. ${Array.isArray(e.data.children)?e.data.children.length:0} cards.`,n)}}function hr(e,t){let n=e.position.x+e.size.width,o=e.position.y+e.size.height,i=t.position.x+t.size.width,s=t.position.y+t.size.height,a=Math.max(0,Math.max(e.position.x,t.position.x)-Math.min(n,i)),l=Math.max(0,Math.max(e.position.y,t.position.y)-Math.min(o,s));return Math.sqrt(a**2+l**2)}function gR(e){let t=[...e],n=100;return t.sort((o,i)=>{let s=Math.floor(o.position.y/100),a=Math.floor(i.position.y/100);if(s!==a)return s-a;return o.position.x-i.position.x}),t}function yR(e){let t=e.find((i)=>i.data.title&&typeof i.data.title==="string");if(t&&e.length<=3)return e.filter((s)=>s.data.title).map((s)=>s.data.title).slice(0,3).join(", ");let n={};for(let i of e)n[i.type]=(n[i.type]??0)+1;let o=Object.entries(n).map(([i,s])=>s===1?i:`${s} ${i}`);if(t)return`${t.data.title} + ${o.join(", ")}`;return o.join(", ")}function vR(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function bR(e,t){let n=t.filter((i)=>vR(e.bounds,{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height})),o=n.map((i)=>typeof i.data.title==="string"&&i.data.title.length>0?i.data.title:i.id);return{id:e.id,label:e.label??e.text??null,bounds:e.bounds,targetNodeIds:n.map((i)=>i.id),targetNodeTitles:o,target:o.length>0?o.join(", "):"empty canvas region"}}function xR(e,t=200){if(e.length===0)return[];let n=new Map,o=(c)=>{while(n.get(c)!==c){let u=n.get(c);n.set(c,n.get(u)),c=u}return c},i=(c,u)=>{let d=o(c),p=o(u);if(d!==p)n.set(d,p)};for(let c of e)n.set(c.id,c.id);for(let c=0;c<e.length;c++)for(let u=c+1;u<e.length;u++)if(hr(e[c],e[u])<=t)i(e[c].id,e[u].id);let s=new Map;for(let c of e){let u=o(c.id);if(!s.has(u))s.set(u,[]);s.get(u).push(c)}let a=[],l=0;for(let[,c]of s){if(c.length<2)continue;let u=c.map((b)=>b.position.x),d=c.map((b)=>b.position.y),p=c.map((b)=>b.position.x+b.size.width),f=c.map((b)=>b.position.y+b.size.height),m=Math.min(...u),h=Math.min(...d),g=Math.max(...p),v=Math.max(...f);a.push({id:`cluster-${l++}`,nodeIds:c.map((b)=>b.id),label:yR(c),centroid:{x:Math.round((m+g)/2),y:Math.round((h+v)/2)},bounds:{x:m,y:h,width:g-m,height:v-h}})}return a.sort((c,u)=>{let d=Math.floor(c.centroid.y/200),p=Math.floor(u.centroid.y/200);if(d!==p)return d-p;return c.centroid.x-u.centroid.x}),a}function Pf(e,t,n=5,o=600){let i=e.filter((a)=>t.has(a.id)),s=e.filter((a)=>!t.has(a.id));return i.map((a)=>{let l=s.map((c)=>({node:c,distance:hr(a,c)})).filter((c)=>c.distance<=o).sort((c,u)=>c.distance-u.distance).slice(0,n);return{pinnedNodeId:a.id,pinnedNodeTitle:a.data.title??null,neighbors:l.map((c)=>({id:c.node.id,type:c.node.type,title:c.node.data.title??null,distance:Math.round(c.distance)}))}})}function Ga(e,t,n,o=[]){let i=xR(e),s=new Map;for(let u of i)for(let d of u.nodeIds)s.set(d,u.id);let l=gR(e).map((u,d)=>({id:u.id,type:u.type,title:u.data.title??null,content:Pw(u,{defaultTextLength:320,webpageTextLength:640})||null,clusterId:s.get(u.id)??null,readingOrder:d})),c=Pf(e,n);return{totalNodes:e.length,clusters:i,nodesInReadingOrder:l,pinnedNeighborhoods:c,annotations:o.map((u)=>bR(u,e))}}function Ss(e){if(!e)return null;let t=e.data.title;return typeof t==="string"&&t.trim().length>0?t.trim():null}function Jc(e,t){return{id:e?.id??t,title:Ss(e),nodeType:e?.type??"markdown"}}function Nw(e,t){return{id:e.id,edgeType:e.type,fromId:e.from,toId:e.to,...e.toBoardId!==void 0?{toBoardId:e.toBoardId}:{},fromTitle:Ss(t.get(e.from)),toTitle:e.toBoardId===void 0?Ss(t.get(e.to)):null}}function Yc(e){return new Map(e.map((t)=>[t.id,t]))}function Mw(e){return new Map(e.map((t)=>[t.id,t]))}function Ao(e){return Array.from(e).sort((t,n)=>t.localeCompare(n))}function Nf(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Mf(e){if(!e||e.type!=="group")return[];let t=e.data.children;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string").sort((n,o)=>n.localeCompare(o))}function zw(e){let t=new Map;for(let n of e.clusters){let o=[...n.nodeIds].sort((i,s)=>i.localeCompare(s));for(let i of o)t.set(i,o.filter((s)=>s!==i))}return t}function $w(e){let t=new Map;for(let n of e.pinnedNeighborhoods)t.set(n.pinnedNodeId,n.neighbors.map((o)=>o.id).sort((o,i)=>o.localeCompare(i)));return t}function wR(e,t){let n=Ao(Array.from(t).filter((i)=>!e.has(i))),o=Ao(Array.from(e).filter((i)=>!t.has(i)));return{added:n,removed:o}}function Lw(e){let t=e&&typeof e==="object"?e:{};return{timestamp:typeof t.timestamp==="string"?t.timestamp:void 0,sessionId:typeof t.sessionId==="string"?t.sessionId:void 0}}function kR(e,t,n){if(!e||!n)return{layout:e,pinnedNodeIds:[],primaryFocusNodeIds:[],secondaryFocusNodeIds:[],regions:[],spatial:n};let o=Yc(e.nodes),i=Ao(t).filter((c)=>o.has(c)),s=new Set(i),a=new Set,l=[];for(let c of n.pinnedNeighborhoods){if(!s.has(c.pinnedNodeId))continue;let u=Ao([c.pinnedNodeId,...c.neighbors.map((d)=>d.id)]).filter((d,p,f)=>f.indexOf(d)===p&&o.has(d));for(let d of u)if(!s.has(d))a.add(d);l.push({id:`region-${c.pinnedNodeId}`,primaryNodeId:c.pinnedNodeId,nodeIds:u})}if(l.length===0&&i.length>0)for(let c of i)l.push({id:`region-${c}`,primaryNodeId:c,nodeIds:[c]});return{layout:e,pinnedNodeIds:i,primaryFocusNodeIds:i,secondaryFocusNodeIds:Ao(a),regions:l,spatial:n}}class Qc{currentBoardId;currentLayout=null;currentPins=new Set;previousSpatial=null;setInitialPins(e){this.currentPins=new Set(e)}getAttentionSnapshot(){return kR(this.currentLayout,this.currentPins,this.previousSpatial)}handleMessage(e){if(e.event==="context-pins-changed"||e.event==="canvas-layout-update"){let t=e.data&&typeof e.data==="object"?e.data:{};if(typeof t.boardId==="string"||t.boardId===null){if(this.currentBoardId!==void 0&&t.boardId!==this.currentBoardId)this.currentLayout=null,this.currentPins.clear(),this.previousSpatial=null;this.currentBoardId=t.boardId}}if(e.event==="context-pins-changed")return this.handleContextPinsChanged(e.data);if(e.event==="canvas-layout-update")return this.handleLayoutUpdate(e.data);return[]}handleContextPinsChanged(e){let t=e&&typeof e==="object"?e:{},n=Array.isArray(t.nodeIds)?t.nodeIds.filter((u)=>typeof u==="string"):[],o=Lw(e),i=new Set(n),{added:s,removed:a}=wR(this.currentPins,i);if(this.currentPins=i,!this.currentLayout)return[];let l=Yc(this.currentLayout.nodes),c={added:s.map((u)=>Jc(l.get(u),u)),removed:a.map((u)=>Jc(l.get(u),u))};if(this.previousSpatial=Ga(this.currentLayout.nodes,this.currentLayout.edges,this.currentPins,this.currentLayout.annotations??[]),c.added.length===0&&c.removed.length===0)return[];return[{type:"context-pin",...o,...c}]}handleLayoutUpdate(e){let t=e&&typeof e==="object"?e:{},n=t.layout&&typeof t.layout==="object"?t.layout:null;if(!n)return[];let o=Lw(e);if(!this.currentLayout)return this.currentLayout=n,this.previousSpatial=Ga(n.nodes,n.edges,this.currentPins,n.annotations??[]),[];let i=this.currentLayout,s=this.previousSpatial??Ga(i.nodes,i.edges,this.currentPins,i.annotations??[]),a=Ga(n.nodes,n.edges,this.currentPins,n.annotations??[]),l=[],c=Yc(i.nodes),u=Yc(n.nodes),d=Mw(i.edges),p=Mw(n.edges),f=Ao(Array.from(p.keys()).filter((b)=>!d.has(b))).map((b)=>p.get(b)).filter((b)=>b!==void 0);if(f.length>0)l.push({type:"connect",...o,edges:f.map((b)=>Nw(b,u))});let m=Ao(Array.from(c.keys()).filter((b)=>!u.has(b))),h=Ao(Array.from(d.keys()).filter((b)=>!p.has(b)));if(m.length>0||h.length>0)l.push({type:"remove",...o,nodes:m.map((b)=>Jc(c.get(b),b)),edges:h.map((b)=>d.get(b)).filter((b)=>b!==void 0).map((b)=>Nw(b,c))});let g=this.buildGroupEvent(c,u,o);if(g)l.push(g);let v=this.buildMoveEndEvent(i,n,c,u,s,a,o);if(v)l.push(v);return this.currentLayout=n,this.previousSpatial=a,l}buildGroupEvent(e,t,n){let o=Ao(Array.from(e.values()).filter((l)=>l.type==="group").map((l)=>l.id)),i=Ao(Array.from(t.values()).filter((l)=>l.type==="group").map((l)=>l.id)),s=i.filter((l)=>!o.includes(l)).map((l)=>{let c=t.get(l),u=Mf(c);return{id:l,title:Ss(c),childCount:u.length}}),a=[];for(let l of i.filter((c)=>o.includes(c))){let c=Mf(e.get(l)),u=Mf(t.get(l));if(Nf(c,u))continue;a.push({id:l,title:Ss(t.get(l)),addedChildIds:u.filter((d)=>!c.includes(d)),removedChildIds:c.filter((d)=>!u.includes(d)),childCount:u.length})}if(s.length===0&&a.length===0)return null;return{type:"group",...n,created:s,updated:a}}buildMoveEndEvent(e,t,n,o,i,s,a){let l=Ao(Array.from(o.keys()).filter((v)=>{let b=n.get(v),x=o.get(v);if(!b||!x)return!1;return b.position.x!==x.position.x||b.position.y!==x.position.y}));if(l.length===0)return null;let c=zw(i),u=zw(s),d=$w(i),p=$w(s),f=new Map,m=(v,b)=>{let x=f.get(v)??new Set;x.add(b),f.set(v,x)};for(let v of l){let b=c.get(v)??[],x=u.get(v)??[];if(!Nf(b,x))if(b.length===0&&x.length>0)m(v,"joined cluster");else if(b.length>0&&x.length===0)m(v,"left cluster");else m(v,"cluster changed")}let h=new Set([...d.keys(),...p.keys()]);for(let v of h){let b=d.get(v)??[],x=p.get(v)??[];if(Nf(b,x))continue;let C=Ss(o.get(v)??n.get(v))??v,y=x.filter((_)=>!b.includes(_)),k=b.filter((_)=>!x.includes(_));for(let _ of y)if(l.includes(_))m(_,`entered pinned neighborhood of "${C}"`);for(let _ of k)if(l.includes(_))m(_,`left pinned neighborhood of "${C}"`);if(l.includes(v))m(v,"pinned neighborhood changed")}let g=l.filter((v)=>(f.get(v)?.size??0)>0).map((v)=>{let b=o.get(v);return{...Jc(b,v),reasons:Array.from(f.get(v)??[]).sort((x,C)=>x.localeCompare(C))}});if(g.length===0)return null;return{type:"move-end",...a,nodes:g}}}var eu=ie(null),Ka=ie([]),tu=ie(new Set),qr=ie(!1),_s=ie(0);function Ow(){eu.value=null,Ka.value=[],tu.value=new Set,qr.value=!1,_s.value=0}function nu(){qr.value=!0,_s.value=0}function Dw(){qr.value=!1}function ou(e){eu.value=e}function zf(e,t=6){if(Ka.value=[e,...Ka.value].slice(0,t),!qr.value)_s.value=Math.min(99,_s.value+1)}function ru(e){tu.value=new Set(e)}var Bw=30000;var $f=80;var qt=ie(new Map),Ts=ie(null),SR=480,_R=320,CR=650,Va=new Map,Cs=new Map,iu=new Map,gr=null;function Lf(e){qt.value=e,TR()}function Of(e){let t=Va.get(e);if(t)clearTimeout(t),Va.delete(e)}function Df(e){let t=Cs.get(e);if(t)clearTimeout(t),Cs.delete(e)}function Hw(e){if(Of(e.id),Df(e.id),!qt.value.has(e.id))iu.set(e.id,Date.now());let t=new Map(qt.value);t.set(e.id,{...e,phase:"forming"}),Lf(t)}function zi(e){if(Of(e),Df(e),iu.delete(e),!qt.value.has(e))return;let t=new Map(qt.value);t.delete(e),Lf(t)}function Fw(e,t,n,o){let i=qt.value.get(e);if(!i||i.phase===t)return;let s=new Map(qt.value);s.set(e,{...i,phase:t,...o?{settledNodeId:o}:{}}),Lf(s),Of(e),Va.set(e,setTimeout(()=>zi(e),n+1500))}function Uw(e,t,n,o){Df(e);let i=Date.now()-(iu.get(e)??0),s=Math.max(0,CR-i);if(s===0){Fw(e,t,n,o);return}Cs.set(e,setTimeout(()=>{Cs.delete(e),Fw(e,t,n,o)},s))}function jw(e,t){Uw(e,"settling",SR,t)}function Bf(e){Uw(e,"dissolving",_R)}function su(){for(let e of Va.values())clearTimeout(e);Va.clear();for(let e of Cs.values())clearTimeout(e);if(Cs.clear(),iu.clear(),gr)clearInterval(gr),gr=null;Ts.value=null,qt.value=new Map}function TR(){if(gr||qt.value.size===0)return;gr=setInterval(()=>{let e=Date.now();for(let t of qt.value.values())if(t.phase==="forming"&&t.expiresAt<=e)Bf(t.id);if(qt.value.size===0&&gr)clearInterval(gr),gr=null},1000),gr.unref?.()}var Ff;function tt(){return Ff!==void 0}var Gt=(e,t)=>Ff?Ff(e,t):globalThis.fetch(e,t),Zw;async function Ww(e){if(!Zw)throw Error("This host does not support downloads. The export is saved in the local PMX workspace.");if(!/^\/api\/canvas\/exports\/[^/?#]+$/.test(e))throw Error("Invalid export path.");let t=await Gt(e);if(!t.ok)throw Error("Could not read the export. Try again.");if((await Zw({name:decodeURIComponent(e.slice(e.lastIndexOf("/")+1)),mimeType:"text/html",text:await t.text()})).isError)throw Error("The download was cancelled or declined by the host.")}function IR(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 Kr=IR("pmx-canvas-human-client",()=>`tab-${Math.random().toString(36).slice(2,8)}`);function ER(){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-${Kr.slice(-4)}`}var Gw=ie(ER()),Kw=ie([]),Ja=Ve(()=>Kw.value.filter((e)=>e.clientId!==Kr)),$i=ie(new Map);function Hf(e){if(!e||!Array.isArray(e.humans))return;Kw.value=e.humans}var Wo=ie(null),cu=null,Vw=0,Gr=null;function lu(e){if(tt())return;oo("humanPresence","/api/canvas/human-presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:Kr,name:Gw.value,...e})})}function qw(){Gr=null,Vw=Date.now(),lu({cursor:cu,grabbingNodeId:Wo.value})}function uu(e){cu=e;let t=Date.now()-Vw;if(t>=$f){if(Gr)clearTimeout(Gr);qw()}else if(!Gr)Gr=setTimeout(qw,$f-t)}function Uf(e){Wo.value=e,lu({cursor:cu,grabbingNodeId:e})}function AR(e,t){let n=new Map($i.value);n.set(e,t),$i.value=n,setTimeout(()=>{let o=new Map($i.value);if(o.get(e)===t)o.delete(e),$i.value=o},6000)}function Xw(e,t){let n=[...qt.value.values()].filter((i)=>i.nodeId===e&&!i.auto&&i.phase==="forming");if(n.length===0)return;let o=Gw.value;AR(e,o);for(let i of n)Li({id:i.id,kind:i.kind,label:i.label,reason:`${o} took over “${t}” mid-edit — yield and requeue the change once it is released`}).then((s)=>{if(s)zi(i.id)});oo("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 au=null,Xa=null;function Ya(){if(au)clearInterval(au);if(au=null,Gr)clearTimeout(Gr);if(Gr=null,Xa)window.removeEventListener("pagehide",Xa);Xa=null}function Jw(){Ya(),lu({cursor:cu,grabbingNodeId:Wo.value}),au=setInterval(()=>lu({grabbingNodeId:Wo.value}),3000),Xa=()=>{try{navigator.sendBeacon?.("/api/canvas/human-presence",new Blob([JSON.stringify({clientId:Kr,left:!0})],{type:"application/json"}))}catch{}},window.addEventListener("pagehide",Xa)}var Mt=(e)=>JSON.stringify([e.boardId,e.cardId??null]);var Xn=ie(null),Oi=ie(!1),jf=Ve(()=>Oe.value?Ro.value:"All"),Is=ie(null),Yw=0;async function Kt(){let e=++Yw,t=wt,n=await de("knowledge","/api/canvas/knowledge",null);if(e!==Yw||t!==wt)return;if(Oi.value=n?.ok!==!0,n?.ok===!0)Xn.value=n}function Jn(e){return se.value?Xn.value?.cards[Mt({boardId:se.value,cardId:e})]:void 0}var Di=Ve(()=>new Set([...kt.value].filter((e)=>!Jn(e)?.retired)));function Es(e){if(Oe.value&&se.value)Ct.value={boardId:se.value,nodeId:e,incarnation:wt}}var Qw="",ek=new Map,ro=Ve(()=>{let e=Di.value,t=new Map;if(e.size>0){let o=new Map,i=[...H.value.values()].filter((s)=>!Jn(s.id)?.retired);for(let s of Pf(i,e)){let a=s.pinnedNodeTitle??s.pinnedNodeId;for(let l of s.neighbors){let c=o.get(l.id)??[];c.push({pinNodeId:s.pinnedNodeId,pinTitle:a,distance:l.distance}),o.set(l.id,c)}}for(let[s,a]of o)a.sort((l,c)=>l.distance-c.distance),t.set(s,a.map(({pinNodeId:l,pinTitle:c})=>({pinNodeId:l,pinTitle:c})))}let n=[...t].sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i.map((s)=>`${s.pinNodeId}=${s.pinTitle}`).join(",")}`).join("|");if(n===Qw)return ek;return Qw=n,ek=t,t}),tk=Ve(()=>{let e=new Map;for(let[t,n]of ro.value)for(let o of n){let i=e.get(o.pinNodeId)??[];i.push(t),e.set(o.pinNodeId,i)}return e}),Qa=ie(null),du=ie(null),nk=Ve(()=>{let e=kt.value;if(e.size===0)return{pinIds:[],ringOnly:!1};let t=Wo.value;if(t&&!e.has(t)){let s=H.value.get(t),a=null,l=Number.POSITIVE_INFINITY;for(let c of e){let u=H.value.get(c);if(!s||!u)continue;let d=hr(s,u);if(d<l)l=d,a=c}return{pinIds:a?[a]:[],ringOnly:!0}}let n=new Set;if(t)n.add(t);let o=Qa.value;if(o&&e.has(o))n.add(o);for(let s of st.value)if(e.has(s))n.add(s);let i=du.value;for(let s of i&&ro.value.get(i)||[])n.add(s.pinNodeId);return{pinIds:[...n],ringOnly:!1}}),Bi=ie(null),Zf;function ok(e){Wf(e),Zf=ro.value.get(e)}function rk(e){let t=Zf;Zf=void 0;let n=ro.value.get(e);if(n&&!t)Bi.value={nodeId:e,kind:"in",pins:n};else if(t&&!n)Bi.value={nodeId:e,kind:"out",pins:t}}function Wf(e){if(Bi.value?.nodeId===e)Bi.value=null}var Vr=ie(null),qo=null;function ik(e,t,n){if(qo)clearTimeout(qo);qo=null;let o=t.getBoundingClientRect();Vr.value={nodeId:e,at:{left:o.left,right:o.right,top:o.top,bottom:o.bottom},view:n}}function As(){if(qo)clearTimeout(qo);qo=setTimeout(()=>{qo=null,Vr.value=null},160)}function qf(){if(qo)clearTimeout(qo);qo=null}var ak=new Qc,Rs=[],el=null,Ps=null,Gf="",Kf=0;function lk(e,t){return globalThis.setTimeout(e,t)}function Vf(e){if(e===null)return;globalThis.clearTimeout(e)}function RR(e){if(typeof globalThis.requestAnimationFrame==="function"){globalThis.requestAnimationFrame(()=>e());return}e()}function Ko(e,t){return e&&e.trim().length>0?e.trim():t}function Go(e,t=3){if(e.length===0)return"";if(e.length<=t)return e.join(", ");return`${e.slice(0,t).join(", ")} +${e.length-t}`}function PR(e){return Array.from(new Set(Array.from(e).filter((t)=>t.length>0)))}function vo(e,t,n,o,i=Date.now()){return{id:`${e}-${i}-${Math.random().toString(36).slice(2,8)}`,tone:e,title:t,detail:n,nodeIds:PR(o),createdAt:i}}function NR(e){if(e==="joined cluster")return"joined a nearby cluster";if(e==="left cluster")return"moved away from its cluster";if(e==="cluster changed")return"shifted into a different cluster";if(e==="pinned neighborhood changed")return"changed the local focus field";return e}function sk(e,t){let n=new RegExp(`^${t} pinned neighborhood of "(.+)"$`);return e.flatMap((o)=>n.exec(o)?.[1]??[])}function MR(e,t,n){let o=(l)=>l.map((c)=>`“${c}”`).join(" and "),i=sk(n,"entered");if(i.length>0)return{title:"Near a pin",body:`“${e}” is now near ${o(i)} — the agent gets its title and summary.`};let s=sk(n,"left");if(s.length===0)return null;let a=ro.value.get(t)??[];return{title:"Left a pin",body:a.length>0?`“${e}” left ${o(s)} — still near ${o(a.map((l)=>l.pinTitle))}.`:`“${e}” left ${o(s)} — it is out of the agent’s brief.`}}function zR(e){let t=e.added.map((i)=>Ko(i.title,i.id)),n=e.removed.map((i)=>Ko(i.title,i.id));if(t.length===0&&n.length===0)return null;let o="";if(t.length>0&&n.length===0)o=`Now in focus: ${Go(t)}`;else if(n.length>0&&t.length===0)o=`Removed from focus: ${Go(n)}`;else{let i=[];if(t.length>0)i.push(`${Go(t)} added`);if(n.length>0)i.push(`${Go(n)} removed`);o=i.join(" · ")}return vo("context","Context updated",o,[...e.added.map((i)=>i.id),...e.removed.map((i)=>i.id)],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function $R(e){if(e.edges.length===0)return null;if(e.edges.length===1){let t=e.edges[0];return vo("relationship","Relationship added",`${Ko(t.fromTitle,t.fromId)} linked to ${Ko(t.toTitle,t.toId)}`,[t.fromId,...!t.toBoardId||t.toBoardId===se.value?[t.toId]:[]],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return vo("relationship","Relationships added",`${e.edges.length} connections changed the board structure`,e.edges.flatMap((t)=>[t.fromId,...!t.toBoardId||t.toBoardId===se.value?[t.toId]:[]]),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function LR(e){if(e.nodes.length===0&&e.edges.length===0)return null;if(e.nodes.length===0){let o=e.edges.map((i)=>`“${Ko(i.fromTitle,i.fromId)}” – “${Ko(i.toTitle,i.toId)}” (${i.edgeType})`);return vo("remove",o.length===1?"Link removed":"Links removed",Go(o),e.edges.flatMap((i)=>[i.fromId,...!i.toBoardId||i.toBoardId===se.value?[i.toId]:[]]),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}let t=e.nodes.map((o)=>Ko(o.title,o.id)),n=[];if(t.length>0)n.push(Go(t));if(e.edges.length>0)n.push(`${e.edges.length} relationship${e.edges.length===1?"":"s"}`);return vo("remove","Items removed",n.join(" · "),[...e.nodes.map((o)=>o.id),...e.edges.flatMap((o)=>[o.fromId,...!o.toBoardId||o.toBoardId===se.value?[o.toId]:[]])],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function OR(e){if(e.created.length>0){let t=e.created.map((n)=>Ko(n.title,n.id));return vo("group",e.created.length===1?"Group created":"Groups created",e.created.length===1?`${t[0]} now frames ${e.created[0].childCount} items`:Go(t),e.created.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}if(e.updated.length>0){let t=e.updated.map((n)=>Ko(n.title,n.id));return vo("group",e.updated.length===1?"Group updated":"Groups updated",e.updated.length===1?`${t[0]} now holds ${e.updated[0].childCount} items`:Go(t),e.updated.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return null}function DR(e){if(e.nodes.length===0)return null;let t=e.nodes.flatMap((s)=>s.reasons),n=e.nodes.map((s)=>Ko(s.title,s.id)),o=e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now();if(t.some((s)=>s.includes("pinned neighborhood"))){let s=e.nodes.length===1?MR(n[0],e.nodes[0].id,e.nodes[0].reasons):null;if(s)return vo("neighborhood",s.title,s.body,[e.nodes[0].id],o);return vo("neighborhood","Neighborhood changed",Go(n),e.nodes.map((a)=>a.id),o)}let i=t.filter((s)=>s.includes("cluster"));if(i.length>0){let s=i.every((a)=>a==="joined cluster");if(e.nodes.length===1)return vo("cluster",s?"Cluster formed":"Cluster changed",`${n[0]} ${NR(e.nodes[0].reasons[0])}`,e.nodes.map((a)=>a.id),o);return vo("cluster",s?"Cluster formed":"Cluster changed",Go(n),e.nodes.map((a)=>a.id),o)}return null}function BR(e){switch(e.type){case"context-pin":return zR(e);case"connect":return $R(e);case"remove":return LR(e);case"group":return OR(e);case"move-end":return DR(e)}}function ck(){if(el!==null)return;let e=Rs.shift()??null;if(!e){ou(null);return}ou(e);let t=Math.max(1800,Math.min(2800,1600+e.detail.length*18));el=lk(()=>{el=null,ou(null),ck()},t)}function uk(e){if(Rs.push(e),Rs.length>3)Rs.splice(0,Rs.length-3);ck()}function hn(e,t,n="",o=[]){let i=vo(e,t,n,o);zf(i),uk(i)}function FR(e){if(Vf(Ps),Ps=null,ru([]),e.length===0)return;RR(()=>{ru(e),Ps=lk(()=>{Ps=null,ru([])},900)})}function HR(e){let t=`${e.tone}:${e.title}:${e.detail}`,n=e.createdAt;if(t===Gf&&n-Kf<1200)return!0;return Gf=t,Kf=n,!1}function pu(){Vf(el),Vf(Ps),el=null,Ps=null,Rs=[],Gf="",Kf=0,ak=new Qc,Ow()}function tl(e){let t=ak.handleMessage(e).map((n)=>BR(n)).filter((n)=>n!==null);for(let n of t){if(HR(n))continue;zf(n),uk(n),FR(n.nodeIds)}}function Xf(e,t){console.error(`[intent-bridge] ${e} failed`,t)}var fu=(()=>{try{let e=new URLSearchParams(window.location.search).get("agent")?.trim();return e?e.slice(0,64):null}catch{return null}})();function Jf(e){if(tt())return e??{};let t={...e?.headers};if(fu)t["x-pmx-source"]=fu;else{t["X-PMX-Workbench"]="1";let n=window.__PMX_WORKBENCH_TOKEN;if(typeof n==="string")t["X-PMX-Workbench-Token"]=n}return{...e,headers:t}}function Yf(e,t,n){if(e.ok||(t?.method??"GET").toUpperCase()==="GET")return;let o=n!==null&&typeof n==="object"&&"error"in n&&typeof n.error==="string"?n.error:"";hn("remove","Change refused",o||`The server answered ${e.status}.`)}async function Qf(e){try{return await e.json()}catch{return null}}async function de(e,t,n,o){try{let i=await Gt(t,Jf(o)),s=await Qf(i);if(Yf(i,o,s),s===null)throw Error(`${i.status} response had no JSON body`);return s}catch(i){return Xf(e,i),n}}async function so(e,t,n){try{let o=await Gt(t,Jf(n));if(!o.ok)Yf(o,n,await Qf(o));return{ok:o.ok}}catch(o){return Xf(e,o),{ok:!1}}}async function oo(e,t,n){try{let o=await Gt(t,Jf(n));if(!o.ok)Yf(o,n,await Qf(o))}catch(o){Xf(e,o)}}async function dk(e,t={}){return de("sendIntent","/api/workbench/intent",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:e,payload:t})})}async function Li(e){let n=`Veto: do not ${e.label?.trim()||`${e.kind} intent`}${e.reason?` — ${e.reason}`:""}.`;if((await de("vetoGhostIntent",`/api/canvas/ax/intent/${encodeURIComponent(e.id)}`,{ok:!1,cleared:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({vetoed:!0})})).cleared!==!0)return!1;return await oo("vetoGhostSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:n,source:"browser"})}),!0}async function Vo(e,t,n=se.value){return(await de("renderMarkdown","/api/render",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({markdown:e,...t?{nodeId:t,expectedBoardId:n}:{}})})).html??null}async function nl(e){return de("fetchFile",`/api/file?path=${encodeURIComponent(e)}`,{content:""})}async function mu(e){return so("openWorkbenchFile","/api/workbench/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})})}async function pk(e){return de("fetchCanvasState",`/api/canvas/state?includeBlobs=true&expectedBoardId=${encodeURIComponent(e??"null")}`,{})}async function hu(e){return de("saveCanvasTheme","/api/canvas/theme",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:e})})}async function fk(){return[]}async function ol(e,t,n,o,i){if(!e.trim())return{ok:!1,error:"Prompt text is required"};return de("submitCanvasPrompt","/api/canvas/prompt",{ok:!1,error:"Network error"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e,...t?{position:t}:{},...n?{parentNodeId:n}:{},...o&&o.length>0?{contextNodeIds:o}:{},...i?{threadNodeId:i}:{}})})}async function mk(e,t){return ol(t,void 0,void 0,void 0,e)}async function gu(e,t={}){await oo("pushCanvasUpdate","/api/canvas/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e,...io.value?{expectedBoardId:se.value}:{},...t.recordHistory===!1?{recordHistory:!1}:{}})})}async function yr(e,t,n,o,i={}){let s=Po.value,a=await de("createEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:t,type:n,label:o,...i})});if(s===Po.value&&H.value.has(e)&&(i.toBoardId||H.value.has(t))){if(a.ok){let{ok:l,...c}=a;zs(c)}else if(!a.error)hn("remove","Connection not added","Could not reach the server. Try again.")}return a}async function No(e){return de("createNodeFromClient","/api/canvas/node",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function ln(e,t){return de("updateNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function yu(e,t){return de("refreshWebpageNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}/refresh`,{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{url:t}:{})})}async function Xr(e){return de("removeNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"DELETE"})}async function hk(){return de("fetchAxSurfaceState","/api/canvas/ax/surface-snapshot",null)}async function gk(){return de("fetchAgentPresence","/api/canvas/ax/presence",null)}async function yk(e,t){return de("openNodeInSystemBrowserRequest","/api/canvas/open-external",{ok:!1,opened:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeId:e,url:t})})}async function vu(e){return de("submitAxInteractionFromClient","/api/canvas/ax/interaction",{ok:!1,code:"request-failed",error:"Request failed"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceSurface:"native-node",...e,source:"browser"})})}async function vk(e,t={}){return de("updateViewportFromClient","/api/canvas/viewport",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...bk(),clientId:Kr,...io.value?{expectedBoardId:se.value}:{},...t.recordHistory===!1?{recordHistory:!1}:{}})})}function bk(){if(typeof window>"u")return{};let e=Jt(),t=Math.round(e.width),n=Math.round(e.height);if(!t||!n)return{};let{top:o,bottom:i}=Wa();return{clientWidth:t,clientHeight:n,clientInsets:{top:o,bottom:i}}}async function Jr(){if(tt()&&!io.value)return;let e=bk();if(!("clientWidth"in e))return;await oo("reportClientViewportSize","/api/canvas/viewport",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...io.value?{expectedBoardId:se.value}:{},recordHistory:!1})})}async function Ns(e){return de("createGroupFromClient","/api/canvas/group",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function em(e,t,n){return de("addToGroupFromClient","/api/canvas/group/add",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e,childIds:t,...n?{childLayout:n}:{}})})}async function bu(e,t){return ln(e,{children:t})}async function Ms(e){return de("ungroupFromClient","/api/canvas/group/ungroup",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e})})}async function xk(){return de("listSnapshots","/api/canvas/snapshots?all=true",[])}async function wk(e){return de("saveSnapshot","/api/canvas/snapshots",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})})}async function kk(e){return de("restoreSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"POST"})}async function Sk(e){return de("deleteSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"DELETE"})}async function Fi(e,t){return de("updateEdgeFromClient",`/api/canvas/edge/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function xu(e){return de("removeEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({edge_id:e})})}var Ge=ie([]),se=ie(null),ut=ie(!1),Ct=ie(null),Ro=ie("All");sn(()=>{se.value,Ro.value="All"});var bo=ie(0),io=ie(!1),tm=null,Sn=null,Mo=null,wt=0,nm=0,wu=null,rl=0,_k=Promise.resolve(),Yr=0,tn=0;sn(()=>{Oe.value,tn++});function Ck(e){if(e===Sn)return;Sn=e,Mo=null,wt++,nm=0,wu=null,rl++,Yr++,Ct.value=null}function Tk(e){tm=e}function Qr(e){if(!e||!Array.isArray(e.boards)||e.catalogEpoch!==Sn||typeof e.catalogRevision!=="number"||typeof e.reloadRevision!=="number"||e.catalogRevision<=nm)return;nm=e.catalogRevision;let t=typeof e.activeBoardId==="string"?e.activeBoardId:null,n=!io.value,o=Mo===null&&typeof e.boardGeneration==="number",i=!n&&(t!==se.value||wu!==null&&e.reloadRevision!==wu||Mo!==null&&typeof e.boardGeneration==="number"&&e.boardGeneration!==Mo);if(i)wt++,Ct.value=null;if(typeof e.boardGeneration==="number")Mo=e.boardGeneration;wu=e.reloadRevision,Nn(()=>{if(Ge.value=e.boards,se.value=t,io.value=!0,i||n)tm?.(n);else if(o)tm?.(!0)})}async function il(){let e=await de("loadBoards","/api/canvas/boards",null);Qr(e)}async function sl(e,t,n,o){return de(e,t,null,{method:n,headers:{"Content-Type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}})}function Ik(){let e=++Yr;return()=>e===Yr}async function Mn(e){let t=++rl;Yr++,Ct.value=null;let n=Sn,o=null,i=_k.then(async()=>{if(n===Sn)o=await sl("openBoard","/api/canvas/boards/open","POST",{id:e})});if(_k=i.catch(()=>{return}),await i,t===rl&&n===Sn&&o)Nn(()=>{if(Qr(o),e!==null)ut.value=!1})}async function zt(e,t={}){if(t.review&&!Oe.value)return!1;let n=tn,o=Mn(e.boardId),i=Yr;await o;let s=wt;if(!e.cardId)return i===Yr&&se.value===e.boardId;for(let a=0;a<400;a++){if(i!==Yr||se.value!==e.boardId||wt!==s||ut.value||t.review&&(!Oe.value||n!==tn))return!1;if(cn.value&&H.value.has(e.cardId)){let l=al.value.get(e.cardId);if(l)Hi(l);if($t(e.cardId),t.review)Ct.value={boardId:e.boardId,nodeId:e.cardId,incarnation:s};return!0}await new Promise((l)=>window.setTimeout(l,25))}return!1}async function Ek(e,t){let n=++rl;Yr++,Ct.value=null;let o=Sn,i=await de("createBoard","/api/canvas/boards",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,...t?{folder:t}:{}})});if(i?.board&&n===rl&&o===Sn)await Mn(i.board.id)}async function Ak(e){return de("previewBoardCopy","/api/canvas/boards/from",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceBoardId:e,name:"Preview",preview:!0})})}async function Rk(e){let t=await de("createBoardFrom","/api/canvas/boards/from",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await il(),t?.board??null}async function vr(e,t){let n=await sl("updateBoard",`/api/canvas/boards/${encodeURIComponent(e)}`,"PATCH",{...t,...t.folder===null?{folder:""}:{}});return Qr(n),n!==null}async function $s(e,t){let n=`/api/canvas/boards/${encodeURIComponent(e)}/${t?"pin":"unpin"}`;Qr(await sl(t?"pinBoard":"unpinBoard",n,"POST",{}))}async function Pk(e,t){let n=await sl("setBoardReadme",`/api/canvas/boards/${encodeURIComponent(e)}`,"PATCH",{readmeNodeId:t});Qr(n)}async function Nk(e){let t=await sl("deleteBoard",`/api/canvas/boards/${encodeURIComponent(e)}`,"DELETE");Qr(t)}function Yn(){return Ge.value.find((e)=>e.id===se.value)??null}function Ok(e,t){console.error(`[canvas-store] ${e} failed`,t)}var Te=ie({x:0,y:0,scale:1}),H=ie(new Map),et=ie(new Map),Ls=ie(new Map),gt=ie(null),br=ie(null),ao=ie("connecting"),Zi=ie(0),Wi=ie(0),qi=ie(0),xr=ie(""),Os=ie(!1),Qt=ie("harbor"),cn=ie(!1),Oo=ie(null),Bt=ie(null),$o=ie(null),zn=null,Ui,Mk=100,UR=2500,cl=ie(null),Po=ie(0),At=ie(null),wr=ie(null),st=ie(new Set),kt=ie(new Set),Wn=ie("select"),ul=ie(!1);function Ds(){return Wn.value==="pan"||ul.value}function Dk(e,t){if(!e)return new Set;let n=new Set;for(let o of t.values()){if(o.toBoardId!==void 0)continue;if(o.from===e)n.add(o.to);if(o.to===e)n.add(o.from)}return n}var Bk=Ve(()=>Dk(gt.value,et.value));function zk(e,t){let n=new Set;for(let o of e)if(t.has(o))n.add(o);return n}function $k(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function im(e){let t=new Set(st.value);if(t.has(e))t.delete(e);else t.add(e);st.value=t}function Fk(e){st.value=new Set(e)}function $n(){if(br.value=null,st.value.size===0)return;st.value=new Set}function Hk(){if(co(),zn!==null)clearTimeout(zn),zn=null;Nn(()=>{Po.value+=1,Lo++,ji=0,gt.value=null,Bt.value=null,$o.value=null,Ui=void 0,st.value=new Set,br.value=null,cl.value=null,At.value=null,wr.value=null,Xo.value=null,kt.value=new Set}),ku=!1}var Xo=ie(null),ku=!1;function Uk(){ku=!0,Xo.value=null}function jk(){ku=!1,Xo.value=null}function om(e){return{x:e.position.x,y:e.position.y,w:e.size.width,h:e.size.height}}function jR(e,t,n){let o=om(e);return t>=o.x&&t<=o.x+o.w&&n>=o.y&&n<=o.y+o.h}function Lk(e,t){let n=om(e),o=om(t);return n.x+n.w<o.x||n.x>o.x+o.w||n.y+n.h<o.y||n.y>o.y+o.h}function Zk(e){let t=H.value.get(e);if(!t||t.type==="group")return;let n=typeof t.data.parentGroup==="string"?t.data.parentGroup:null,o=n?H.value.get(n):void 0,i=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=null;for(let l of H.value.values()){if(l.type!=="group"||l.id===n||l.collapsed)continue;if(jR(l,i,s))a=l}if(!ku){let l=a?{nodeId:e,groupId:a.id,mode:"add"}:o&&Lk(t,o)?{nodeId:e,groupId:o.id,mode:"remove"}:null,c=Xo.value;if((c?.groupId??null)!==(l?.groupId??null)||c?.mode!==l?.mode)Xo.value=l}if(o&&o.data.frameMode!=="manual"&&!Lk(t,o)){let c=Math.min(o.position.x,t.position.x-22),u=Math.min(o.position.y,t.position.y-22-32),d=Math.max(o.position.x+o.size.width,t.position.x+t.size.width+22),p=Math.max(o.position.y+o.size.height,t.position.y+t.size.height+22);if(c!==o.position.x||u!==o.position.y||d!==o.position.x+o.size.width||p!==o.position.y+o.size.height)_u(o.id,{position:{x:c,y:u},size:{width:d-c,height:p-u}},{skipGroupChildTranslation:!0})}}var al=Ve(()=>{let e=new Map;for(let t of H.value.values()){if(t.type!=="group"||!t.collapsed)continue;let n=Array.isArray(t.data.children)?t.data.children:[];for(let o of n)if(typeof o==="string")e.set(o,t.id)}return e});function Bs(e){let t=al.value.get(e);return H.value.get(t??e)}function Wk(){let e=new Set;for(let t of st.value){let n=H.value.get(t);if(!n)continue;if(n.type==="group")e.add(n.id);else if(typeof n.data.parentGroup==="string")e.add(n.data.parentGroup)}return[...e]}function sm(e){let t=am();if(t.length<2)return;let n=Math.min(...t.map((c)=>e==="left"?c.position.x:c.position.y)),o=24,i=new Map;for(let c of t)i.set(c.id,e==="left"?{x:n,y:c.position.y}:{x:c.position.x,y:n});let s=(c,u)=>c.x<u.x+u.w&&u.x<c.x+c.w&&c.y<u.y+u.h&&u.y<c.y+c.h,a=t.map((c)=>{let u=i.get(c.id);return{node:c,x:u.x,y:u.y,w:c.size.width,h:c.size.height}});if(a.some((c,u)=>a.some((d,p)=>p>u&&s(c,d)))){let c=[...t].sort((d,p)=>e==="left"?d.position.y-p.position.y:d.position.x-p.position.x),u=e==="left"?Math.min(...t.map((d)=>d.position.y)):Math.min(...t.map((d)=>d.position.x));for(let d of c)i.set(d.id,e==="left"?{x:n,y:u}:{x:u,y:n}),u+=(e==="left"?d.size.height:d.size.width)+o}Nn(()=>{for(let c of t)un(c.id,{position:i.get(c.id)})}),dn()}function qk(){let e=am().sort((l,c)=>l.position.x-c.position.x);if(e.length<3)return;let t=e[0],o=e[e.length-1].position.x-(t.position.x+t.size.width),i=e.slice(1,-1),s=i.reduce((l,c)=>l+c.size.width,0),a=(o-s)/(i.length+1);Nn(()=>{if(a<8){let c=t.position.x+t.size.width+24;for(let u of e.slice(1))un(u.id,{position:{x:c,y:u.position.y}}),c+=u.size.width+24;return}let l=t.position.x+t.size.width+a;for(let c of i)un(c.id,{position:{x:l,y:c.position.y}}),l+=c.size.width+a}),dn()}function Gk(e=24){let t=am().sort((l,c)=>l.position.y-c.position.y||l.position.x-c.position.x);if(t.length<2)return;let n=Math.min(...t.map((l)=>l.position.x)),o=Math.min(...t.map((l)=>l.position.y)),i=Math.ceil(Math.sqrt(t.length)),s=Math.max(...t.map((l)=>l.size.width)),a=Math.max(...t.map((l)=>l.size.height));Nn(()=>{t.forEach((l,c)=>{un(l.id,{position:{x:n+c%i*(s+e),y:o+Math.floor(c/i)*(a+e)}})})}),dn()}function am(){let e=st.value;if(e.size===0)return[];return Array.from(e).map((t)=>H.value.get(t)).filter((t)=>t!==void 0)}var Lo=0,ji=0;function lo(e){let t=new Set(kt.value);if(t.has(e))t.delete(e);else t.add(e);kt.value=t,dn(),dl(t)}function Su(e){let t=new Set(kt.value);for(let n of e)t.add(n);kt.value=t,dn(),dl(t)}function Kk(e){let t=new Set(kt.value);for(let n of e)t.delete(n);kt.value=t,dn(),dl(new Set(e),"remove")}function lm(){if(kt.value.size===0)return;kt.value=new Set,dn(),dl(new Set)}function cm(e){Lo++,kt.value=new Set(e)}async function um(){if(ji>0)return;let e=Lo,t=Po.value,o=(await de("refreshContextPins","/api/workbench/poll",{})).events?.find((i)=>i.event==="context-pins-changed")?.payload;if(e===Lo&&t===Po.value&&o?.boardId===se.value&&Array.isArray(o.nodeIds))cm(o.nodeIds),tl({event:"context-pins-changed",data:o})}function dl(e,t="set"){Lo++,ji++;let n=Po.value;oo("syncContextPinsToServer","/api/canvas/context-pins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeIds:Array.from(e),mode:t,...io.value?{expectedBoardId:se.value}:{}})}).then(()=>{if(n!==Po.value)return;ji--,Lo++,um()})}var ll=1;function kr(e){Nn(()=>{let t=new Map(H.value);if(e.zIndex>=ll)ll=e.zIndex+1;t.set(e.id,e),H.value=t,gt.value=e.id})}function un(e,t){_u(e,t)}function _u(e,t,n={}){let o=H.value.get(e);if(!o)return;let i=new Map(H.value);if(o.type==="group"&&t.position&&n.skipGroupChildTranslation!==!0){let a=t.position.x-o.position.x,l=t.position.y-o.position.y;if(a!==0||l!==0){let c=Array.isArray(o.data.children)?o.data.children.filter((u)=>typeof u==="string"):[];for(let u of c){let d=i.get(u);if(!d||d.type==="group")continue;i.set(u,{...d,position:{x:d.position.x+a,y:d.position.y+l}})}}}i.set(e,{...o,...t}),H.value=i;let s=i.get(e)?.data.appCheckpoint?.updatedAt;if($o.value===e&&s!==void 0&&s!==Ui)rm(e)}function Xe(e,t){let n=H.value.get(e);if(!n)return;un(e,{data:{...n.data,...t}})}function ei(e){ZR(e);let t=new Map(H.value);if(t.delete(e),H.value=t,gt.value===e)gt.value=null;if(Bt.value===e)Bt.value=null;if(st.value.has(e)){let n=new Set(st.value);n.delete(e),st.value=n}if(kt.value.has(e)){let n=new Set(kt.value);n.delete(e),kt.value=n,dl(n)}}function zs(e){let t=new Map(et.value);t.set(e.id,e),et.value=t}function Vk(e){let t=new Map(et.value);t.delete(e),et.value=t}function ZR(e){let t=!1,n=new Map(et.value);for(let[o,i]of n)if(i.from===e||i.toBoardId===void 0&&i.to===e)n.delete(o),t=!0;if(t)et.value=n}function WR(e){let t=new Map(Ls.value);if(!t.delete(e))return;Ls.value=t}async function dm(e){return so("createAnnotationFromClient","/api/canvas/annotation",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Xk(e){let t=await so("removeAnnotationFromClient",`/api/canvas/annotation/${encodeURIComponent(e)}`,{method:"DELETE"});if(t.ok)WR(e);return t}function Cu(e,t){if(!H.value.get(e))return;un(e,{size:t})}function Sr(e){let t=H.value.get(e);if(!t)return;Nn(()=>{if(un(e,{zIndex:ll++}),t.type==="group"&&Array.isArray(t.data.children)){for(let n of t.data.children)if(typeof n==="string"&&H.value.has(n))un(n,{zIndex:ll++})}}),gt.value=e}function Hi(e){let t=H.value.get(e);if(!t)return;un(e,{collapsed:!t.collapsed}),dn()}function Jk(e){Te.value={...Te.value,...e}}function pm(e){Te.value=e}function pl(e,t={}){Te.value=e,dn(t),vk(e,t)}function fm(e,t={}){let n=new Map,o=1;for(let p of e.nodes){let f=H.value.get(p.id);if(n.set(p.id,t.applyViewport!==!0&&f&&(f.contentRevision??0)>(p.contentRevision??0)?{...p,data:f.data,contentRevision:f.contentRevision,lastEditedBy:f.lastEditedBy}:p),p.zIndex>=o)o=p.zIndex+1}let i=e.edges.filter((p)=>n.has(p.from)&&(p.toBoardId!==void 0||n.has(p.to))),s=new Map;for(let p of i)s.set(p.id,p);let a=new Map;for(let p of e.annotations??[])a.set(p.id,p);let l=gt.value!==null&&n.has(gt.value)?gt.value:null,c=Bt.value!==null&&n.has(Bt.value)?Bt.value:null,u=zk(st.value,n),d=zk(kt.value,n);Nn(()=>{if(t.applyViewport===!0&&e.viewport)Te.value=e.viewport;if(ll=o,H.value=n,et.value=s,Ls.value=a,gt.value=l,Bt.value=c,!$k(st.value,u))st.value=u;if(!$k(kt.value,d))kt.value=d})}var zo=null;function qR(e){return 1-(1-e)**3}function ti(e,t=150){let n=Te.value,o=Math.min(4,Math.max(0.1,n.scale*e));if(o===n.scale)return;let i=o/n.scale,{x:s,y:a}=Zr();_r({x:s-i*(s-n.x),y:a-i*(a-n.y),scale:o},t)}function _r(e,t=300,n={}){if(zo!==null)cancelAnimationFrame(zo);let o={...Te.value},i=performance.now();function s(a){let l=a-i,c=Math.min(1,l/t),u=qR(c);if(Te.value={x:o.x+(e.x-o.x)*u,y:o.y+(e.y-o.y)*u,scale:o.scale+(e.scale-o.scale)*u},c<1)zo=requestAnimationFrame(s);else zo=null,pl(e,n)}zo=requestAnimationFrame(s)}function Yk(e,t,n){co();let o=performance.now(),i=(s)=>{let a=t<=0?1:Math.min(1,(s-o)/t);if(Te.value=e(a),a<1)zo=requestAnimationFrame(i);else zo=null,n?.(Te.value)};if(t<=0)i(o);else zo=requestAnimationFrame(i)}function co(){if(zo!==null)cancelAnimationFrame(zo),zo=null}var Qk="pmx-canvas-layout";function dn(e={}){try{let t=Array.from(H.value.values()),n=t.map((i)=>({id:i.id,position:i.position,size:i.size,collapsed:i.collapsed})),o={viewport:Te.value,nodes:t.map((i)=>({id:i.id,type:i.type,position:i.position,size:i.size,collapsed:i.collapsed,pinned:i.pinned})),edges:Array.from(et.value.values()).map((i)=>({id:i.id,from:i.from,to:i.to,...i.toBoardId!==void 0?{toBoardId:i.toBoardId}:{},type:i.type,label:i.label,style:i.style,animated:i.animated})),contextPinnedNodeIds:Array.from(kt.value)};if(!tt())localStorage.setItem(Qk,JSON.stringify(o));gu(n,e)}catch(t){Ok("persistLayout",t)}}function mm(){try{let e=localStorage.getItem(Qk);if(!e)return null;let t=JSON.parse(e),n=Array.isArray(t.nodes)?t.nodes:[];if(n.length===0)return null;let o=new Map;for(let i of n){if(typeof i.id!=="string"||i.id.length===0)continue;o.set(i.id,{...i.position?{position:i.position}:{},...i.size?{size:i.size}:{},...i.collapsed!==void 0?{collapsed:i.collapsed}:{},...i.pinned!==void 0?{pinned:i.pinned}:{}})}return o.size>0?o:null}catch(e){return Ok("restoreLayout",e),null}}function Fs(e,t){let n=Array.from(H.value.values());if(n.length===0)return;let{POSITIVE_INFINITY:o,POSITIVE_INFINITY:i,NEGATIVE_INFINITY:s,NEGATIVE_INFINITY:a}=Number;for(let g of n)o=Math.min(o,g.position.x),i=Math.min(i,g.position.y),s=Math.max(s,g.position.x+g.size.width),a=Math.max(a,g.position.y+g.size.height);let l=Wa(),c=Math.max(80,e-l.left-l.right),u=Math.max(80,t-l.top-l.bottom),d=Math.max(1,s-o),p=Math.max(1,a-i),f=Math.min(1,Math.min(c/d,u/p)),m=(o+s)/2,h=(i+a)/2;_r({x:l.left+c/2-m*f,y:l.top+u/2-h*f,scale:f})}function $t(e,t={}){let n=H.value.get(e);if(!n)return;let o=Te.value,i=Jt(),s=Wa(),a=Math.max(80,i.width-s.left-s.right),l=Math.max(80,i.height-s.top-s.bottom),c=Math.min(o.scale,a/n.size.width,l/n.size.height),u=n.position.x+n.size.width/2,d=n.position.y+n.size.height/2;_r({x:s.left+a/2-u*c,y:s.top+l/2-d*c,scale:c},300,t),Sr(e)}function eS(e=1){let t=Array.from(H.value.keys());if(t.length===0)return;let o=((gt.value?t.indexOf(gt.value):-1)+e+t.length)%t.length,i=t[o];Sr(i),$t(i)}function tS(e){let t=gt.value;if(!t)return;let n=H.value.get(t);if(!n)return;let o=Dk(t,et.value);if(o.size===0)return;let i=n.position.x+n.size.width/2,s=n.position.y+n.size.height/2,a=null,l=-1/0;for(let c of o){let u=H.value.get(c);if(!u)continue;let d=u.position.x+u.size.width/2,p=u.position.y+u.size.height/2,f=d-i,m=p-s,h=Math.sqrt(f*f+m*m);if(h<1)continue;let g;switch(e){case"up":g=-m;break;case"down":g=m;break;case"left":g=-f;break;case"right":g=f;break}if(g<=0)continue;let v=g/h-h*0.001;if(v>l)l=v,a=c}if(a)$t(a)}function xo(e){if(!H.value.get(e))return;if(zn!==null)clearTimeout(zn),zn=null;$o.value=null,Ui=void 0,Sr(e),Bt.value=e}function rm(e){if(zn!==null)clearTimeout(zn),zn=null;if(Bt.value===e)Bt.value=null;if($o.value===e)$o.value=null;Ui=void 0}function Cr(){let e=Bt.value,t=e?H.value.get(e):void 0;if(e&&t&&Aw(t)){let n=e,o=Date.now();if($o.value=n,Ui=t.data.appCheckpoint?.updatedAt,zn!==null)clearTimeout(zn);let i=()=>{let a=H.value.get(n)?.data.appCheckpoint?.updatedAt;if(a!==void 0&&a!==Ui){rm(n);return}if(Date.now()-o>=UR){rm(n);return}zn=setTimeout(i,Mk)};zn=setTimeout(i,Mk);return}if(zn!==null)clearTimeout(zn),zn=null;$o.value=null,Ui=void 0,Bt.value=null}function Tu(){let e=Ef(Array.from(H.value.values()),Array.from(et.value.values()),"grid");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;Nn(()=>{for(let[t,n]of e.nodePositions.entries())un(t,{position:n});for(let[t,n]of e.groupBounds.entries())_u(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),dn()}function Iu(){let e=Ef(Array.from(H.value.values()),Array.from(et.value.values()),"graph");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;Nn(()=>{for(let[t,n]of e.nodePositions.entries())un(t,{position:n});for(let[t,n]of e.groupBounds.entries())_u(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),dn()}var Ln=ie(!1),Do=ie(!1),Jo=ie("");function hm(){return Ln.value||Do.value}function GR(){return typeof matchMedia==="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}function gm(e,t){let n=Jt(),o=Tw(e,[...H.value.values()],n.width,n.height),i={...Te.value},s=GR()?0:(e.duration??1)*1000;Yk((a)=>Iw(i,o,a,n.width,n.height,e.easing,e.pullback),s,t)}var nS=0;function oS(e){let t=++nS,n=!Ln.value;Ln.value=!0,Jo.value="";let o=()=>{if(t!==nS)return;try{gm(e)}catch(i){Jo.value=i instanceof Error?i.message:String(i)}};if(n)requestAnimationFrame(()=>requestAnimationFrame(o));else o()}async function Eu(e){let t=await de("step tour","/api/canvas/tour/go",{ok:!1,error:"Could not reach the canvas server."},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,present:!1})});if(!t.ok)Jo.value=t.error??"Could not change the tour stop."}async function fl(e=!1){Ln.value=!0,Jo.value="";let t=e?(await de("read tour","/api/canvas/tour",{})).position:null;await Eu({stop:typeof t==="number"?t:0})}function ym(){Ln.value=!1,Jo.value="",oo("exit tour","/api/canvas/tour/exit",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})}var KR=0.1,VR=4,rS=1,XR=5;function iS(e){return Math.min(VR,Math.max(KR,e))}function Au({viewport:e,onViewportChange:t,onViewportCommit:n,onBackgroundContextMenu:o,onEdgeContextMenu:i,disabled:s=!1}){let a=D(null),l=D(!1),c=D({x:0,y:0}),u=D(null),d=D(0),p=D(null),f=oe((y)=>{if(p.current!==null)window.clearTimeout(p.current);p.current=window.setTimeout(()=>{p.current=null,n(y)},140)},[n]);function m(y){if(y.deltaMode!==0)return y.deltaX===0;return y.deltaX===0&&Number.isInteger(y.deltaY)&&Math.abs(y.deltaY)>=50}let h=oe((y)=>{if(s)return;y.preventDefault();let k=e.value;if(y.ctrlKey||y.metaKey||m(y)){let _=a.current?.getBoundingClientRect();if(!_)return;let I=y.clientX-_.left,w=y.clientY-_.top,P=-y.deltaY*0.002,L=iS(k.scale*(1+P)),N=L/k.scale,Y={x:I-N*(I-k.x),y:w-N*(w-k.y),scale:L};t(Y),f(Y)}else{let _={x:k.x-y.deltaX*rS,y:k.y-y.deltaY*rS,scale:k.scale};t(_),f(_)}},[s,e,t,f]),g=oe((y)=>{if(s)return;let k=a.current;if(!k)return;if(y.button===1||y.button===2)y.preventDefault();else if(Ds()){if(y.target!==k)return;y.preventDefault()}else return;u.current=y.button===2?{x:y.clientX,y:y.clientY,background:y.target===k,edgeId:y.target instanceof Element?y.target.getAttribute("data-edge-id"):null,dragged:!1}:null,l.current=!0,document.documentElement.classList.add("is-canvas-panning"),c.current={x:y.clientX,y:y.clientY},k.setPointerCapture(y.pointerId)},[s]),v=oe((y)=>{if(!l.current)return;if(s)return;let k=u.current;if(k&&!k.dragged){if(Math.hypot(y.clientX-k.x,y.clientY-k.y)<=XR)return;k.dragged=!0}let _=y.clientX-c.current.x,I=y.clientY-c.current.y;c.current={x:y.clientX,y:y.clientY};let w=e.value;t({x:w.x+_,y:w.y+I,scale:w.scale})},[s,e,t]),b=oe((y)=>{if(!l.current)return;y.preventDefault();let k=u.current;if(u.current=null,l.current=!1,document.documentElement.classList.remove("is-canvas-panning"),k&&!k.dragged){if(!s&&y.type==="pointerup"){if(k.edgeId)i?.(y,k.edgeId);else if(k.background){let _=a.current?.getBoundingClientRect();if(!_)return;let I=e.value;o?.(y,(y.clientX-_.left-I.x)/I.scale,(y.clientY-_.top-I.y)/I.scale)}}return}n(e.value)},[s,o,i,n,e]),x=oe((y)=>{if(s)return;if(y.touches.length!==2){d.current=0;return}y.preventDefault();let k=y.touches[0],_=y.touches[1],I=Math.hypot(_.clientX-k.clientX,_.clientY-k.clientY),w=(k.clientX+_.clientX)/2,P=(k.clientY+_.clientY)/2;if(d.current>0){let L=e.value,N=a.current?.getBoundingClientRect();if(!N)return;let Y=w-N.left,B=P-N.top,J=I/d.current,X=iS(L.scale*J),V=X/L.scale,ee={x:Y-V*(Y-L.x),y:B-V*(B-L.y),scale:X};t(ee),f(ee)}d.current=I},[s,e,t,f]),C=oe(()=>{if(p.current!==null)window.clearTimeout(p.current),p.current=null;n(e.value),d.current=0},[n,e]);return q(()=>{let y=a.current;if(!y)return;return y.addEventListener("wheel",h,{passive:!1}),y.addEventListener("pointerdown",g),y.addEventListener("pointermove",v),y.addEventListener("pointerup",b),y.addEventListener("pointercancel",b),y.addEventListener("lostpointercapture",b),y.addEventListener("touchmove",x,{passive:!1}),y.addEventListener("touchend",C),()=>{if(p.current!==null)window.clearTimeout(p.current);y.removeEventListener("wheel",h),y.removeEventListener("pointerdown",g),y.removeEventListener("pointermove",v),y.removeEventListener("pointerup",b),y.removeEventListener("pointercancel",b),y.removeEventListener("lostpointercapture",b),y.removeEventListener("touchmove",x),y.removeEventListener("touchend",C)}},[h,g,v,b,x,C]),q(()=>()=>{document.documentElement.classList.remove("is-canvas-panning")},[]),a}var JR=0;function r(e,t,n,o,i,s){t||(t={});var a,l,c=t;if("ref"in c)for(l in c={},t)l=="ref"?a=t[l]:c[l]=t[l];var u={type:e,props:c,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--JR,__i:-1,__u:0,__source:i,__self:s};if(typeof e=="function"&&(a=e.defaultProps))for(l in a)c[l]===void 0&&(c[l]=a[l]);return ct.vnode&&ct.vnode(u),u}function sS(){let e=Ln.value,t=cn.value,n=(i)=>{co(),Te.value=i},o=Au({viewport:Te,onViewportChange:n,onViewportCommit:n});return q(()=>{let i=new URLSearchParams(location.search);return Ln.value=i.get("present")==="1",Do.value=i.get("capture")==="1",window.pmxCapture={ready:()=>cn.value,area:Jt,camera:()=>({...Te.value}),frame:async(s)=>(Do.value=!0,co(),Te.value=Za.parse(s),await new Promise((a)=>requestAnimationFrame(()=>requestAnimationFrame(()=>a()))),{...Te.value})},()=>{delete window.pmxCapture,Ln.value=!1,Do.value=!1}},[]),q(()=>{if(t&&Ln.value&&!Do.value)fl(!0)},[t]),q(()=>{if(!e)return;let i=(s)=>{if(s.stopImmediatePropagation(),s.target instanceof HTMLButtonElement&&["Enter"," "].includes(s.key))return;if(["Escape","ArrowRight","ArrowDown","ArrowLeft","ArrowUp"," "].includes(s.key))s.preventDefault();if(s.key==="Escape")ym();if(["ArrowRight","ArrowDown"," "].includes(s.key))Eu({step:"next"});if(["ArrowLeft","ArrowUp"].includes(s.key))Eu({step:"previous"})};return document.addEventListener("keydown",i,!0),()=>document.removeEventListener("keydown",i,!0)},[e]),e?r(be,{children:[!Do.value&&r("div",{class:"presentation-navigation",ref:o,onPointerDown:(i)=>{if(i.button===1||i.button===2)co()},onContextMenu:(i)=>i.preventDefault(),children:r("button",{type:"button",class:"presentation-exit",onClick:ym,children:"Exit presentation"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Jo.value&&r("div",{class:"presentation-error",role:"alert",children:Jo.value},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null}var YR={fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"};function nt({size:e=16,children:t,...n}){return r("svg",{width:e,height:e,viewBox:"0 0 16 16",style:{verticalAlign:"middle",flexShrink:0},...YR,...n,children:t},void 0,!1,void 0,this)}function Tt(e){return r(nt,{...e,children:r("path",{d:"m4 4 8 8M12 4l-8 8"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function lS(e){return r(nt,{...e,children:r("path",{d:"M8 2v12M2 8h12"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function cS(e){return r(nt,{...e,children:[r("circle",{cx:"8",cy:"8",r:"6"},void 0,!1,void 0,this),r("path",{d:"M8 5v6M5 8h6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oi(e){return r(nt,{...e,children:r("polyline",{points:"6 3 11 8 6 13"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ml(e){return r(nt,{...e,children:[r("circle",{cx:"3",cy:"8",r:"0.75"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"8",r:"0.75"},void 0,!1,void 0,this),r("circle",{cx:"13",cy:"8",r:"0.75"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ri(e){return r(nt,{...e,children:r("path",{d:"M9 2h5v5M14 2 7 9M6 3H2v11h11v-4"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function uS(e){return r(nt,{...e,children:r("path",{d:"M9 2h5v5M14 2l-5 5M7 14H2V9M2 14l5-5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function dS(e){return r(nt,{...e,children:r("path",{d:"M14 8H2m5-5-5 5 5 5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Ru(e){return r(nt,{...e,children:r("path",{d:"M13.5 6A5.5 5.5 0 1 0 13 11M14 2v4h-4"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function bm(e){return r(nt,{...e,children:r("path",{d:"M6 2 2 6l4 4M2 6h7a4 4 0 0 1 0 8"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function pS(e){return r(nt,{...e,children:r("path",{d:"M8 10V2M4.5 5.5 8 2l3.5 3.5M2 10v3.5h12V10"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Us(e){return r(nt,{...e,children:r("polyline",{points:"3 6 8 11 13 6"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Pu(e){return r(nt,{...e,children:[r("polyline",{points:"1 5 1 1 5 1"},void 0,!1,void 0,this),r("polyline",{points:"11 1 15 1 15 5"},void 0,!1,void 0,this),r("polyline",{points:"15 11 15 15 11 15"},void 0,!1,void 0,this),r("polyline",{points:"5 15 1 15 1 11"},void 0,!1,void 0,this),r("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function fS(e){return r(nt,{...e,children:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),r("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this),r("line",{x1:"7",y1:"5",x2:"7",y2:"9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function mS(e){return r(nt,{...e,children:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),r("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Tr(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"4",x2:"9.5",y2:"4"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"12",x2:"9.5",y2:"12"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"6.5",x2:"4",y2:"9.5"},void 0,!1,void 0,this),r("line",{x1:"12",y1:"6.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function hS(e){return r(nt,{...e,children:[r("rect",{x:"1",y:"2",width:"14",height:"12",rx:"1.5"},void 0,!1,void 0,this),r("rect",{x:"8",y:"7",width:"6",height:"6",rx:"1",fill:"currentColor","fill-opacity":"0.2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function gS(e){return r(nt,{...e,children:r("path",{d:"M13 9.5A5.5 5.5 0 1 1 6.5 3 4.5 4.5 0 0 0 13 9.5Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function yS(e){return r(nt,{...e,children:[r("path",{d:"M3 13l2.8-.7L13 5.1 10.9 3 3.7 10.2 3 13Z"},void 0,!1,void 0,this),r("path",{d:"M9.8 4.1l2.1 2.1"},void 0,!1,void 0,this),r("path",{d:"M2.5 14h11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function vS(e){return r(nt,{...e,children:[r("path",{d:"M3 10.5 8.5 5a2 2 0 0 1 2.8 0l1.7 1.7a2 2 0 0 1 0 2.8L8.5 14H5.8L3 11.2Z"},void 0,!1,void 0,this),r("path",{d:"M7.5 6 12 10.5"},void 0,!1,void 0,this),r("path",{d:"M8.5 14H14"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bS(e){return r(nt,{...e,children:[r("path",{d:"M3 4h10"},void 0,!1,void 0,this),r("path",{d:"M8 4v8"},void 0,!1,void 0,this),r("path",{d:"M6 12h4"},void 0,!1,void 0,this),r("path",{d:"M4.5 4 4 6"},void 0,!1,void 0,this),r("path",{d:"M11.5 4 12 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Nu(e){return r(nt,{...e,children:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function js(e){return r(nt,{...e,children:r("path",{d:"M2 13 L2 4 A2 2 0 0 1 4 2 L12 2 A2 2 0 0 1 14 4 L14 9 A2 2 0 0 1 12 11 L5 11 Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function uo(e){return r(nt,{...e,children:r("path",{d:"M6 2.67h4l-.53 3.66 1.86 2H4.67l1.86-2zM8 8.33v5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Mu({size:e=22,class:t}){return r("svg",{width:e,height:e,viewBox:"0 0 64 64",xmlns:"http://www.w3.org/2000/svg",class:t,"aria-hidden":"true",children:[r("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.35"},void 0,!1,void 0,this),r("rect",{x:"16",y:"16",width:"32",height:"32",rx:"5",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.6"},void 0,!1,void 0,this),r("rect",{x:"24",y:"24",width:"16",height:"16",rx:"3",fill:"none",stroke:"currentColor","stroke-width":"2.2"},void 0,!1,void 0,this),r("rect",{x:"29",y:"29",width:"6",height:"6",rx:"1",fill:"currentColor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xS({size:e=15}){return r("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:r("path",{d:"M3 2l10 5.5-4.2 1.3L7.5 13z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function wS({size:e=15}){return r("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:r("path",{d:"M5 7.5V3.8a1 1 0 0 1 2 0V7m0-3.9a1 1 0 0 1 2 0V7m0-2.7a1 1 0 0 1 2 0V7.4m0-.9a1 1 0 0 1 2 0v3.2A4.3 4.3 0 0 1 8.7 14H8a4.3 4.3 0 0 1-3.6-2L2.7 9.3a1 1 0 0 1 1.6-1.2L5 9.2"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ni(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"6",x2:"10",y2:"6"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"8.5",x2:"8",y2:"8.5"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"11",x2:"11",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function QR(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M4 13.5 L5.5 11.5 L8 11.5"},void 0,!1,void 0,this),r("polyline",{points:"5 6 7 8 5 10"},void 0,!1,void 0,this),r("line",{x1:"8",y1:"10",x2:"11",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function eP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M12 13.5 L10.5 11.5 L8 11.5"},void 0,!1,void 0,this),r("circle",{cx:"5",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"11",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function aS(e){return r(nt,{...e,children:[r("path",{d:"M3 1.5h6l3.5 3.5v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V2.5a1 1 0 0 1 1-1z"},void 0,!1,void 0,this),r("polyline",{points:"9 1.5 9 5 12.5 5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"8.5",x2:"10.5",y2:"8.5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"11",x2:"9",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function tP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("circle",{cx:"5.5",cy:"6.5",r:"1.2"},void 0,!1,void 0,this),r("path",{d:"M1.8 12 L6 8.5 L9 11 L11.5 9 L14.2 12"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Hs(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"1.5",y1:"5.5",x2:"14.5",y2:"5.5"},void 0,!1,void 0,this),r("circle",{cx:"3.3",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"5",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"6.7",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"8",x2:"12",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"10",x2:"10",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nP(e){return r(nt,{...e,children:[r("rect",{x:"2",y:"4",width:"12",height:"10",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"2",y1:"6.5",x2:"14",y2:"6.5"},void 0,!1,void 0,this),r("path",{d:"M11 1.5 L11 4"},void 0,!1,void 0,this),r("circle",{cx:"11",cy:"4",r:"1.6",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xm(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"1.5","stroke-dasharray":"2 1.5"},void 0,!1,void 0,this),r("rect",{x:"4",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),r("rect",{x:"8.5",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),r("rect",{x:"6.25",y:"8.5",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function rP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M3.5 10.5 L6 6.5 L8.5 9.5 L12.5 5"},void 0,!1,void 0,this),r("circle",{cx:"12.5",cy:"5",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function iP(e){return r(nt,{...e,children:[r("rect",{x:"2",y:"2",width:"12",height:"12",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"5.5",x2:"11.5",y2:"5.5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"8",x2:"11.5",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"10.5",x2:"8",y2:"10.5"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"2",x2:"6.5",y2:"14",opacity:"0.45"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"2"},void 0,!1,void 0,this),r("path",{d:"M4 11 L4 6 L6 8.5 L8 6 L8 11"},void 0,!1,void 0,this),r("path",{d:"M10 11 L10 6 L12.5 11 L12.5 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function aP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("polyline",{points:"10 5 13 5 13 8"},void 0,!1,void 0,this),r("line",{x1:"13",y1:"5",x2:"8",y2:"10"},void 0,!1,void 0,this),r("path",{d:"M6 6 L3.5 6 L3.5 11.5 L10 11.5 L10 9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function lP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M7 5.5 C 5.5 5.5 5.5 8 4 8 C 5.5 8 5.5 10.5 7 10.5"},void 0,!1,void 0,this),r("path",{d:"M9 5.5 C 10.5 5.5 10.5 8 12 8 C 10.5 8 10.5 10.5 9 10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function vm(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"5.2",y1:"6",x2:"8",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"8",y1:"8",x2:"10.8",y2:"6"},void 0,!1,void 0,this),r("line",{x1:"8",y1:"8",x2:"8",y2:"11"},void 0,!1,void 0,this),r("circle",{cx:"5.2",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"10.8",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"8",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"11",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Bo(e){switch(e){case"markdown":return ni;case"prompt":return QR;case"response":return eP;case"file":return aS;case"diff":return aS;case"mermaid":return vm;case"image":return tP;case"webpage":return Hs;case"context":return nP;case"group":return xm;case"status":return oP;case"trace":return rP;case"ledger":return iP;case"mcp-app":return sP;case"ext-app":return aP;case"json-render":return lP;case"graph":return vm;case"board":return vm;case"html":return Hs;default:return ni}}function cP(e){return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function uP(){nu()}function kS(){let e=Ka.value;if(e.length===0)return null;let t=qr.value,n=_s.value;if(!t)return r("button",{type:"button",class:"attention-history-tab",onClick:uP,"aria-label":n>0?`Recent updates — ${n} new`:"Recent updates",children:[r("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"attention-history-tab-label",children:"Updates"},void 0,!1,void 0,this),n>0&&r("span",{class:"attention-history-tab-badge","aria-hidden":"true",children:n>9?"9+":n},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("aside",{class:"attention-history","aria-label":"Recent semantic changes",children:[r("div",{class:"attention-history-header",children:[r("div",{class:"attention-history-header-text",children:[r("span",{class:"attention-history-title",children:"Recent Updates"},void 0,!1,void 0,this),r("span",{class:"attention-history-subtitle",children:"Focus and meaning shifts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"attention-history-close",onClick:Dw,"aria-label":"Collapse changes panel",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"attention-history-list",children:e.map((o)=>r("article",{class:`attention-history-entry attention-tone-${o.tone}`,children:[r("div",{class:"attention-history-meta",children:[r("span",{class:"attention-history-kind",children:o.title},void 0,!1,void 0,this),r("time",{class:"attention-history-time",dateTime:new Date(o.createdAt).toISOString(),children:cP(o.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{class:"attention-history-detail",children:o.detail},void 0,!1,void 0,this)]},o.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function SS(){let e=eu.value;if(!e)return null;return r("button",{type:"button",class:`attention-toast attention-tone-${e.tone}`,onClick:nu,"aria-label":`${e.title}${e.detail?`: ${e.detail}`:""} — open change history`,children:[r("span",{class:"attention-toast-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"attention-toast-copy",children:[r("span",{class:"attention-toast-title",children:e.title},void 0,!1,void 0,this),e.detail&&r("span",{class:"attention-toast-detail",children:e.detail},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var gl=ie(null),_S=0;function On(e,t,n={}){return new Promise((o)=>{gl.value?.resolve(null),_S+=1,gl.value={seq:_S,title:e,placeholder:t,initial:n.initial??"",allowEmpty:n.allowEmpty??!1,confirm:n.confirm??"Add",resolve:o}})}function hl(e){let t=gl.value;gl.value=null,t?.resolve(e)}function CS(){let e=gl.value,t=D(null);if(q(()=>{if(!e)return;let o=(i)=>{if(i.key!=="Escape")return;i.preventDefault(),i.stopPropagation(),hl(null)};return window.addEventListener("keydown",o,{capture:!0}),()=>window.removeEventListener("keydown",o,{capture:!0})},[e]),!e)return null;let n=()=>{let o=t.current?.value.trim()??"";hl(o?o:e.allowEmpty?"":null)};return r("div",{class:"text-prompt-backdrop",onPointerDown:()=>hl(null),children:r("div",{class:"text-prompt",role:"dialog","aria-label":e.title,"data-testid":"text-prompt",onPointerDown:(o)=>o.stopPropagation(),children:[r("div",{class:"text-prompt-title",children:e.title},void 0,!1,void 0,this),r("input",{ref:(o)=>{if(t.current=o,!o)return;if(o.focus(),e.initial)o.select()},class:"text-prompt-input",type:"text",defaultValue:e.initial,placeholder:e.placeholder,onKeyDown:(o)=>{if(o.key==="Enter")o.preventDefault(),o.stopPropagation(),n();else if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),hl(null)}},e.seq,!1,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",onClick:()=>hl(null),children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"button",class:"text-prompt-confirm",onClick:n,children:e.confirm},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Zs({children:e}){let t=Ke(()=>document.createElement("div"),[]);return Me(()=>(document.body.appendChild(t),()=>{Aa(null,t),t.remove()}),[t]),Me(()=>Aa(e,t),[e,t]),null}function _e({label:e,shortcut:t,body:n,align:o="center",side:i="down",tapToOpen:s=!1,fitWithin:a,children:l}){let[c,u]=E(null),d=(f)=>{if(!a)return;let m=f.currentTarget,h=m.closest(a)?.getBoundingClientRect(),g=m.querySelector(".toolbar-tooltip")?.getBoundingClientRect();if(!h||!g)return;let v=m.getBoundingClientRect(),b=v.right-g.width>=h.left,x=v.left+g.width<=h.right;u(b||!x?"end":"start")};return r("span",{class:`toolbar-tooltip-anchor toolbar-tooltip-anchor-${c??o}${i==="up"?" toolbar-tooltip-anchor-up":""}${s?" toolbar-tooltip-anchor-tap":""}`,tabIndex:s?-1:void 0,onPointerEnter:a?d:void 0,onFocusIn:a?d:void 0,children:[l,r("span",{class:"toolbar-tooltip",role:"tooltip",children:[r("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),n&&r("span",{class:"toolbar-tooltip-body",children:n},void 0,!1,void 0,this),t&&r("span",{class:"toolbar-tooltip-meta",children:r("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)}async function ii(e,t,n,o){if((await vu({type:t,sourceNodeId:e.id,sourceSurface:"native-node",...n?{payload:n}:{}})).ok)hn("context",o,"",[e.id])}var Gi={padding:"3px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer",flexShrink:0};function dP(e){let t=e.title||e.label||e.key||"Context",n=e.summary?.trim()||"Available in startup context.",o=e.pathDisplay||e.path||"",i=e.category==="profile"?"Operator":e.category==="planning"||e.category==="memory"?"Product":e.category?e.category.charAt(0).toUpperCase()+e.category.slice(1):void 0,s=e.sourceKind==="global"?"Global":"Workspace",a=e.state==="missing"?"Missing":e.state==="stale"?"Stale":e.state==="invalid"?"Invalid":"Loaded";return{title:t,summary:n,pathDisplay:o,category:i,sourceKind:s,status:a,required:e.required===!0}}function Fo(e){return typeof e==="string"?e.trim():""}function pP(e){return e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function fP(e){let t=Fo(e.title),n=Fo(e.content),o=pP(Fo(e.rendered)),i=n||o,s=Fo(e.path);if(!t&&!i&&!s)return null;return{title:t||"Context",summary:i,path:s}}function mP(e){let t=Fo(e.data.title)||e.id,n=Fo(e.data.content)||Fo(e.data.excerpt)||Fo(e.data.description)||Fo(e.data.pageTitle)||"",o=Fo(e.data.path)||Fo(e.data.url);return{id:e.id,title:t,summary:n,kind:an[e.type]??e.type,path:o}}function TS(e){if(e===null||!Number.isFinite(e)||e<0)return"0";if(e>=1e6)return`${(e/1e6).toFixed(1)}m`;if(e>=1000)return`${(e/1000).toFixed(1)}k`;return`${Math.round(e)}`}function hP(e){if(e>=0.95)return"var(--c-danger)";if(e>=0.85)return"var(--c-warn)";if(e>=0.7)return"var(--c-warn)";return"var(--c-accent)"}function zu({node:e,expanded:t=!1,pinnedNodes:n=[]}){let o=e.data.cards??[],i=e.data.auxTabs??[],s=n.map(mP),a=s.length>0,l=typeof e.data.currentTokens==="number"?e.data.currentTokens:null,c=typeof e.data.tokenLimit==="number"?e.data.tokenLimit:null,u=typeof e.data.utilization==="number"?e.data.utilization:null,d=typeof e.data.messagesLength==="number"?e.data.messagesLength:null,p=u!==null?Math.max(0,Math.min(100,Math.round(u*100))):null,f=hP(u??0),m=!a&&o.length===0&&i.length===0?fP(e.data):null,h=async(g)=>{let v=typeof g.path==="string"?g.path.trim():"";if(!v)return;await mu(v)};return r("div",{style:{display:"flex",flexDirection:"column",gap:t?"10px":"6px",fontSize:t?"14px":"12px",maxWidth:t?"760px":void 0,margin:t?"0 auto":void 0,width:t?"100%":void 0,padding:t?"8px 0":void 0},children:[r("div",{style:{display:"flex",justifyContent:"flex-end"},children:r(_e,{label:"Point the agent at this node",body:"Sets it as the agent's current AX focus, so the agent pulls it into context to work on next — a one-click alternative to pinning.",align:"end",fitWithin:".node-content",children:r("button",{type:"button",class:"ax-node-action",style:Gi,onClick:(g)=>{g.stopPropagation(),ii(e,"ax.focus.set",void 0,"Focus set")},children:"Set focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),c!==null&&c>0&&r("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:"Token Usage"},void 0,!1,void 0,this),r("div",{style:{height:"6px",background:"var(--c-surface-hover)",borderRadius:"3px",overflow:"hidden",marginBottom:"4px"},children:r("div",{style:{height:"100%",width:`${Math.min(100,(u??0)*100)}%`,background:f,borderRadius:"3px",transition:"width 0.3s ease"}},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{style:{fontSize:"11px",color:"var(--c-muted)"},children:[p,"% — ",TS(l)," / ",TS(c)," tokens",d!==null&&r(be,{children:[" · ",d," messages"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&r("div",{children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Pinned Context (",s.length,")"]},void 0,!0,void 0,this),s.map((g)=>r("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[r("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:g.title},void 0,!1,void 0,this),g.summary&&r("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px",whiteSpace:"pre-wrap"},children:g.summary},void 0,!1,void 0,this),r("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:g.kind},void 0,!1,void 0,this)},void 0,!1,void 0,this),g.path&&r("div",{style:{marginTop:"6px"},children:[r("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:g.path},void 0,!1,void 0,this),g.path.startsWith("/")&&r("button",{type:"button",onClick:()=>void mu(g.path),style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},g.id,!0,void 0,this))]},void 0,!0,void 0,this),!a&&o.length>0&&r("div",{children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Context (",o.length,")"]},void 0,!0,void 0,this),o.map((g)=>{let v=dP(g);return r("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[r("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:v.title},void 0,!1,void 0,this),r("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px"},children:v.summary},void 0,!1,void 0,this),v.pathDisplay&&r("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all"},children:v.pathDisplay},void 0,!1,void 0,this),r("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:[r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"color-mix(in srgb, var(--c-accent) 10%, transparent)",color:"var(--c-accent)",borderRadius:"3px",display:"inline-block"},children:v.status},void 0,!1,void 0,this),v.category&&r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:v.category},void 0,!1,void 0,this),r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:v.sourceKind},void 0,!1,void 0,this),v.required&&r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)",borderRadius:"3px",display:"inline-block"},children:"Required"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),g.path&&r("div",{style:{marginTop:"6px"},children:r("button",{type:"button",onClick:()=>void h(g),style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},g.key??v.pathDisplay??v.title,!0,void 0,this)})]},void 0,!0,void 0,this),!a&&i.length>0&&r("div",{children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px",marginTop:o.length>0?"8px":0},children:["References (",i.length,")"]},void 0,!0,void 0,this),i.map((g)=>r("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",style:{display:"block",padding:"4px 8px",color:"var(--c-accent)",fontSize:"11px",textDecoration:"none",borderRadius:"4px",marginBottom:"2px",wordBreak:"break-all"},children:[g.url,g.reason&&r("span",{style:{color:"var(--c-dim)",fontSize:"10px",marginLeft:"6px"},children:["(",g.reason,")"]},void 0,!0,void 0,this)]},g.id,!0,void 0,this))]},void 0,!0,void 0,this),m&&r("div",{style:{padding:"8px 10px",background:"var(--c-surface-subtle)",borderRadius:"6px",borderLeft:"2px solid var(--c-accent)"},children:[r("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"4px"},children:m.title},void 0,!1,void 0,this),m.summary&&r("div",{style:{color:"var(--c-text-soft)",fontSize:"11px",lineHeight:1.5,whiteSpace:"pre-wrap"},children:m.summary},void 0,!1,void 0,this),m.path&&r("div",{style:{marginTop:"6px"},children:[r("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:m.path},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>void mu(m.path),style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!a&&!m&&o.length===0&&i.length===0&&r("div",{style:{color:"var(--c-dim)",fontStyle:"italic"},children:"No context loaded"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function IS(e){return e.replace(/^[ab]\//,"")}function gP(e,t){if(t&&t!=="/dev/null")return IS(t);if(e&&e!=="/dev/null")return IS(e);return null}function yP(e){if(!e.trim())return[];let t=e.split(`
89
- `);if(t.length>0&&t[t.length-1]==="")t.pop();let n=[],o=null,i=!1,s=(a)=>{let l={path:a,lines:[]};return i=!1,n.push(l),l};for(let a=0;a<t.length;a++){let l=t[a]??"",c=l.match(/^diff --git a\/(.+?) b\/(.+)$/);if(c){o=s(c[2]??null);continue}let u=t[a+1]??"";if(l.startsWith("--- ")&&u.startsWith("+++ ")){let p=gP(l.slice(4).trim(),u.slice(4).trim());if(o&&!i){if(!o.path)o.path=p}else o=s(p);a++;continue}if(!o)o=s(null);let d=o;if(l.startsWith("@@"))i=!0,d.lines.push({kind:"hunk",text:l});else if(l.startsWith("+"))d.lines.push({kind:"add",text:l});else if(l.startsWith("-"))d.lines.push({kind:"remove",text:l});else d.lines.push({kind:"context",text:l})}return n}function $u({node:e}){let t=typeof e.data.content==="string"?e.data.content:"",n=Ke(()=>yP(t),[t]);if(n.length===0)return r("div",{class:"diff-node diff-node-empty",children:"Empty diff"},void 0,!1,void 0,this);return r("div",{class:"diff-node",children:n.map((o,i)=>r("div",{class:"diff-file",children:[o.path&&r("div",{class:"diff-file-header",children:o.path},void 0,!1,void 0,this),r("pre",{class:"diff-lines",children:o.lines.map((s,a)=>r("div",{class:s.kind==="hunk"?"diff-hunk":`diff-line-${s.kind}`,children:s.text||" "},a,!1,void 0,this))},void 0,!1,void 0,this)]},`${o.path??"anonymous"}-${i}`,!0,void 0,this))},void 0,!1,void 0,this)}function ES(e){let t=e.toLowerCase();if(t.endsWith(".csv"))return",";if(t.endsWith(".tsv"))return"\t";return null}function AS(e,t){let n=[],o=[],i="",s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a=!0,s){if(u==='"')if(e[c+1]==='"')i+='"',c++;else s=!1;else if(u==="\r"&&e[c+1]===`
88
+ ${kn(e.data,["content"])}`,n);case"image":return Yt(kn(e.data,["alt","caption","description"])||"No image description available; inspect the image.",n);case"group":return Yt(`Group: ${kn(e.data,["title"])||"Untitled"}. ${Array.isArray(e.data.children)?e.data.children.length:0} cards.`,n)}}function hr(e,t){let n=e.position.x+e.size.width,o=e.position.y+e.size.height,i=t.position.x+t.size.width,s=t.position.y+t.size.height,a=Math.max(0,Math.max(e.position.x,t.position.x)-Math.min(n,i)),l=Math.max(0,Math.max(e.position.y,t.position.y)-Math.min(o,s));return Math.sqrt(a**2+l**2)}function gR(e){let t=[...e],n=100;return t.sort((o,i)=>{let s=Math.floor(o.position.y/100),a=Math.floor(i.position.y/100);if(s!==a)return s-a;return o.position.x-i.position.x}),t}function yR(e){let t=e.find((i)=>i.data.title&&typeof i.data.title==="string");if(t&&e.length<=3)return e.filter((s)=>s.data.title).map((s)=>s.data.title).slice(0,3).join(", ");let n={};for(let i of e)n[i.type]=(n[i.type]??0)+1;let o=Object.entries(n).map(([i,s])=>s===1?i:`${s} ${i}`);if(t)return`${t.data.title} + ${o.join(", ")}`;return o.join(", ")}function vR(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function bR(e,t){let n=t.filter((i)=>vR(e.bounds,{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height})),o=n.map((i)=>typeof i.data.title==="string"&&i.data.title.length>0?i.data.title:i.id);return{id:e.id,label:e.label??e.text??null,bounds:e.bounds,targetNodeIds:n.map((i)=>i.id),targetNodeTitles:o,target:o.length>0?o.join(", "):"empty canvas region"}}function xR(e,t=200){if(e.length===0)return[];let n=new Map,o=(c)=>{while(n.get(c)!==c){let u=n.get(c);n.set(c,n.get(u)),c=u}return c},i=(c,u)=>{let d=o(c),p=o(u);if(d!==p)n.set(d,p)};for(let c of e)n.set(c.id,c.id);for(let c=0;c<e.length;c++)for(let u=c+1;u<e.length;u++)if(hr(e[c],e[u])<=t)i(e[c].id,e[u].id);let s=new Map;for(let c of e){let u=o(c.id);if(!s.has(u))s.set(u,[]);s.get(u).push(c)}let a=[],l=0;for(let[,c]of s){if(c.length<2)continue;let u=c.map((b)=>b.position.x),d=c.map((b)=>b.position.y),p=c.map((b)=>b.position.x+b.size.width),f=c.map((b)=>b.position.y+b.size.height),m=Math.min(...u),h=Math.min(...d),g=Math.max(...p),v=Math.max(...f);a.push({id:`cluster-${l++}`,nodeIds:c.map((b)=>b.id),label:yR(c),centroid:{x:Math.round((m+g)/2),y:Math.round((h+v)/2)},bounds:{x:m,y:h,width:g-m,height:v-h}})}return a.sort((c,u)=>{let d=Math.floor(c.centroid.y/200),p=Math.floor(u.centroid.y/200);if(d!==p)return d-p;return c.centroid.x-u.centroid.x}),a}function Nf(e,t,n=5,o=600){let i=e.filter((a)=>t.has(a.id)),s=e.filter((a)=>!t.has(a.id));return i.map((a)=>{let l=s.map((c)=>({node:c,distance:hr(a,c)})).filter((c)=>c.distance<=o).sort((c,u)=>c.distance-u.distance).slice(0,n);return{pinnedNodeId:a.id,pinnedNodeTitle:a.data.title??null,neighbors:l.map((c)=>({id:c.node.id,type:c.node.type,title:c.node.data.title??null,distance:Math.round(c.distance)}))}})}function Ka(e,t,n,o=[]){let i=xR(e),s=new Map;for(let u of i)for(let d of u.nodeIds)s.set(d,u.id);let l=gR(e).map((u,d)=>({id:u.id,type:u.type,title:u.data.title??null,content:Mw(u,{defaultTextLength:320,webpageTextLength:640})||null,clusterId:s.get(u.id)??null,readingOrder:d})),c=Nf(e,n);return{totalNodes:e.length,clusters:i,nodesInReadingOrder:l,pinnedNeighborhoods:c,annotations:o.map((u)=>bR(u,e))}}function Ss(e){if(!e)return null;let t=e.data.title;return typeof t==="string"&&t.trim().length>0?t.trim():null}function Jc(e,t){return{id:e?.id??t,title:Ss(e),nodeType:e?.type??"markdown"}}function zw(e,t){return{id:e.id,edgeType:e.type,fromId:e.from,toId:e.to,...e.toBoardId!==void 0?{toBoardId:e.toBoardId}:{},fromTitle:Ss(t.get(e.from)),toTitle:e.toBoardId===void 0?Ss(t.get(e.to)):null}}function Yc(e){return new Map(e.map((t)=>[t.id,t]))}function $w(e){return new Map(e.map((t)=>[t.id,t]))}function Ao(e){return Array.from(e).sort((t,n)=>t.localeCompare(n))}function Mf(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function zf(e){if(!e||e.type!=="group")return[];let t=e.data.children;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string").sort((n,o)=>n.localeCompare(o))}function Lw(e){let t=new Map;for(let n of e.clusters){let o=[...n.nodeIds].sort((i,s)=>i.localeCompare(s));for(let i of o)t.set(i,o.filter((s)=>s!==i))}return t}function Ow(e){let t=new Map;for(let n of e.pinnedNeighborhoods)t.set(n.pinnedNodeId,n.neighbors.map((o)=>o.id).sort((o,i)=>o.localeCompare(i)));return t}function wR(e,t){let n=Ao(Array.from(t).filter((i)=>!e.has(i))),o=Ao(Array.from(e).filter((i)=>!t.has(i)));return{added:n,removed:o}}function Dw(e){let t=e&&typeof e==="object"?e:{};return{timestamp:typeof t.timestamp==="string"?t.timestamp:void 0,sessionId:typeof t.sessionId==="string"?t.sessionId:void 0}}function kR(e,t,n){if(!e||!n)return{layout:e,pinnedNodeIds:[],primaryFocusNodeIds:[],secondaryFocusNodeIds:[],regions:[],spatial:n};let o=Yc(e.nodes),i=Ao(t).filter((c)=>o.has(c)),s=new Set(i),a=new Set,l=[];for(let c of n.pinnedNeighborhoods){if(!s.has(c.pinnedNodeId))continue;let u=Ao([c.pinnedNodeId,...c.neighbors.map((d)=>d.id)]).filter((d,p,f)=>f.indexOf(d)===p&&o.has(d));for(let d of u)if(!s.has(d))a.add(d);l.push({id:`region-${c.pinnedNodeId}`,primaryNodeId:c.pinnedNodeId,nodeIds:u})}if(l.length===0&&i.length>0)for(let c of i)l.push({id:`region-${c}`,primaryNodeId:c,nodeIds:[c]});return{layout:e,pinnedNodeIds:i,primaryFocusNodeIds:i,secondaryFocusNodeIds:Ao(a),regions:l,spatial:n}}class Qc{currentBoardId;currentLayout=null;currentPins=new Set;previousSpatial=null;setInitialPins(e){this.currentPins=new Set(e)}getAttentionSnapshot(){return kR(this.currentLayout,this.currentPins,this.previousSpatial)}handleMessage(e){if(e.event==="context-pins-changed"||e.event==="canvas-layout-update"){let t=e.data&&typeof e.data==="object"?e.data:{};if(typeof t.boardId==="string"||t.boardId===null){if(this.currentBoardId!==void 0&&t.boardId!==this.currentBoardId)this.currentLayout=null,this.currentPins.clear(),this.previousSpatial=null;this.currentBoardId=t.boardId}}if(e.event==="context-pins-changed")return this.handleContextPinsChanged(e.data);if(e.event==="canvas-layout-update")return this.handleLayoutUpdate(e.data);return[]}handleContextPinsChanged(e){let t=e&&typeof e==="object"?e:{},n=Array.isArray(t.nodeIds)?t.nodeIds.filter((u)=>typeof u==="string"):[],o=Dw(e),i=new Set(n),{added:s,removed:a}=wR(this.currentPins,i);if(this.currentPins=i,!this.currentLayout)return[];let l=Yc(this.currentLayout.nodes),c={added:s.map((u)=>Jc(l.get(u),u)),removed:a.map((u)=>Jc(l.get(u),u))};if(this.previousSpatial=Ka(this.currentLayout.nodes,this.currentLayout.edges,this.currentPins,this.currentLayout.annotations??[]),c.added.length===0&&c.removed.length===0)return[];return[{type:"context-pin",...o,...c}]}handleLayoutUpdate(e){let t=e&&typeof e==="object"?e:{},n=t.layout&&typeof t.layout==="object"?t.layout:null;if(!n)return[];let o=Dw(e);if(!this.currentLayout)return this.currentLayout=n,this.previousSpatial=Ka(n.nodes,n.edges,this.currentPins,n.annotations??[]),[];let i=this.currentLayout,s=this.previousSpatial??Ka(i.nodes,i.edges,this.currentPins,i.annotations??[]),a=Ka(n.nodes,n.edges,this.currentPins,n.annotations??[]),l=[],c=Yc(i.nodes),u=Yc(n.nodes),d=$w(i.edges),p=$w(n.edges),f=Ao(Array.from(p.keys()).filter((b)=>!d.has(b))).map((b)=>p.get(b)).filter((b)=>b!==void 0);if(f.length>0)l.push({type:"connect",...o,edges:f.map((b)=>zw(b,u))});let m=Ao(Array.from(c.keys()).filter((b)=>!u.has(b))),h=Ao(Array.from(d.keys()).filter((b)=>!p.has(b)));if(m.length>0||h.length>0)l.push({type:"remove",...o,nodes:m.map((b)=>Jc(c.get(b),b)),edges:h.map((b)=>d.get(b)).filter((b)=>b!==void 0).map((b)=>zw(b,c))});let g=this.buildGroupEvent(c,u,o);if(g)l.push(g);let v=this.buildMoveEndEvent(i,n,c,u,s,a,o);if(v)l.push(v);return this.currentLayout=n,this.previousSpatial=a,l}buildGroupEvent(e,t,n){let o=Ao(Array.from(e.values()).filter((l)=>l.type==="group").map((l)=>l.id)),i=Ao(Array.from(t.values()).filter((l)=>l.type==="group").map((l)=>l.id)),s=i.filter((l)=>!o.includes(l)).map((l)=>{let c=t.get(l),u=zf(c);return{id:l,title:Ss(c),childCount:u.length}}),a=[];for(let l of i.filter((c)=>o.includes(c))){let c=zf(e.get(l)),u=zf(t.get(l));if(Mf(c,u))continue;a.push({id:l,title:Ss(t.get(l)),addedChildIds:u.filter((d)=>!c.includes(d)),removedChildIds:c.filter((d)=>!u.includes(d)),childCount:u.length})}if(s.length===0&&a.length===0)return null;return{type:"group",...n,created:s,updated:a}}buildMoveEndEvent(e,t,n,o,i,s,a){let l=Ao(Array.from(o.keys()).filter((v)=>{let b=n.get(v),x=o.get(v);if(!b||!x)return!1;return b.position.x!==x.position.x||b.position.y!==x.position.y}));if(l.length===0)return null;let c=Lw(i),u=Lw(s),d=Ow(i),p=Ow(s),f=new Map,m=(v,b)=>{let x=f.get(v)??new Set;x.add(b),f.set(v,x)};for(let v of l){let b=c.get(v)??[],x=u.get(v)??[];if(!Mf(b,x))if(b.length===0&&x.length>0)m(v,"joined cluster");else if(b.length>0&&x.length===0)m(v,"left cluster");else m(v,"cluster changed")}let h=new Set([...d.keys(),...p.keys()]);for(let v of h){let b=d.get(v)??[],x=p.get(v)??[];if(Mf(b,x))continue;let C=Ss(o.get(v)??n.get(v))??v,y=x.filter((_)=>!b.includes(_)),k=b.filter((_)=>!x.includes(_));for(let _ of y)if(l.includes(_))m(_,`entered pinned neighborhood of "${C}"`);for(let _ of k)if(l.includes(_))m(_,`left pinned neighborhood of "${C}"`);if(l.includes(v))m(v,"pinned neighborhood changed")}let g=l.filter((v)=>(f.get(v)?.size??0)>0).map((v)=>{let b=o.get(v);return{...Jc(b,v),reasons:Array.from(f.get(v)??[]).sort((x,C)=>x.localeCompare(C))}});if(g.length===0)return null;return{type:"move-end",...a,nodes:g}}}var eu=ie(null),Va=ie([]),tu=ie(new Set),qr=ie(!1),_s=ie(0);function Bw(){eu.value=null,Va.value=[],tu.value=new Set,qr.value=!1,_s.value=0}function nu(){qr.value=!0,_s.value=0}function Fw(){qr.value=!1}function ou(e){eu.value=e}function $f(e,t=6){if(Va.value=[e,...Va.value].slice(0,t),!qr.value)_s.value=Math.min(99,_s.value+1)}function ru(e){tu.value=new Set(e)}var Hw=30000;var Lf=80;var qt=ie(new Map),Ts=ie(null),SR=480,_R=320,CR=650,Xa=new Map,Cs=new Map,iu=new Map,gr=null;function Of(e){qt.value=e,TR()}function Df(e){let t=Xa.get(e);if(t)clearTimeout(t),Xa.delete(e)}function Bf(e){let t=Cs.get(e);if(t)clearTimeout(t),Cs.delete(e)}function jw(e){if(Df(e.id),Bf(e.id),!qt.value.has(e.id))iu.set(e.id,Date.now());let t=new Map(qt.value);t.set(e.id,{...e,phase:"forming"}),Of(t)}function zi(e){if(Df(e),Bf(e),iu.delete(e),!qt.value.has(e))return;let t=new Map(qt.value);t.delete(e),Of(t)}function Uw(e,t,n,o){let i=qt.value.get(e);if(!i||i.phase===t)return;let s=new Map(qt.value);s.set(e,{...i,phase:t,...o?{settledNodeId:o}:{}}),Of(s),Df(e),Xa.set(e,setTimeout(()=>zi(e),n+1500))}function Zw(e,t,n,o){Bf(e);let i=Date.now()-(iu.get(e)??0),s=Math.max(0,CR-i);if(s===0){Uw(e,t,n,o);return}Cs.set(e,setTimeout(()=>{Cs.delete(e),Uw(e,t,n,o)},s))}function Ww(e,t){Zw(e,"settling",SR,t)}function Ff(e){Zw(e,"dissolving",_R)}function su(){for(let e of Xa.values())clearTimeout(e);Xa.clear();for(let e of Cs.values())clearTimeout(e);if(Cs.clear(),iu.clear(),gr)clearInterval(gr),gr=null;Ts.value=null,qt.value=new Map}function TR(){if(gr||qt.value.size===0)return;gr=setInterval(()=>{let e=Date.now();for(let t of qt.value.values())if(t.phase==="forming"&&t.expiresAt<=e)Ff(t.id);if(qt.value.size===0&&gr)clearInterval(gr),gr=null},1000),gr.unref?.()}var Hf;function tt(){return Hf!==void 0}var Gt=(e,t)=>Hf?Hf(e,t):globalThis.fetch(e,t),qw;async function Gw(e){if(!qw)throw Error("This host does not support downloads. The export is saved in the local PMX workspace.");if(!/^\/api\/canvas\/exports\/[^/?#]+$/.test(e))throw Error("Invalid export path.");let t=await Gt(e);if(!t.ok)throw Error("Could not read the export. Try again.");if((await qw({name:decodeURIComponent(e.slice(e.lastIndexOf("/")+1)),mimeType:"text/html",text:await t.text()})).isError)throw Error("The download was cancelled or declined by the host.")}function IR(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 Kr=IR("pmx-canvas-human-client",()=>`tab-${Math.random().toString(36).slice(2,8)}`);function ER(){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-${Kr.slice(-4)}`}var Vw=ie(ER()),Xw=ie([]),Ya=Ve(()=>Xw.value.filter((e)=>e.clientId!==Kr)),$i=ie(new Map);function Uf(e){if(!e||!Array.isArray(e.humans))return;Xw.value=e.humans}var Wo=ie(null),cu=null,Jw=0,Gr=null;function lu(e){if(tt())return;oo("humanPresence","/api/canvas/human-presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:Kr,name:Vw.value,...e})})}function Kw(){Gr=null,Jw=Date.now(),lu({cursor:cu,grabbingNodeId:Wo.value})}function uu(e){cu=e;let t=Date.now()-Jw;if(t>=Lf){if(Gr)clearTimeout(Gr);Kw()}else if(!Gr)Gr=setTimeout(Kw,Lf-t)}function jf(e){Wo.value=e,lu({cursor:cu,grabbingNodeId:e})}function AR(e,t){let n=new Map($i.value);n.set(e,t),$i.value=n,setTimeout(()=>{let o=new Map($i.value);if(o.get(e)===t)o.delete(e),$i.value=o},6000)}function Yw(e,t){let n=[...qt.value.values()].filter((i)=>i.nodeId===e&&!i.auto&&i.phase==="forming");if(n.length===0)return;let o=Vw.value;AR(e,o);for(let i of n)Li({id:i.id,kind:i.kind,label:i.label,reason:`${o} took over “${t}” mid-edit — yield and requeue the change once it is released`}).then((s)=>{if(s)zi(i.id)});oo("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 au=null,Ja=null;function Qa(){if(au)clearInterval(au);if(au=null,Gr)clearTimeout(Gr);if(Gr=null,Ja)window.removeEventListener("pagehide",Ja);Ja=null}function Qw(){Qa(),lu({cursor:cu,grabbingNodeId:Wo.value}),au=setInterval(()=>lu({grabbingNodeId:Wo.value}),3000),Ja=()=>{try{navigator.sendBeacon?.("/api/canvas/human-presence",new Blob([JSON.stringify({clientId:Kr,left:!0})],{type:"application/json"}))}catch{}},window.addEventListener("pagehide",Ja)}var Mt=(e)=>JSON.stringify([e.boardId,e.cardId??null]);var Xn=ie(null),Oi=ie(!1),Zf=Ve(()=>Oe.value?Ro.value:"All"),Is=ie(null),ek=0;async function Kt(){let e=++ek,t=wt,n=await pe("knowledge","/api/canvas/knowledge",null);if(e!==ek||t!==wt)return;if(Oi.value=n?.ok!==!0,n?.ok===!0)Xn.value=n}function Jn(e){return se.value?Xn.value?.cards[Mt({boardId:se.value,cardId:e})]:void 0}var Di=Ve(()=>new Set([...kt.value].filter((e)=>!Jn(e)?.retired)));function Es(e){if(Oe.value&&se.value)Ct.value={boardId:se.value,nodeId:e,incarnation:wt}}var tk="",nk=new Map,ro=Ve(()=>{let e=Di.value,t=new Map;if(e.size>0){let o=new Map,i=[...H.value.values()].filter((s)=>!Jn(s.id)?.retired);for(let s of Nf(i,e)){let a=s.pinnedNodeTitle??s.pinnedNodeId;for(let l of s.neighbors){let c=o.get(l.id)??[];c.push({pinNodeId:s.pinnedNodeId,pinTitle:a,distance:l.distance}),o.set(l.id,c)}}for(let[s,a]of o)a.sort((l,c)=>l.distance-c.distance),t.set(s,a.map(({pinNodeId:l,pinTitle:c})=>({pinNodeId:l,pinTitle:c})))}let n=[...t].sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>`${o}:${i.map((s)=>`${s.pinNodeId}=${s.pinTitle}`).join(",")}`).join("|");if(n===tk)return nk;return tk=n,nk=t,t}),ok=Ve(()=>{let e=new Map;for(let[t,n]of ro.value)for(let o of n){let i=e.get(o.pinNodeId)??[];i.push(t),e.set(o.pinNodeId,i)}return e}),el=ie(null),du=ie(null),rk=Ve(()=>{let e=kt.value;if(e.size===0)return{pinIds:[],ringOnly:!1};let t=Wo.value;if(t&&!e.has(t)){let s=H.value.get(t),a=null,l=Number.POSITIVE_INFINITY;for(let c of e){let u=H.value.get(c);if(!s||!u)continue;let d=hr(s,u);if(d<l)l=d,a=c}return{pinIds:a?[a]:[],ringOnly:!0}}let n=new Set;if(t)n.add(t);let o=el.value;if(o&&e.has(o))n.add(o);for(let s of st.value)if(e.has(s))n.add(s);let i=du.value;for(let s of i&&ro.value.get(i)||[])n.add(s.pinNodeId);return{pinIds:[...n],ringOnly:!1}}),Bi=ie(null),Wf;function ik(e){qf(e),Wf=ro.value.get(e)}function sk(e){let t=Wf;Wf=void 0;let n=ro.value.get(e);if(n&&!t)Bi.value={nodeId:e,kind:"in",pins:n};else if(t&&!n)Bi.value={nodeId:e,kind:"out",pins:t}}function qf(e){if(Bi.value?.nodeId===e)Bi.value=null}var Vr=ie(null),qo=null;function ak(e,t,n){if(qo)clearTimeout(qo);qo=null;let o=t.getBoundingClientRect();Vr.value={nodeId:e,at:{left:o.left,right:o.right,top:o.top,bottom:o.bottom},view:n}}function As(){if(qo)clearTimeout(qo);qo=setTimeout(()=>{qo=null,Vr.value=null},160)}function Gf(){if(qo)clearTimeout(qo);qo=null}var ck=new Qc,Rs=[],tl=null,Ps=null,Kf="",Vf=0;function uk(e,t){return globalThis.setTimeout(e,t)}function Xf(e){if(e===null)return;globalThis.clearTimeout(e)}function RR(e){if(typeof globalThis.requestAnimationFrame==="function"){globalThis.requestAnimationFrame(()=>e());return}e()}function Ko(e,t){return e&&e.trim().length>0?e.trim():t}function Go(e,t=3){if(e.length===0)return"";if(e.length<=t)return e.join(", ");return`${e.slice(0,t).join(", ")} +${e.length-t}`}function PR(e){return Array.from(new Set(Array.from(e).filter((t)=>t.length>0)))}function vo(e,t,n,o,i=Date.now()){return{id:`${e}-${i}-${Math.random().toString(36).slice(2,8)}`,tone:e,title:t,detail:n,nodeIds:PR(o),createdAt:i}}function NR(e){if(e==="joined cluster")return"joined a nearby cluster";if(e==="left cluster")return"moved away from its cluster";if(e==="cluster changed")return"shifted into a different cluster";if(e==="pinned neighborhood changed")return"changed the local focus field";return e}function lk(e,t){let n=new RegExp(`^${t} pinned neighborhood of "(.+)"$`);return e.flatMap((o)=>n.exec(o)?.[1]??[])}function MR(e,t,n){let o=(l)=>l.map((c)=>`“${c}”`).join(" and "),i=lk(n,"entered");if(i.length>0)return{title:"Near a pin",body:`“${e}” is now near ${o(i)} — the agent gets its title and summary.`};let s=lk(n,"left");if(s.length===0)return null;let a=ro.value.get(t)??[];return{title:"Left a pin",body:a.length>0?`“${e}” left ${o(s)} — still near ${o(a.map((l)=>l.pinTitle))}.`:`“${e}” left ${o(s)} — it is out of the agent’s brief.`}}function zR(e){let t=e.added.map((i)=>Ko(i.title,i.id)),n=e.removed.map((i)=>Ko(i.title,i.id));if(t.length===0&&n.length===0)return null;let o="";if(t.length>0&&n.length===0)o=`Now in focus: ${Go(t)}`;else if(n.length>0&&t.length===0)o=`Removed from focus: ${Go(n)}`;else{let i=[];if(t.length>0)i.push(`${Go(t)} added`);if(n.length>0)i.push(`${Go(n)} removed`);o=i.join(" · ")}return vo("context","Context updated",o,[...e.added.map((i)=>i.id),...e.removed.map((i)=>i.id)],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function $R(e){if(e.edges.length===0)return null;if(e.edges.length===1){let t=e.edges[0];return vo("relationship","Relationship added",`${Ko(t.fromTitle,t.fromId)} linked to ${Ko(t.toTitle,t.toId)}`,[t.fromId,...!t.toBoardId||t.toBoardId===se.value?[t.toId]:[]],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return vo("relationship","Relationships added",`${e.edges.length} connections changed the board structure`,e.edges.flatMap((t)=>[t.fromId,...!t.toBoardId||t.toBoardId===se.value?[t.toId]:[]]),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function LR(e){if(e.nodes.length===0&&e.edges.length===0)return null;if(e.nodes.length===0){let o=e.edges.map((i)=>`“${Ko(i.fromTitle,i.fromId)}” – “${Ko(i.toTitle,i.toId)}” (${i.edgeType})`);return vo("remove",o.length===1?"Link removed":"Links removed",Go(o),e.edges.flatMap((i)=>[i.fromId,...!i.toBoardId||i.toBoardId===se.value?[i.toId]:[]]),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}let t=e.nodes.map((o)=>Ko(o.title,o.id)),n=[];if(t.length>0)n.push(Go(t));if(e.edges.length>0)n.push(`${e.edges.length} relationship${e.edges.length===1?"":"s"}`);return vo("remove","Items removed",n.join(" · "),[...e.nodes.map((o)=>o.id),...e.edges.flatMap((o)=>[o.fromId,...!o.toBoardId||o.toBoardId===se.value?[o.toId]:[]])],e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}function OR(e){if(e.created.length>0){let t=e.created.map((n)=>Ko(n.title,n.id));return vo("group",e.created.length===1?"Group created":"Groups created",e.created.length===1?`${t[0]} now frames ${e.created[0].childCount} items`:Go(t),e.created.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}if(e.updated.length>0){let t=e.updated.map((n)=>Ko(n.title,n.id));return vo("group",e.updated.length===1?"Group updated":"Groups updated",e.updated.length===1?`${t[0]} now holds ${e.updated[0].childCount} items`:Go(t),e.updated.map((n)=>n.id),e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now())}return null}function DR(e){if(e.nodes.length===0)return null;let t=e.nodes.flatMap((s)=>s.reasons),n=e.nodes.map((s)=>Ko(s.title,s.id)),o=e.timestamp?Date.parse(e.timestamp)||Date.now():Date.now();if(t.some((s)=>s.includes("pinned neighborhood"))){let s=e.nodes.length===1?MR(n[0],e.nodes[0].id,e.nodes[0].reasons):null;if(s)return vo("neighborhood",s.title,s.body,[e.nodes[0].id],o);return vo("neighborhood","Neighborhood changed",Go(n),e.nodes.map((a)=>a.id),o)}let i=t.filter((s)=>s.includes("cluster"));if(i.length>0){let s=i.every((a)=>a==="joined cluster");if(e.nodes.length===1)return vo("cluster",s?"Cluster formed":"Cluster changed",`${n[0]} ${NR(e.nodes[0].reasons[0])}`,e.nodes.map((a)=>a.id),o);return vo("cluster",s?"Cluster formed":"Cluster changed",Go(n),e.nodes.map((a)=>a.id),o)}return null}function BR(e){switch(e.type){case"context-pin":return zR(e);case"connect":return $R(e);case"remove":return LR(e);case"group":return OR(e);case"move-end":return DR(e)}}function dk(){if(tl!==null)return;let e=Rs.shift()??null;if(!e){ou(null);return}ou(e);let t=Math.max(1800,Math.min(2800,1600+e.detail.length*18));tl=uk(()=>{tl=null,ou(null),dk()},t)}function pk(e){if(Rs.push(e),Rs.length>3)Rs.splice(0,Rs.length-3);dk()}function hn(e,t,n="",o=[]){let i=vo(e,t,n,o);$f(i),pk(i)}function FR(e){if(Xf(Ps),Ps=null,ru([]),e.length===0)return;RR(()=>{ru(e),Ps=uk(()=>{Ps=null,ru([])},900)})}function HR(e){let t=`${e.tone}:${e.title}:${e.detail}`,n=e.createdAt;if(t===Kf&&n-Vf<1200)return!0;return Kf=t,Vf=n,!1}function pu(){Xf(tl),Xf(Ps),tl=null,Ps=null,Rs=[],Kf="",Vf=0,ck=new Qc,Bw()}function nl(e){let t=ck.handleMessage(e).map((n)=>BR(n)).filter((n)=>n!==null);for(let n of t){if(HR(n))continue;$f(n),pk(n),FR(n.nodeIds)}}function Jf(e,t){console.error(`[intent-bridge] ${e} failed`,t)}var fu=(()=>{try{let e=new URLSearchParams(window.location.search).get("agent")?.trim();return e?e.slice(0,64):null}catch{return null}})();function Yf(e){if(tt())return e??{};let t={...e?.headers};if(fu)t["x-pmx-source"]=fu;else{t["X-PMX-Workbench"]="1";let n=window.__PMX_WORKBENCH_TOKEN;if(typeof n==="string")t["X-PMX-Workbench-Token"]=n}return{...e,headers:t}}function Qf(e,t,n){if(e.ok||(t?.method??"GET").toUpperCase()==="GET")return;let o=n!==null&&typeof n==="object"&&"error"in n&&typeof n.error==="string"?n.error:"";hn("remove","Change refused",o||`The server answered ${e.status}.`)}async function em(e){try{return await e.json()}catch{return null}}async function pe(e,t,n,o){try{let i=await Gt(t,Yf(o)),s=await em(i);if(Qf(i,o,s),s===null)throw Error(`${i.status} response had no JSON body`);return s}catch(i){return Jf(e,i),n}}async function so(e,t,n){try{let o=await Gt(t,Yf(n));if(!o.ok)Qf(o,n,await em(o));return{ok:o.ok}}catch(o){return Jf(e,o),{ok:!1}}}async function oo(e,t,n){try{let o=await Gt(t,Yf(n));if(!o.ok)Qf(o,n,await em(o))}catch(o){Jf(e,o)}}async function fk(e,t={}){return pe("sendIntent","/api/workbench/intent",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:e,payload:t})})}async function Li(e){let n=`Veto: do not ${e.label?.trim()||`${e.kind} intent`}${e.reason?` — ${e.reason}`:""}.`;if((await pe("vetoGhostIntent",`/api/canvas/ax/intent/${encodeURIComponent(e.id)}`,{ok:!1,cleared:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({vetoed:!0})})).cleared!==!0)return!1;return await oo("vetoGhostSteering","/api/canvas/ax/steer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:n,source:"browser"})}),!0}async function Vo(e,t,n=se.value){return(await pe("renderMarkdown","/api/render",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({markdown:e,...t?{nodeId:t,expectedBoardId:n}:{}})})).html??null}async function ol(e){return pe("fetchFile",`/api/file?path=${encodeURIComponent(e)}`,{content:""})}async function mu(e){return so("openWorkbenchFile","/api/workbench/open",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})})}async function mk(e){return pe("fetchCanvasState",`/api/canvas/state?includeBlobs=true&expectedBoardId=${encodeURIComponent(e??"null")}`,{})}async function hu(e){return pe("saveCanvasTheme","/api/canvas/theme",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:e})})}async function hk(){return[]}async function rl(e,t,n,o,i){if(!e.trim())return{ok:!1,error:"Prompt text is required"};return pe("submitCanvasPrompt","/api/canvas/prompt",{ok:!1,error:"Network error"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e,...t?{position:t}:{},...n?{parentNodeId:n}:{},...o&&o.length>0?{contextNodeIds:o}:{},...i?{threadNodeId:i}:{}})})}async function gk(e,t){return rl(t,void 0,void 0,void 0,e)}async function gu(e,t={}){await oo("pushCanvasUpdate","/api/canvas/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e,...io.value?{expectedBoardId:se.value}:{},...t.recordHistory===!1?{recordHistory:!1}:{}})})}async function yr(e,t,n,o,i={}){let s=Po.value,a=await pe("createEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:t,type:n,label:o,...i})});if(s===Po.value&&H.value.has(e)&&(i.toBoardId||H.value.has(t))){if(a.ok){let{ok:l,...c}=a;zs(c)}else if(!a.error)hn("remove","Connection not added","Could not reach the server. Try again.")}return a}async function No(e){return pe("createNodeFromClient","/api/canvas/node",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function ln(e,t){return pe("updateNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function yu(e,t){return pe("refreshWebpageNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}/refresh`,{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{url:t}:{})})}async function Xr(e){return pe("removeNodeFromClient",`/api/canvas/node/${encodeURIComponent(e)}`,{ok:!1},{method:"DELETE"})}async function yk(){return pe("fetchAxSurfaceState","/api/canvas/ax/surface-snapshot",null)}async function vk(e,t){return pe("openNodeInSystemBrowserRequest","/api/canvas/open-external",{ok:!1,opened:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeId:e,url:t})})}async function vu(e){return pe("submitAxInteractionFromClient","/api/canvas/ax/interaction",{ok:!1,code:"request-failed",error:"Request failed"},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceSurface:"native-node",...e,source:"browser"})})}async function bu(e,t={}){return pe("updateViewportFromClient","/api/canvas/viewport",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...bk(),clientId:Kr,...io.value?{expectedBoardId:se.value}:{},...t.recordHistory===!1?{recordHistory:!1}:{}})})}function bk(){if(typeof window>"u")return{};let e=Jt(),t=Math.round(e.width),n=Math.round(e.height);if(!t||!n)return{};let{top:o,bottom:i}=qa();return{clientWidth:t,clientHeight:n,clientInsets:{top:o,bottom:i}}}async function Jr(){if(tt()&&!io.value)return;let e=bk();if(!("clientWidth"in e))return;await oo("reportClientViewportSize","/api/canvas/viewport",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...io.value?{expectedBoardId:se.value}:{},recordHistory:!1})})}async function Ns(e){return pe("createGroupFromClient","/api/canvas/group",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function tm(e,t,n){return pe("addToGroupFromClient","/api/canvas/group/add",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e,childIds:t,...n?{childLayout:n}:{}})})}async function xu(e,t){return ln(e,{children:t})}async function Ms(e){return pe("ungroupFromClient","/api/canvas/group/ungroup",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:e})})}async function xk(){return pe("listSnapshots","/api/canvas/snapshots?all=true",[])}async function wk(e){return pe("saveSnapshot","/api/canvas/snapshots",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})})}async function kk(e){return pe("restoreSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"POST"})}async function Sk(e){return pe("deleteSnapshot",`/api/canvas/snapshots/${e}`,{ok:!1},{method:"DELETE"})}async function Fi(e,t){return pe("updateEdgeFromClient",`/api/canvas/edge/${encodeURIComponent(e)}`,{ok:!1},{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function wu(e){return pe("removeEdgeFromClient","/api/canvas/edge",{ok:!1},{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({edge_id:e})})}var Ge=ie([]),se=ie(null),ut=ie(!1),Ct=ie(null),Ro=ie("All");sn(()=>{se.value,Ro.value="All"});var bo=ie(0),io=ie(!1),nm=null,Sn=null,Mo=null,wt=0,om=0,ku=null,il=0,_k=Promise.resolve(),Yr=0,tn=0;sn(()=>{Oe.value,tn++});function Ck(e){if(e===Sn)return;Sn=e,Mo=null,wt++,om=0,ku=null,il++,Yr++,Ct.value=null}function Tk(e){nm=e}function Qr(e){if(!e||!Array.isArray(e.boards)||e.catalogEpoch!==Sn||typeof e.catalogRevision!=="number"||typeof e.reloadRevision!=="number"||e.catalogRevision<=om)return;om=e.catalogRevision;let t=typeof e.activeBoardId==="string"?e.activeBoardId:null,n=!io.value,o=Mo===null&&typeof e.boardGeneration==="number",i=!n&&(t!==se.value||ku!==null&&e.reloadRevision!==ku||Mo!==null&&typeof e.boardGeneration==="number"&&e.boardGeneration!==Mo);if(i)wt++,Ct.value=null;if(typeof e.boardGeneration==="number")Mo=e.boardGeneration;ku=e.reloadRevision,Nn(()=>{if(Ge.value=e.boards,se.value=t,io.value=!0,i||n)nm?.(n);else if(o)nm?.(!0)})}async function sl(){let e=await pe("loadBoards","/api/canvas/boards",null);Qr(e)}async function al(e,t,n,o){return pe(e,t,null,{method:n,headers:{"Content-Type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}})}function Ik(){let e=++Yr;return()=>e===Yr}async function Mn(e){let t=++il;Yr++,Ct.value=null;let n=Sn,o=null,i=_k.then(async()=>{if(n===Sn)o=await al("openBoard","/api/canvas/boards/open","POST",{id:e})});if(_k=i.catch(()=>{return}),await i,t===il&&n===Sn&&o)Nn(()=>{if(Qr(o),e!==null)ut.value=!1})}async function zt(e,t={}){if(t.review&&!Oe.value)return!1;let n=tn,o=Mn(e.boardId),i=Yr;await o;let s=wt;if(!e.cardId)return i===Yr&&se.value===e.boardId;for(let a=0;a<400;a++){if(i!==Yr||se.value!==e.boardId||wt!==s||ut.value||t.review&&(!Oe.value||n!==tn))return!1;if(cn.value&&H.value.has(e.cardId)){let l=ll.value.get(e.cardId);if(l)Hi(l);if($t(e.cardId),t.review)Ct.value={boardId:e.boardId,nodeId:e.cardId,incarnation:s};return!0}await new Promise((l)=>window.setTimeout(l,25))}return!1}async function Ek(e,t){let n=++il;Yr++,Ct.value=null;let o=Sn,i=await pe("createBoard","/api/canvas/boards",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,...t?{folder:t}:{}})});if(i?.board&&n===il&&o===Sn)await Mn(i.board.id)}async function Ak(e){return pe("previewBoardCopy","/api/canvas/boards/from",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceBoardId:e,name:"Preview",preview:!0})})}async function Rk(e){let t=await pe("createBoardFrom","/api/canvas/boards/from",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await sl(),t?.board??null}async function vr(e,t){let n=await al("updateBoard",`/api/canvas/boards/${encodeURIComponent(e)}`,"PATCH",{...t,...t.folder===null?{folder:""}:{}});return Qr(n),n!==null}async function $s(e,t){let n=`/api/canvas/boards/${encodeURIComponent(e)}/${t?"pin":"unpin"}`;Qr(await al(t?"pinBoard":"unpinBoard",n,"POST",{}))}async function Pk(e,t){let n=await al("setBoardReadme",`/api/canvas/boards/${encodeURIComponent(e)}`,"PATCH",{readmeNodeId:t});Qr(n)}async function Nk(e){let t=await al("deleteBoard",`/api/canvas/boards/${encodeURIComponent(e)}`,"DELETE");Qr(t)}function Yn(){return Ge.value.find((e)=>e.id===se.value)??null}function Ok(e,t){console.error(`[canvas-store] ${e} failed`,t)}var Ee=ie({x:0,y:0,scale:1}),H=ie(new Map),et=ie(new Map),Os=ie(new Map),gt=ie(null),br=ie(null),ao=ie("connecting"),Zi=ie(0),Wi=ie(0),qi=ie(0),xr=ie(""),Ds=ie(!1),Qt=ie("harbor"),cn=ie(!1),Lo=ie(null),Bt=ie(null),zo=ie(null),zn=null,Ui,Mk=100,UR=2500,ul=ie(null),Po=ie(0),At=ie(null),wr=ie(null),st=ie(new Set),kt=ie(new Set),Wn=ie("select"),dl=ie(!1);function Bs(){return Wn.value==="pan"||dl.value}function Dk(e,t){if(!e)return new Set;let n=new Set;for(let o of t.values()){if(o.toBoardId!==void 0)continue;if(o.from===e)n.add(o.to);if(o.to===e)n.add(o.from)}return n}var Bk=Ve(()=>Dk(gt.value,et.value));function zk(e,t){let n=new Set;for(let o of e)if(t.has(o))n.add(o);return n}function $k(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function sm(e){let t=new Set(st.value);if(t.has(e))t.delete(e);else t.add(e);st.value=t}function Fk(e){st.value=new Set(e)}function $n(){if(br.value=null,st.value.size===0)return;st.value=new Set}function Hk(){if(co(),zn!==null)clearTimeout(zn),zn=null;Nn(()=>{Po.value+=1,$o++,ji=0,gt.value=null,Bt.value=null,zo.value=null,Ui=void 0,st.value=new Set,br.value=null,ul.value=null,At.value=null,wr.value=null,Xo.value=null,kt.value=new Set}),Su=!1}var Xo=ie(null),Su=!1;function Uk(){Su=!0,Xo.value=null}function jk(){Su=!1,Xo.value=null}function rm(e){return{x:e.position.x,y:e.position.y,w:e.size.width,h:e.size.height}}function jR(e,t,n){let o=rm(e);return t>=o.x&&t<=o.x+o.w&&n>=o.y&&n<=o.y+o.h}function Lk(e,t){let n=rm(e),o=rm(t);return n.x+n.w<o.x||n.x>o.x+o.w||n.y+n.h<o.y||n.y>o.y+o.h}function Zk(e){let t=H.value.get(e);if(!t||t.type==="group")return;let n=typeof t.data.parentGroup==="string"?t.data.parentGroup:null,o=n?H.value.get(n):void 0,i=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=null;for(let l of H.value.values()){if(l.type!=="group"||l.id===n||l.collapsed)continue;if(jR(l,i,s))a=l}if(!Su){let l=a?{nodeId:e,groupId:a.id,mode:"add"}:o&&Lk(t,o)?{nodeId:e,groupId:o.id,mode:"remove"}:null,c=Xo.value;if((c?.groupId??null)!==(l?.groupId??null)||c?.mode!==l?.mode)Xo.value=l}if(o&&o.data.frameMode!=="manual"&&!Lk(t,o)){let c=Math.min(o.position.x,t.position.x-22),u=Math.min(o.position.y,t.position.y-22-32),d=Math.max(o.position.x+o.size.width,t.position.x+t.size.width+22),p=Math.max(o.position.y+o.size.height,t.position.y+t.size.height+22);if(c!==o.position.x||u!==o.position.y||d!==o.position.x+o.size.width||p!==o.position.y+o.size.height)Cu(o.id,{position:{x:c,y:u},size:{width:d-c,height:p-u}},{skipGroupChildTranslation:!0})}}var ll=Ve(()=>{let e=new Map;for(let t of H.value.values()){if(t.type!=="group"||!t.collapsed)continue;let n=Array.isArray(t.data.children)?t.data.children:[];for(let o of n)if(typeof o==="string")e.set(o,t.id)}return e});function Fs(e){let t=ll.value.get(e);return H.value.get(t??e)}function Wk(){let e=new Set;for(let t of st.value){let n=H.value.get(t);if(!n)continue;if(n.type==="group")e.add(n.id);else if(typeof n.data.parentGroup==="string")e.add(n.data.parentGroup)}return[...e]}function am(e){let t=lm();if(t.length<2)return;let n=Math.min(...t.map((c)=>e==="left"?c.position.x:c.position.y)),o=24,i=new Map;for(let c of t)i.set(c.id,e==="left"?{x:n,y:c.position.y}:{x:c.position.x,y:n});let s=(c,u)=>c.x<u.x+u.w&&u.x<c.x+c.w&&c.y<u.y+u.h&&u.y<c.y+c.h,a=t.map((c)=>{let u=i.get(c.id);return{node:c,x:u.x,y:u.y,w:c.size.width,h:c.size.height}});if(a.some((c,u)=>a.some((d,p)=>p>u&&s(c,d)))){let c=[...t].sort((d,p)=>e==="left"?d.position.y-p.position.y:d.position.x-p.position.x),u=e==="left"?Math.min(...t.map((d)=>d.position.y)):Math.min(...t.map((d)=>d.position.x));for(let d of c)i.set(d.id,e==="left"?{x:n,y:u}:{x:u,y:n}),u+=(e==="left"?d.size.height:d.size.width)+o}Nn(()=>{for(let c of t)un(c.id,{position:i.get(c.id)})}),dn()}function qk(){let e=lm().sort((l,c)=>l.position.x-c.position.x);if(e.length<3)return;let t=e[0],o=e[e.length-1].position.x-(t.position.x+t.size.width),i=e.slice(1,-1),s=i.reduce((l,c)=>l+c.size.width,0),a=(o-s)/(i.length+1);Nn(()=>{if(a<8){let c=t.position.x+t.size.width+24;for(let u of e.slice(1))un(u.id,{position:{x:c,y:u.position.y}}),c+=u.size.width+24;return}let l=t.position.x+t.size.width+a;for(let c of i)un(c.id,{position:{x:l,y:c.position.y}}),l+=c.size.width+a}),dn()}function Gk(e=24){let t=lm().sort((l,c)=>l.position.y-c.position.y||l.position.x-c.position.x);if(t.length<2)return;let n=Math.min(...t.map((l)=>l.position.x)),o=Math.min(...t.map((l)=>l.position.y)),i=Math.ceil(Math.sqrt(t.length)),s=Math.max(...t.map((l)=>l.size.width)),a=Math.max(...t.map((l)=>l.size.height));Nn(()=>{t.forEach((l,c)=>{un(l.id,{position:{x:n+c%i*(s+e),y:o+Math.floor(c/i)*(a+e)}})})}),dn()}function lm(){let e=st.value;if(e.size===0)return[];return Array.from(e).map((t)=>H.value.get(t)).filter((t)=>t!==void 0)}var $o=0,ji=0;function lo(e){let t=new Set(kt.value);if(t.has(e))t.delete(e);else t.add(e);kt.value=t,dn(),pl(t)}function _u(e){let t=new Set(kt.value);for(let n of e)t.add(n);kt.value=t,dn(),pl(t)}function Kk(e){let t=new Set(kt.value);for(let n of e)t.delete(n);kt.value=t,dn(),pl(new Set(e),"remove")}function cm(){if(kt.value.size===0)return;kt.value=new Set,dn(),pl(new Set)}function um(e){$o++,kt.value=new Set(e)}async function dm(){if(ji>0)return;let e=$o,t=Po.value,o=(await pe("refreshContextPins","/api/workbench/poll",{})).events?.find((i)=>i.event==="context-pins-changed")?.payload;if(e===$o&&t===Po.value&&o?.boardId===se.value&&Array.isArray(o.nodeIds))um(o.nodeIds),nl({event:"context-pins-changed",data:o})}function pl(e,t="set"){$o++,ji++;let n=Po.value;oo("syncContextPinsToServer","/api/canvas/context-pins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeIds:Array.from(e),mode:t,...io.value?{expectedBoardId:se.value}:{}})}).then(()=>{if(n!==Po.value)return;ji--,$o++,dm()})}var cl=1;function kr(e){Nn(()=>{let t=new Map(H.value);if(e.zIndex>=cl)cl=e.zIndex+1;t.set(e.id,e),H.value=t,gt.value=e.id})}function un(e,t){Cu(e,t)}function Cu(e,t,n={}){let o=H.value.get(e);if(!o)return;let i=new Map(H.value);if(o.type==="group"&&t.position&&n.skipGroupChildTranslation!==!0){let a=t.position.x-o.position.x,l=t.position.y-o.position.y;if(a!==0||l!==0){let c=Array.isArray(o.data.children)?o.data.children.filter((u)=>typeof u==="string"):[];for(let u of c){let d=i.get(u);if(!d||d.type==="group")continue;i.set(u,{...d,position:{x:d.position.x+a,y:d.position.y+l}})}}}i.set(e,{...o,...t}),H.value=i;let s=i.get(e)?.data.appCheckpoint?.updatedAt;if(zo.value===e&&s!==void 0&&s!==Ui)im(e)}function Xe(e,t){let n=H.value.get(e);if(!n)return;un(e,{data:{...n.data,...t}})}function ei(e){ZR(e);let t=new Map(H.value);if(t.delete(e),H.value=t,gt.value===e)gt.value=null;if(Bt.value===e)Bt.value=null;if(st.value.has(e)){let n=new Set(st.value);n.delete(e),st.value=n}if(kt.value.has(e)){let n=new Set(kt.value);n.delete(e),kt.value=n,pl(n)}}function zs(e){let t=new Map(et.value);t.set(e.id,e),et.value=t}function Vk(e){let t=new Map(et.value);t.delete(e),et.value=t}function ZR(e){let t=!1,n=new Map(et.value);for(let[o,i]of n)if(i.from===e||i.toBoardId===void 0&&i.to===e)n.delete(o),t=!0;if(t)et.value=n}function WR(e){let t=new Map(Os.value);if(!t.delete(e))return;Os.value=t}async function pm(e){return so("createAnnotationFromClient","/api/canvas/annotation",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Xk(e){let t=await so("removeAnnotationFromClient",`/api/canvas/annotation/${encodeURIComponent(e)}`,{method:"DELETE"});if(t.ok)WR(e);return t}function Tu(e,t){if(!H.value.get(e))return;un(e,{size:t})}function Sr(e){let t=H.value.get(e);if(!t)return;Nn(()=>{if(un(e,{zIndex:cl++}),t.type==="group"&&Array.isArray(t.data.children)){for(let n of t.data.children)if(typeof n==="string"&&H.value.has(n))un(n,{zIndex:cl++})}}),gt.value=e}function Hi(e){let t=H.value.get(e);if(!t)return;un(e,{collapsed:!t.collapsed}),dn()}function Jk(e){Ee.value={...Ee.value,...e}}function fm(e){Ee.value=e}function mm(e,t={}){Ee.value=e,dn(t),bu(e,t)}function hm(e,t={}){let n=new Map,o=1;for(let p of e.nodes){let f=H.value.get(p.id);if(n.set(p.id,t.applyViewport!==!0&&f&&(f.contentRevision??0)>(p.contentRevision??0)?{...p,data:f.data,contentRevision:f.contentRevision,lastEditedBy:f.lastEditedBy}:p),p.zIndex>=o)o=p.zIndex+1}let i=e.edges.filter((p)=>n.has(p.from)&&(p.toBoardId!==void 0||n.has(p.to))),s=new Map;for(let p of i)s.set(p.id,p);let a=new Map;for(let p of e.annotations??[])a.set(p.id,p);let l=gt.value!==null&&n.has(gt.value)?gt.value:null,c=Bt.value!==null&&n.has(Bt.value)?Bt.value:null,u=zk(st.value,n),d=zk(kt.value,n);Nn(()=>{if(t.applyViewport===!0&&e.viewport)Ee.value=e.viewport;if(cl=o,H.value=n,et.value=s,Os.value=a,gt.value=l,Bt.value=c,!$k(st.value,u))st.value=u;if(!$k(kt.value,d))kt.value=d})}var Ls=null;function qR(e){return 1-(1-e)**3}function ti(e,t=150){let n=Ee.value,o=Math.min(4,Math.max(0.1,n.scale*e));if(o===n.scale)return;let i=o/n.scale,{x:s,y:a}=Zr();_r({x:s-i*(s-n.x),y:a-i*(a-n.y),scale:o},t)}function _r(e,t=300,n={}){let o={...Ee.value};gm((i)=>{let s=qR(i);return{x:o.x+(e.x-o.x)*s,y:o.y+(e.y-o.y)*s,scale:o.scale+(e.scale-o.scale)*s}},t,()=>mm(e,n))}function gm(e,t,n){co();let o=performance.now(),i=(s)=>{let a=t<=0?1:Math.min(1,(s-o)/t);if(Ee.value=e(a),a<1)Ls=requestAnimationFrame(i);else Ls=null,n?.(Ee.value)};if(t<=0)i(o);else Ls=requestAnimationFrame(i)}function co(){if(Ls!==null)cancelAnimationFrame(Ls),Ls=null}var Yk="pmx-canvas-layout";function dn(e={}){try{let t=Array.from(H.value.values()),n=t.map((i)=>({id:i.id,position:i.position,size:i.size,collapsed:i.collapsed})),o={viewport:Ee.value,nodes:t.map((i)=>({id:i.id,type:i.type,position:i.position,size:i.size,collapsed:i.collapsed,pinned:i.pinned})),edges:Array.from(et.value.values()).map((i)=>({id:i.id,from:i.from,to:i.to,...i.toBoardId!==void 0?{toBoardId:i.toBoardId}:{},type:i.type,label:i.label,style:i.style,animated:i.animated})),contextPinnedNodeIds:Array.from(kt.value)};if(!tt())localStorage.setItem(Yk,JSON.stringify(o));gu(n,e)}catch(t){Ok("persistLayout",t)}}function ym(){try{let e=localStorage.getItem(Yk);if(!e)return null;let t=JSON.parse(e),n=Array.isArray(t.nodes)?t.nodes:[];if(n.length===0)return null;let o=new Map;for(let i of n){if(typeof i.id!=="string"||i.id.length===0)continue;o.set(i.id,{...i.position?{position:i.position}:{},...i.size?{size:i.size}:{},...i.collapsed!==void 0?{collapsed:i.collapsed}:{},...i.pinned!==void 0?{pinned:i.pinned}:{}})}return o.size>0?o:null}catch(e){return Ok("restoreLayout",e),null}}function Hs(e,t){let n=Array.from(H.value.values());if(n.length===0)return;let{POSITIVE_INFINITY:o,POSITIVE_INFINITY:i,NEGATIVE_INFINITY:s,NEGATIVE_INFINITY:a}=Number;for(let g of n)o=Math.min(o,g.position.x),i=Math.min(i,g.position.y),s=Math.max(s,g.position.x+g.size.width),a=Math.max(a,g.position.y+g.size.height);let l=qa(),c=Math.max(80,e-l.left-l.right),u=Math.max(80,t-l.top-l.bottom),d=Math.max(1,s-o),p=Math.max(1,a-i),f=Math.min(1,Math.min(c/d,u/p)),m=(o+s)/2,h=(i+a)/2;_r({x:l.left+c/2-m*f,y:l.top+u/2-h*f,scale:f})}function $t(e,t={}){let n=H.value.get(e);if(!n)return;let o=Ee.value,i=Jt(),s=qa(),a=Math.max(80,i.width-s.left-s.right),l=Math.max(80,i.height-s.top-s.bottom),c=Math.min(o.scale,a/n.size.width,l/n.size.height),u=n.position.x+n.size.width/2,d=n.position.y+n.size.height/2;_r({x:s.left+a/2-u*c,y:s.top+l/2-d*c,scale:c},300,t),Sr(e)}function Qk(e=1){let t=Array.from(H.value.keys());if(t.length===0)return;let o=((gt.value?t.indexOf(gt.value):-1)+e+t.length)%t.length,i=t[o];Sr(i),$t(i)}function eS(e){let t=gt.value;if(!t)return;let n=H.value.get(t);if(!n)return;let o=Dk(t,et.value);if(o.size===0)return;let i=n.position.x+n.size.width/2,s=n.position.y+n.size.height/2,a=null,l=-1/0;for(let c of o){let u=H.value.get(c);if(!u)continue;let d=u.position.x+u.size.width/2,p=u.position.y+u.size.height/2,f=d-i,m=p-s,h=Math.sqrt(f*f+m*m);if(h<1)continue;let g;switch(e){case"up":g=-m;break;case"down":g=m;break;case"left":g=-f;break;case"right":g=f;break}if(g<=0)continue;let v=g/h-h*0.001;if(v>l)l=v,a=c}if(a)$t(a)}function xo(e){if(!H.value.get(e))return;if(zn!==null)clearTimeout(zn),zn=null;zo.value=null,Ui=void 0,Sr(e),Bt.value=e}function im(e){if(zn!==null)clearTimeout(zn),zn=null;if(Bt.value===e)Bt.value=null;if(zo.value===e)zo.value=null;Ui=void 0}function Cr(){let e=Bt.value,t=e?H.value.get(e):void 0;if(e&&t&&Pw(t)){let n=e,o=Date.now();if(zo.value=n,Ui=t.data.appCheckpoint?.updatedAt,zn!==null)clearTimeout(zn);let i=()=>{let a=H.value.get(n)?.data.appCheckpoint?.updatedAt;if(a!==void 0&&a!==Ui){im(n);return}if(Date.now()-o>=UR){im(n);return}zn=setTimeout(i,Mk)};zn=setTimeout(i,Mk);return}if(zn!==null)clearTimeout(zn),zn=null;zo.value=null,Ui=void 0,Bt.value=null}function Iu(){let e=Af(Array.from(H.value.values()),Array.from(et.value.values()),"grid");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;Nn(()=>{for(let[t,n]of e.nodePositions.entries())un(t,{position:n});for(let[t,n]of e.groupBounds.entries())Cu(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),dn()}function Eu(){let e=Af(Array.from(H.value.values()),Array.from(et.value.values()),"graph");if(e.nodePositions.size===0&&e.groupBounds.size===0)return;Nn(()=>{for(let[t,n]of e.nodePositions.entries())un(t,{position:n});for(let[t,n]of e.groupBounds.entries())Cu(t,{position:{x:n.x,y:n.y},size:{width:n.width,height:n.height}},{skipGroupChildTranslation:!0})}),dn()}var Ln=ie(!1),Oo=ie(!1),Jo=ie("");function vm(){return Ln.value||Oo.value}function GR(){return typeof matchMedia==="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}function bm(e,t){let n=Jt(),o=Ew(e,[...H.value.values()],n.width,n.height),i={...Ee.value},s=GR()?0:(e.duration??1)*1000;gm((a)=>Aw(i,o,a,n.width,n.height,e.easing,e.pullback),s,t)}var tS=0;function nS(e){let t=++tS,n=!Ln.value;Ln.value=!0,Jo.value="";let o=()=>{if(t!==tS)return;try{bm(e)}catch(i){Jo.value=i instanceof Error?i.message:String(i)}};if(n)requestAnimationFrame(()=>requestAnimationFrame(o));else o()}async function Au(e){let t=await pe("step tour","/api/canvas/tour/go",{ok:!1,error:"Could not reach the canvas server."},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,present:!1})});if(!t.ok)Jo.value=t.error??"Could not change the tour stop."}async function fl(e=!1){Ln.value=!0,Jo.value="";let t=e?(await pe("read tour","/api/canvas/tour",{})).position:null;await Au({stop:typeof t==="number"?t:0})}function xm(){Ln.value=!1,Jo.value="",oo("exit tour","/api/canvas/tour/exit",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})}var KR=0.1,VR=4,oS=1,XR=5;function rS(e){return Math.min(VR,Math.max(KR,e))}function Ru({viewport:e,onViewportChange:t,onViewportCommit:n,onBackgroundContextMenu:o,onEdgeContextMenu:i,disabled:s=!1}){let a=D(null),l=D(!1),c=D({x:0,y:0}),u=D(null),d=D(0),p=D(null),f=oe((y)=>{if(p.current!==null)window.clearTimeout(p.current);p.current=window.setTimeout(()=>{p.current=null,n(y)},140)},[n]);function m(y){if(y.deltaMode!==0)return y.deltaX===0;return y.deltaX===0&&Number.isInteger(y.deltaY)&&Math.abs(y.deltaY)>=50}let h=oe((y)=>{if(s)return;y.preventDefault();let k=e.value;if(y.ctrlKey||y.metaKey||m(y)){let _=a.current?.getBoundingClientRect();if(!_)return;let I=y.clientX-_.left,w=y.clientY-_.top,P=-y.deltaY*0.002,L=rS(k.scale*(1+P)),N=L/k.scale,Y={x:I-N*(I-k.x),y:w-N*(w-k.y),scale:L};t(Y),f(Y)}else{let _={x:k.x-y.deltaX*oS,y:k.y-y.deltaY*oS,scale:k.scale};t(_),f(_)}},[s,e,t,f]),g=oe((y)=>{if(s)return;let k=a.current;if(!k)return;if(y.button===1||y.button===2)y.preventDefault();else if(Bs()){if(y.target!==k)return;y.preventDefault()}else return;u.current=y.button===2?{x:y.clientX,y:y.clientY,background:y.target===k,edgeId:y.target instanceof Element?y.target.getAttribute("data-edge-id"):null,dragged:!1}:null,l.current=!0,document.documentElement.classList.add("is-canvas-panning"),c.current={x:y.clientX,y:y.clientY},k.setPointerCapture(y.pointerId)},[s]),v=oe((y)=>{if(!l.current)return;if(s)return;let k=u.current;if(k&&!k.dragged){if(Math.hypot(y.clientX-k.x,y.clientY-k.y)<=XR)return;k.dragged=!0}let _=y.clientX-c.current.x,I=y.clientY-c.current.y;c.current={x:y.clientX,y:y.clientY};let w=e.value;t({x:w.x+_,y:w.y+I,scale:w.scale})},[s,e,t]),b=oe((y)=>{if(!l.current)return;y.preventDefault();let k=u.current;if(u.current=null,l.current=!1,document.documentElement.classList.remove("is-canvas-panning"),k&&!k.dragged){if(!s&&y.type==="pointerup"){if(k.edgeId)i?.(y,k.edgeId);else if(k.background){let _=a.current?.getBoundingClientRect();if(!_)return;let I=e.value;o?.(y,(y.clientX-_.left-I.x)/I.scale,(y.clientY-_.top-I.y)/I.scale)}}return}n(e.value)},[s,o,i,n,e]),x=oe((y)=>{if(s)return;if(y.touches.length!==2){d.current=0;return}y.preventDefault();let k=y.touches[0],_=y.touches[1],I=Math.hypot(_.clientX-k.clientX,_.clientY-k.clientY),w=(k.clientX+_.clientX)/2,P=(k.clientY+_.clientY)/2;if(d.current>0){let L=e.value,N=a.current?.getBoundingClientRect();if(!N)return;let Y=w-N.left,B=P-N.top,J=I/d.current,X=rS(L.scale*J),V=X/L.scale,ee={x:Y-V*(Y-L.x),y:B-V*(B-L.y),scale:X};t(ee),f(ee)}d.current=I},[s,e,t,f]),C=oe(()=>{if(p.current!==null)window.clearTimeout(p.current),p.current=null;n(e.value),d.current=0},[n,e]);return q(()=>{let y=a.current;if(!y)return;return y.addEventListener("wheel",h,{passive:!1}),y.addEventListener("pointerdown",g),y.addEventListener("pointermove",v),y.addEventListener("pointerup",b),y.addEventListener("pointercancel",b),y.addEventListener("lostpointercapture",b),y.addEventListener("touchmove",x,{passive:!1}),y.addEventListener("touchend",C),()=>{if(p.current!==null)window.clearTimeout(p.current);y.removeEventListener("wheel",h),y.removeEventListener("pointerdown",g),y.removeEventListener("pointermove",v),y.removeEventListener("pointerup",b),y.removeEventListener("pointercancel",b),y.removeEventListener("lostpointercapture",b),y.removeEventListener("touchmove",x),y.removeEventListener("touchend",C)}},[h,g,v,b,x,C]),q(()=>()=>{document.documentElement.classList.remove("is-canvas-panning")},[]),a}var JR=0;function r(e,t,n,o,i,s){t||(t={});var a,l,c=t;if("ref"in c)for(l in c={},t)l=="ref"?a=t[l]:c[l]=t[l];var u={type:e,props:c,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--JR,__i:-1,__u:0,__source:i,__self:s};if(typeof e=="function"&&(a=e.defaultProps))for(l in a)c[l]===void 0&&(c[l]=a[l]);return ct.vnode&&ct.vnode(u),u}function iS(){let e=Ln.value,t=cn.value,n=(i)=>{co(),Ee.value=i},o=Ru({viewport:Ee,onViewportChange:n,onViewportCommit:n});return q(()=>{let i=new URLSearchParams(location.search);return Ln.value=i.get("present")==="1",Oo.value=i.get("capture")==="1",window.pmxCapture={ready:()=>cn.value,area:Jt,camera:()=>({...Ee.value}),frame:async(s)=>(Oo.value=!0,co(),Ee.value=Wa.parse(s),await new Promise((a)=>requestAnimationFrame(()=>requestAnimationFrame(()=>a()))),{...Ee.value})},()=>{delete window.pmxCapture,Ln.value=!1,Oo.value=!1}},[]),q(()=>{if(t&&Ln.value&&!Oo.value)fl(!0)},[t]),q(()=>{if(!e)return;let i=(s)=>{if(s.stopImmediatePropagation(),s.target instanceof HTMLButtonElement&&["Enter"," "].includes(s.key))return;if(["Escape","ArrowRight","ArrowDown","ArrowLeft","ArrowUp"," "].includes(s.key))s.preventDefault();if(s.key==="Escape")xm();if(["ArrowRight","ArrowDown"," "].includes(s.key))Au({step:"next"});if(["ArrowLeft","ArrowUp"].includes(s.key))Au({step:"previous"})};return document.addEventListener("keydown",i,!0),()=>document.removeEventListener("keydown",i,!0)},[e]),e?r(be,{children:[!Oo.value&&r("div",{class:"presentation-navigation",ref:o,onPointerDown:(i)=>{if(i.button===1||i.button===2)co()},onContextMenu:(i)=>i.preventDefault(),children:r("button",{type:"button",class:"presentation-exit",onClick:xm,children:"Exit presentation"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Jo.value&&r("div",{class:"presentation-error",role:"alert",children:Jo.value},void 0,!1,void 0,this)]},void 0,!0,void 0,this):null}var YR={fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"};function nt({size:e=16,children:t,...n}){return r("svg",{width:e,height:e,viewBox:"0 0 16 16",style:{verticalAlign:"middle",flexShrink:0},...YR,...n,children:t},void 0,!1,void 0,this)}function Tt(e){return r(nt,{...e,children:r("path",{d:"m4 4 8 8M12 4l-8 8"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function aS(e){return r(nt,{...e,children:r("path",{d:"M8 2v12M2 8h12"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function lS(e){return r(nt,{...e,children:[r("circle",{cx:"8",cy:"8",r:"6"},void 0,!1,void 0,this),r("path",{d:"M8 5v6M5 8h6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oi(e){return r(nt,{...e,children:r("polyline",{points:"6 3 11 8 6 13"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ml(e){return r(nt,{...e,children:[r("circle",{cx:"3",cy:"8",r:"0.75"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"8",r:"0.75"},void 0,!1,void 0,this),r("circle",{cx:"13",cy:"8",r:"0.75"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ri(e){return r(nt,{...e,children:r("path",{d:"M9 2h5v5M14 2 7 9M6 3H2v11h11v-4"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function cS(e){return r(nt,{...e,children:r("path",{d:"M9 2h5v5M14 2l-5 5M7 14H2V9M2 14l5-5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function uS(e){return r(nt,{...e,children:r("path",{d:"M14 8H2m5-5-5 5 5 5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Pu(e){return r(nt,{...e,children:r("path",{d:"M13.5 6A5.5 5.5 0 1 0 13 11M14 2v4h-4"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function km(e){return r(nt,{...e,children:r("path",{d:"M6 2 2 6l4 4M2 6h7a4 4 0 0 1 0 8"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function dS(e){return r(nt,{...e,children:r("path",{d:"M8 10V2M4.5 5.5 8 2l3.5 3.5M2 10v3.5h12V10"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function js(e){return r(nt,{...e,children:r("polyline",{points:"3 6 8 11 13 6"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function Nu(e){return r(nt,{...e,children:[r("polyline",{points:"1 5 1 1 5 1"},void 0,!1,void 0,this),r("polyline",{points:"11 1 15 1 15 5"},void 0,!1,void 0,this),r("polyline",{points:"15 11 15 15 11 15"},void 0,!1,void 0,this),r("polyline",{points:"5 15 1 15 1 11"},void 0,!1,void 0,this),r("rect",{x:"4",y:"4",width:"8",height:"8",rx:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function pS(e){return r(nt,{...e,children:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),r("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this),r("line",{x1:"7",y1:"5",x2:"7",y2:"9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function fS(e){return r(nt,{...e,children:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this),r("line",{x1:"5",y1:"7",x2:"9",y2:"7"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Tr(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"9.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"4",x2:"9.5",y2:"4"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"12",x2:"9.5",y2:"12"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"6.5",x2:"4",y2:"9.5"},void 0,!1,void 0,this),r("line",{x1:"12",y1:"6.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function mS(e){return r(nt,{...e,children:[r("rect",{x:"1",y:"2",width:"14",height:"12",rx:"1.5"},void 0,!1,void 0,this),r("rect",{x:"8",y:"7",width:"6",height:"6",rx:"1",fill:"currentColor","fill-opacity":"0.2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function hS(e){return r(nt,{...e,children:r("path",{d:"M13 9.5A5.5 5.5 0 1 1 6.5 3 4.5 4.5 0 0 0 13 9.5Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function gS(e){return r(nt,{...e,children:[r("path",{d:"M3 13l2.8-.7L13 5.1 10.9 3 3.7 10.2 3 13Z"},void 0,!1,void 0,this),r("path",{d:"M9.8 4.1l2.1 2.1"},void 0,!1,void 0,this),r("path",{d:"M2.5 14h11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yS(e){return r(nt,{...e,children:[r("path",{d:"M3 10.5 8.5 5a2 2 0 0 1 2.8 0l1.7 1.7a2 2 0 0 1 0 2.8L8.5 14H5.8L3 11.2Z"},void 0,!1,void 0,this),r("path",{d:"M7.5 6 12 10.5"},void 0,!1,void 0,this),r("path",{d:"M8.5 14H14"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function vS(e){return r(nt,{...e,children:[r("path",{d:"M3 4h10"},void 0,!1,void 0,this),r("path",{d:"M8 4v8"},void 0,!1,void 0,this),r("path",{d:"M6 12h4"},void 0,!1,void 0,this),r("path",{d:"M4.5 4 4 6"},void 0,!1,void 0,this),r("path",{d:"M11.5 4 12 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Mu(e){return r(nt,{...e,children:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("line",{x1:"10.5",y1:"10.5",x2:"14.5",y2:"14.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Zs(e){return r(nt,{...e,children:r("path",{d:"M2 13 L2 4 A2 2 0 0 1 4 2 L12 2 A2 2 0 0 1 14 4 L14 9 A2 2 0 0 1 12 11 L5 11 Z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function uo(e){return r(nt,{...e,children:r("path",{d:"M6 2.67h4l-.53 3.66 1.86 2H4.67l1.86-2zM8 8.33v5"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function zu({size:e=22,class:t}){return r("svg",{width:e,height:e,viewBox:"0 0 64 64",xmlns:"http://www.w3.org/2000/svg",class:t,"aria-hidden":"true",children:[r("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.35"},void 0,!1,void 0,this),r("rect",{x:"16",y:"16",width:"32",height:"32",rx:"5",fill:"none",stroke:"currentColor","stroke-width":"2.2",opacity:"0.6"},void 0,!1,void 0,this),r("rect",{x:"24",y:"24",width:"16",height:"16",rx:"3",fill:"none",stroke:"currentColor","stroke-width":"2.2"},void 0,!1,void 0,this),r("rect",{x:"29",y:"29",width:"6",height:"6",rx:"1",fill:"currentColor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function bS({size:e=15}){return r("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:r("path",{d:"M3 2l10 5.5-4.2 1.3L7.5 13z"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function xS({size:e=15}){return r("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:r("path",{d:"M5 7.5V3.8a1 1 0 0 1 2 0V7m0-3.9a1 1 0 0 1 2 0V7m0-2.7a1 1 0 0 1 2 0V7.4m0-.9a1 1 0 0 1 2 0v3.2A4.3 4.3 0 0 1 8.7 14H8a4.3 4.3 0 0 1-3.6-2L2.7 9.3a1 1 0 0 1 1.6-1.2L5 9.2"},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ni(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"6",x2:"10",y2:"6"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"8.5",x2:"8",y2:"8.5"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"11",x2:"11",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function QR(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M4 13.5 L5.5 11.5 L8 11.5"},void 0,!1,void 0,this),r("polyline",{points:"5 6 7 8 5 10"},void 0,!1,void 0,this),r("line",{x1:"8",y1:"10",x2:"11",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function eP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"9",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M12 13.5 L10.5 11.5 L8 11.5"},void 0,!1,void 0,this),r("circle",{cx:"5",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"11",cy:"7",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sS(e){return r(nt,{...e,children:[r("path",{d:"M3 1.5h6l3.5 3.5v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V2.5a1 1 0 0 1 1-1z"},void 0,!1,void 0,this),r("polyline",{points:"9 1.5 9 5 12.5 5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"8.5",x2:"10.5",y2:"8.5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"11",x2:"9",y2:"11"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function tP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("circle",{cx:"5.5",cy:"6.5",r:"1.2"},void 0,!1,void 0,this),r("path",{d:"M1.8 12 L6 8.5 L9 11 L11.5 9 L14.2 12"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Us(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"1.5",y1:"5.5",x2:"14.5",y2:"5.5"},void 0,!1,void 0,this),r("circle",{cx:"3.3",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"5",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"6.7",cy:"4",r:"0.5",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"8",x2:"12",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"4",y1:"10",x2:"10",y2:"10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nP(e){return r(nt,{...e,children:[r("rect",{x:"2",y:"4",width:"12",height:"10",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"2",y1:"6.5",x2:"14",y2:"6.5"},void 0,!1,void 0,this),r("path",{d:"M11 1.5 L11 4"},void 0,!1,void 0,this),r("circle",{cx:"11",cy:"4",r:"1.6",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Sm(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"1.5","stroke-dasharray":"2 1.5"},void 0,!1,void 0,this),r("rect",{x:"4",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),r("rect",{x:"8.5",y:"4",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this),r("rect",{x:"6.25",y:"8.5",width:"3.5",height:"3.5",rx:"0.6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function rP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M3.5 10.5 L6 6.5 L8.5 9.5 L12.5 5"},void 0,!1,void 0,this),r("circle",{cx:"12.5",cy:"5",r:"0.9",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function iP(e){return r(nt,{...e,children:[r("rect",{x:"2",y:"2",width:"12",height:"12",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"5.5",x2:"11.5",y2:"5.5"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"8",x2:"11.5",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"4.5",y1:"10.5",x2:"8",y2:"10.5"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"2",x2:"6.5",y2:"14",opacity:"0.45"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"1.5",width:"13",height:"13",rx:"2"},void 0,!1,void 0,this),r("path",{d:"M4 11 L4 6 L6 8.5 L8 6 L8 11"},void 0,!1,void 0,this),r("path",{d:"M10 11 L10 6 L12.5 11 L12.5 6"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function aP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("polyline",{points:"10 5 13 5 13 8"},void 0,!1,void 0,this),r("line",{x1:"13",y1:"5",x2:"8",y2:"10"},void 0,!1,void 0,this),r("path",{d:"M6 6 L3.5 6 L3.5 11.5 L10 11.5 L10 9"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function lP(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("path",{d:"M7 5.5 C 5.5 5.5 5.5 8 4 8 C 5.5 8 5.5 10.5 7 10.5"},void 0,!1,void 0,this),r("path",{d:"M9 5.5 C 10.5 5.5 10.5 8 12 8 C 10.5 8 10.5 10.5 9 10.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function wm(e){return r(nt,{...e,children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("line",{x1:"5.2",y1:"6",x2:"8",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"8",y1:"8",x2:"10.8",y2:"6"},void 0,!1,void 0,this),r("line",{x1:"8",y1:"8",x2:"8",y2:"11"},void 0,!1,void 0,this),r("circle",{cx:"5.2",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"10.8",cy:"6",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"8",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("circle",{cx:"8",cy:"11",r:"1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Do(e){switch(e){case"markdown":return ni;case"prompt":return QR;case"response":return eP;case"file":return sS;case"diff":return sS;case"mermaid":return wm;case"image":return tP;case"webpage":return Us;case"context":return nP;case"group":return Sm;case"status":return oP;case"trace":return rP;case"ledger":return iP;case"mcp-app":return sP;case"ext-app":return aP;case"json-render":return lP;case"graph":return wm;case"board":return wm;case"html":return Us;default:return ni}}function cP(e){return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function uP(){nu()}function wS(){let e=Va.value;if(e.length===0)return null;let t=qr.value,n=_s.value;if(!t)return r("button",{type:"button",class:"attention-history-tab",onClick:uP,"aria-label":n>0?`Recent updates — ${n} new`:"Recent updates",children:[r("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[r("rect",{x:"1.5",y:"2.5",width:"13",height:"11",rx:"1.5"},void 0,!1,void 0,this),r("circle",{cx:"4.5",cy:"8",r:"1.1",fill:"currentColor",stroke:"none"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"6.5",x2:"12.5",y2:"6.5"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"8",x2:"11",y2:"8"},void 0,!1,void 0,this),r("line",{x1:"6.5",y1:"9.5",x2:"12",y2:"9.5"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"attention-history-tab-label",children:"Updates"},void 0,!1,void 0,this),n>0&&r("span",{class:"attention-history-tab-badge","aria-hidden":"true",children:n>9?"9+":n},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("aside",{class:"attention-history","aria-label":"Recent semantic changes",children:[r("div",{class:"attention-history-header",children:[r("div",{class:"attention-history-header-text",children:[r("span",{class:"attention-history-title",children:"Recent Updates"},void 0,!1,void 0,this),r("span",{class:"attention-history-subtitle",children:"Focus and meaning shifts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"attention-history-close",onClick:Fw,"aria-label":"Collapse changes panel",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"attention-history-list",children:e.map((o)=>r("article",{class:`attention-history-entry attention-tone-${o.tone}`,children:[r("div",{class:"attention-history-meta",children:[r("span",{class:"attention-history-kind",children:o.title},void 0,!1,void 0,this),r("time",{class:"attention-history-time",dateTime:new Date(o.createdAt).toISOString(),children:cP(o.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{class:"attention-history-detail",children:o.detail},void 0,!1,void 0,this)]},o.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kS(){let e=eu.value;if(!e)return null;return r("button",{type:"button",class:`attention-toast attention-tone-${e.tone}`,onClick:nu,"aria-label":`${e.title}${e.detail?`: ${e.detail}`:""} — open change history`,children:[r("span",{class:"attention-toast-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"attention-toast-copy",children:[r("span",{class:"attention-toast-title",children:e.title},void 0,!1,void 0,this),e.detail&&r("span",{class:"attention-toast-detail",children:e.detail},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var gl=ie(null),SS=0;function On(e,t,n={}){return new Promise((o)=>{gl.value?.resolve(null),SS+=1,gl.value={seq:SS,title:e,placeholder:t,initial:n.initial??"",allowEmpty:n.allowEmpty??!1,confirm:n.confirm??"Add",resolve:o}})}function hl(e){let t=gl.value;gl.value=null,t?.resolve(e)}function _S(){let e=gl.value,t=D(null);if(q(()=>{if(!e)return;let o=(i)=>{if(i.key!=="Escape")return;i.preventDefault(),i.stopPropagation(),hl(null)};return window.addEventListener("keydown",o,{capture:!0}),()=>window.removeEventListener("keydown",o,{capture:!0})},[e]),!e)return null;let n=()=>{let o=t.current?.value.trim()??"";hl(o?o:e.allowEmpty?"":null)};return r("div",{class:"text-prompt-backdrop",onPointerDown:()=>hl(null),children:r("div",{class:"text-prompt",role:"dialog","aria-label":e.title,"data-testid":"text-prompt",onPointerDown:(o)=>o.stopPropagation(),children:[r("div",{class:"text-prompt-title",children:e.title},void 0,!1,void 0,this),r("input",{ref:(o)=>{if(t.current=o,!o)return;if(o.focus(),e.initial)o.select()},class:"text-prompt-input",type:"text",defaultValue:e.initial,placeholder:e.placeholder,onKeyDown:(o)=>{if(o.key==="Enter")o.preventDefault(),o.stopPropagation(),n();else if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),hl(null)}},e.seq,!1,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",onClick:()=>hl(null),children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"button",class:"text-prompt-confirm",onClick:n,children:e.confirm},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function Ws({children:e}){let t=Ke(()=>document.createElement("div"),[]);return Me(()=>(document.body.appendChild(t),()=>{Ra(null,t),t.remove()}),[t]),Me(()=>Ra(e,t),[e,t]),null}function _e({label:e,shortcut:t,body:n,align:o="center",side:i="down",tapToOpen:s=!1,fitWithin:a,children:l}){let[c,u]=E(null),d=(f)=>{if(!a)return;let m=f.currentTarget,h=m.closest(a)?.getBoundingClientRect(),g=m.querySelector(".toolbar-tooltip")?.getBoundingClientRect();if(!h||!g)return;let v=m.getBoundingClientRect(),b=v.right-g.width>=h.left,x=v.left+g.width<=h.right;u(b||!x?"end":"start")};return r("span",{class:`toolbar-tooltip-anchor toolbar-tooltip-anchor-${c??o}${i==="up"?" toolbar-tooltip-anchor-up":""}${s?" toolbar-tooltip-anchor-tap":""}`,tabIndex:s?-1:void 0,onPointerEnter:a?d:void 0,onFocusIn:a?d:void 0,children:[l,r("span",{class:"toolbar-tooltip",role:"tooltip",children:[r("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),n&&r("span",{class:"toolbar-tooltip-body",children:n},void 0,!1,void 0,this),t&&r("span",{class:"toolbar-tooltip-meta",children:r("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)}async function ii(e,t,n,o){if((await vu({type:t,sourceNodeId:e.id,sourceSurface:"native-node",...n?{payload:n}:{}})).ok)hn("context",o,"",[e.id])}var Gi={padding:"3px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer",flexShrink:0};function dP(e){let t=e.title||e.label||e.key||"Context",n=e.summary?.trim()||"Available in startup context.",o=e.pathDisplay||e.path||"",i=e.category==="profile"?"Operator":e.category==="planning"||e.category==="memory"?"Product":e.category?e.category.charAt(0).toUpperCase()+e.category.slice(1):void 0,s=e.sourceKind==="global"?"Global":"Workspace",a=e.state==="missing"?"Missing":e.state==="stale"?"Stale":e.state==="invalid"?"Invalid":"Loaded";return{title:t,summary:n,pathDisplay:o,category:i,sourceKind:s,status:a,required:e.required===!0}}function Bo(e){return typeof e==="string"?e.trim():""}function pP(e){return e.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim()}function fP(e){let t=Bo(e.title),n=Bo(e.content),o=pP(Bo(e.rendered)),i=n||o,s=Bo(e.path);if(!t&&!i&&!s)return null;return{title:t||"Context",summary:i,path:s}}function mP(e){let t=Bo(e.data.title)||e.id,n=Bo(e.data.content)||Bo(e.data.excerpt)||Bo(e.data.description)||Bo(e.data.pageTitle)||"",o=Bo(e.data.path)||Bo(e.data.url);return{id:e.id,title:t,summary:n,kind:an[e.type]??e.type,path:o}}function CS(e){if(e===null||!Number.isFinite(e)||e<0)return"0";if(e>=1e6)return`${(e/1e6).toFixed(1)}m`;if(e>=1000)return`${(e/1000).toFixed(1)}k`;return`${Math.round(e)}`}function hP(e){if(e>=0.95)return"var(--c-danger)";if(e>=0.85)return"var(--c-warn)";if(e>=0.7)return"var(--c-warn)";return"var(--c-accent)"}function $u({node:e,expanded:t=!1,pinnedNodes:n=[]}){let o=e.data.cards??[],i=e.data.auxTabs??[],s=n.map(mP),a=s.length>0,l=typeof e.data.currentTokens==="number"?e.data.currentTokens:null,c=typeof e.data.tokenLimit==="number"?e.data.tokenLimit:null,u=typeof e.data.utilization==="number"?e.data.utilization:null,d=typeof e.data.messagesLength==="number"?e.data.messagesLength:null,p=u!==null?Math.max(0,Math.min(100,Math.round(u*100))):null,f=hP(u??0),m=!a&&o.length===0&&i.length===0?fP(e.data):null,h=async(g)=>{let v=typeof g.path==="string"?g.path.trim():"";if(!v)return;await mu(v)};return r("div",{style:{display:"flex",flexDirection:"column",gap:t?"10px":"6px",fontSize:t?"14px":"12px",maxWidth:t?"760px":void 0,margin:t?"0 auto":void 0,width:t?"100%":void 0,padding:t?"8px 0":void 0},children:[r("div",{style:{display:"flex",justifyContent:"flex-end"},children:r(_e,{label:"Point the agent at this node",body:"Sets it as the agent's current AX focus, so the agent pulls it into context to work on next — a one-click alternative to pinning.",align:"end",fitWithin:".node-content",children:r("button",{type:"button",class:"ax-node-action",style:Gi,onClick:(g)=>{g.stopPropagation(),ii(e,"ax.focus.set",void 0,"Focus set")},children:"Set focus"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),c!==null&&c>0&&r("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:"Token Usage"},void 0,!1,void 0,this),r("div",{style:{height:"6px",background:"var(--c-surface-hover)",borderRadius:"3px",overflow:"hidden",marginBottom:"4px"},children:r("div",{style:{height:"100%",width:`${Math.min(100,(u??0)*100)}%`,background:f,borderRadius:"3px",transition:"width 0.3s ease"}},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{style:{fontSize:"11px",color:"var(--c-muted)"},children:[p,"% — ",CS(l)," / ",CS(c)," tokens",d!==null&&r(be,{children:[" · ",d," messages"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&r("div",{children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Pinned Context (",s.length,")"]},void 0,!0,void 0,this),s.map((g)=>r("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[r("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:g.title},void 0,!1,void 0,this),g.summary&&r("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px",whiteSpace:"pre-wrap"},children:g.summary},void 0,!1,void 0,this),r("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:g.kind},void 0,!1,void 0,this)},void 0,!1,void 0,this),g.path&&r("div",{style:{marginTop:"6px"},children:[r("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:g.path},void 0,!1,void 0,this),g.path.startsWith("/")&&r("button",{type:"button",onClick:()=>void mu(g.path),style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},g.id,!0,void 0,this))]},void 0,!0,void 0,this),!a&&o.length>0&&r("div",{children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px"},children:["Context (",o.length,")"]},void 0,!0,void 0,this),o.map((g)=>{let v=dP(g);return r("div",{style:{padding:"6px 8px",background:"var(--c-surface-subtle)",borderRadius:"6px",marginBottom:"4px",borderLeft:"2px solid var(--c-accent)"},children:[r("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"2px"},children:v.title},void 0,!1,void 0,this),r("div",{style:{color:"var(--c-muted)",fontSize:"10px",lineHeight:1.45,marginBottom:"4px"},children:v.summary},void 0,!1,void 0,this),v.pathDisplay&&r("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all"},children:v.pathDisplay},void 0,!1,void 0,this),r("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginTop:"4px"},children:[r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"color-mix(in srgb, var(--c-accent) 10%, transparent)",color:"var(--c-accent)",borderRadius:"3px",display:"inline-block"},children:v.status},void 0,!1,void 0,this),v.category&&r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:v.category},void 0,!1,void 0,this),r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"var(--c-surface-hover)",color:"var(--c-text-soft)",borderRadius:"3px",display:"inline-block"},children:v.sourceKind},void 0,!1,void 0,this),v.required&&r("span",{style:{fontSize:"9px",padding:"1px 4px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)",borderRadius:"3px",display:"inline-block"},children:"Required"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),g.path&&r("div",{style:{marginTop:"6px"},children:r("button",{type:"button",onClick:()=>void h(g),style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},g.key??v.pathDisplay??v.title,!0,void 0,this)})]},void 0,!0,void 0,this),!a&&i.length>0&&r("div",{children:[r("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginBottom:"6px",marginTop:o.length>0?"8px":0},children:["References (",i.length,")"]},void 0,!0,void 0,this),i.map((g)=>r("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",style:{display:"block",padding:"4px 8px",color:"var(--c-accent)",fontSize:"11px",textDecoration:"none",borderRadius:"4px",marginBottom:"2px",wordBreak:"break-all"},children:[g.url,g.reason&&r("span",{style:{color:"var(--c-dim)",fontSize:"10px",marginLeft:"6px"},children:["(",g.reason,")"]},void 0,!0,void 0,this)]},g.id,!0,void 0,this))]},void 0,!0,void 0,this),m&&r("div",{style:{padding:"8px 10px",background:"var(--c-surface-subtle)",borderRadius:"6px",borderLeft:"2px solid var(--c-accent)"},children:[r("div",{style:{fontWeight:600,color:"var(--c-text)",marginBottom:"4px"},children:m.title},void 0,!1,void 0,this),m.summary&&r("div",{style:{color:"var(--c-text-soft)",fontSize:"11px",lineHeight:1.5,whiteSpace:"pre-wrap"},children:m.summary},void 0,!1,void 0,this),m.path&&r("div",{style:{marginTop:"6px"},children:[r("div",{style:{color:"var(--c-dim)",fontSize:"10px",wordBreak:"break-all",marginBottom:"6px"},children:m.path},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>void mu(m.path),style:{padding:"4px 8px",fontSize:"10px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--c-accent) 25%, transparent)",borderRadius:"4px",color:"var(--c-text-soft)",cursor:"pointer"},children:"Open in canvas"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!a&&!m&&o.length===0&&i.length===0&&r("div",{style:{color:"var(--c-dim)",fontStyle:"italic"},children:"No context loaded"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function TS(e){return e.replace(/^[ab]\//,"")}function gP(e,t){if(t&&t!=="/dev/null")return TS(t);if(e&&e!=="/dev/null")return TS(e);return null}function yP(e){if(!e.trim())return[];let t=e.split(`
89
+ `);if(t.length>0&&t[t.length-1]==="")t.pop();let n=[],o=null,i=!1,s=(a)=>{let l={path:a,lines:[]};return i=!1,n.push(l),l};for(let a=0;a<t.length;a++){let l=t[a]??"",c=l.match(/^diff --git a\/(.+?) b\/(.+)$/);if(c){o=s(c[2]??null);continue}let u=t[a+1]??"";if(l.startsWith("--- ")&&u.startsWith("+++ ")){let p=gP(l.slice(4).trim(),u.slice(4).trim());if(o&&!i){if(!o.path)o.path=p}else o=s(p);a++;continue}if(!o)o=s(null);let d=o;if(l.startsWith("@@"))i=!0,d.lines.push({kind:"hunk",text:l});else if(l.startsWith("+"))d.lines.push({kind:"add",text:l});else if(l.startsWith("-"))d.lines.push({kind:"remove",text:l});else d.lines.push({kind:"context",text:l})}return n}function Lu({node:e}){let t=typeof e.data.content==="string"?e.data.content:"",n=Ke(()=>yP(t),[t]);if(n.length===0)return r("div",{class:"diff-node diff-node-empty",children:"Empty diff"},void 0,!1,void 0,this);return r("div",{class:"diff-node",children:n.map((o,i)=>r("div",{class:"diff-file",children:[o.path&&r("div",{class:"diff-file-header",children:o.path},void 0,!1,void 0,this),r("pre",{class:"diff-lines",children:o.lines.map((s,a)=>r("div",{class:s.kind==="hunk"?"diff-hunk":`diff-line-${s.kind}`,children:s.text||" "},a,!1,void 0,this))},void 0,!1,void 0,this)]},`${o.path??"anonymous"}-${i}`,!0,void 0,this))},void 0,!1,void 0,this)}function IS(e){let t=e.toLowerCase();if(t.endsWith(".csv"))return",";if(t.endsWith(".tsv"))return"\t";return null}function ES(e,t){let n=[],o=[],i="",s=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a=!0,s){if(u==='"')if(e[c+1]==='"')i+='"',c++;else s=!1;else if(u==="\r"&&e[c+1]===`
90
90
  `)i+=`
91
91
  `,c++;else i+=u;continue}if(u==='"'&&i==="")s=!0;else if(u===t)o.push(i),i="";else if(u===`
92
92
  `||u==="\r"){if(u==="\r"&&e[c+1]===`
93
- `)c++;o.push(i),i="",n.push(o),o=[],a=!1}else i+=u}if(a)o.push(i),n.push(o);let l=n.shift()??[];return{header:l,rows:n.map((c)=>Array.from({length:l.length},(u,d)=>c[d]??""))}}var RS="pmx-canvas-iframe-probe";var vP="/api/canvas/iframe-probe",bP=3000,_n=ie(null);function xP(){let e=new URLSearchParams(window.location.search).get("iframe-mode");return e==="srcdoc"||e==="src"?e:null}function PS(e=bP){return new Promise((t)=>{let n=document.createElement("iframe");n.setAttribute("data-pmx-iframe-probe",""),n.style.cssText="position:fixed;width:1px;height:1px;left:-9999px;border:none",n.setAttribute("sandbox","allow-scripts");let o=(a)=>{window.clearTimeout(s),window.removeEventListener("message",i),n.remove(),t(a)},i=(a)=>{if(a.source!==n.contentWindow)return;if(a.data?.source!==RS)return;o(!0)},s=window.setTimeout(()=>o(!1),e);window.addEventListener("message",i),n.addEventListener("error",()=>o(!1)),n.src=vP,(document.body??document.documentElement).appendChild(n)})}var Lu=null;function wP(){try{return window.self!==window.top}catch{return!0}}function kP(){return window.__PMX_AMP_ORB===!0}function NS(e={}){if(tt())return _n.value="srcdoc",Promise.resolve("srcdoc");if(_n.value)return Promise.resolve(_n.value);if(Lu)return Lu;let t=xP();if(t)return _n.value=t,Promise.resolve(t);if(!(e.embedded??wP()))return _n.value="src",PS(e.probeTimeoutMs).then((n)=>{if(!n&&_n.value==="src")_n.value="srcdoc"}),Promise.resolve("src");if(e.ampOrb??kP())return _n.value="srcdoc",Promise.resolve("srcdoc");return Lu=PS(e.probeTimeoutMs).then((n)=>{let o=n?"src":"srcdoc";return _n.value=o,o}),Lu}function Ws(e){let t=tt()&&e.startsWith("/"),[n,o]=E(null);return q(()=>{if(!t)return;let i=!1;return Gt(e).then(async(s)=>{if(!s.ok)throw Error(`Asset read failed: ${s.status}`);let a=new FileReader;a.onload=()=>{if(!i&&typeof a.result==="string")o({path:e,url:a.result})},a.readAsDataURL(await s.blob())}).catch((s)=>console.error("[workbench-asset]",s)),()=>{i=!0}},[e,t]),t?n?.path===e?n.url:void 0:e}function MS({node:e,expanded:t=!1}){let n=String(e.data.attachmentId),o=Ws(`/api/canvas/attachments/${encodeURIComponent(n)}/bytes`),i=se.value,[s,a]=E(null),[l,c]=E(t),[u,d]=E(!1);q(()=>{let m=!0,h=async()=>{let v=await de("readImports",`/api/canvas/imports?boardId=${encodeURIComponent(i??"")}`,null);if(m)a(v?.imports?.find((b)=>b.attachmentId===n)??null)};h();let g=window.setInterval(()=>void h(),2000);return()=>{m=!1,window.clearInterval(g)}},[n,i]),q(()=>{if(!l)return;let m=(h)=>{if(h.key==="Escape")h.stopPropagation(),c(!1)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[l]);let p=async(m)=>{if(!s)return;d(!0);let h=await de(`import.${m}`,`/api/canvas/imports/${s.id}/${m}`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({consent:!0})});if(d(!1),h?.import){if(a(h.import),c(!1),t&&m==="commit")Cr()}},f=s&&["attached","cancelled","unavailable"].includes(s.status);return r("div",{class:"attachment-node",onPointerDown:(m)=>m.stopPropagation(),children:[r("div",{class:"attachment-status",children:s?.status==="requested"?"Waiting for agent":s?.status==="drafted"?"Ready for review":s?.status==="committed"?"Markdown added":"Original attached"},void 0,!1,void 0,this),r("a",{href:o,download:String(e.data.title??"attachment"),target:"_blank",rel:"noopener noreferrer",children:["Download original · ",Math.ceil(Number(e.data.size??0)/1024)," KB"]},void 0,!0,void 0,this),s?.reason&&r("p",{children:s.reason},void 0,!1,void 0,this),f&&r(be,{children:[r("p",{id:`import-consent-${e.id}`,children:"Asking the agent to import allows it to process this file with its tools and model provider."},void 0,!1,void 0,this),r("button",{type:"button",class:"attachment-button is-primary","aria-describedby":`import-consent-${e.id}`,disabled:u,onClick:()=>void p("request"),children:"Ask agent to import"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s?.status==="requested"&&r("p",{children:"No automatic extraction. Ask your connected agent to check its pending steering or use canvas_import list."},void 0,!1,void 0,this),s?.status==="drafted"&&!l&&r("button",{type:"button",class:"attachment-button is-primary",onClick:()=>t?c(!0):xo(e.id),children:["Review Markdown · ",s.sections.length," ",s.sections.length===1?"card":"cards"]},void 0,!0,void 0,this),s&&["requested","drafted"].includes(s.status)&&r("button",{type:"button",class:"attachment-button",disabled:u,onClick:()=>void p("cancel"),children:"Cancel import"},void 0,!1,void 0,this),l&&s?.status==="drafted"&&r("div",{class:"attachment-review",role:"dialog","aria-label":"Review imported Markdown",children:[r("h3",{children:"Review imported Markdown"},void 0,!1,void 0,this),r("p",{children:["Source material, not instructions or verified knowledge. ",s.agentDescription]},void 0,!0,void 0,this),s.warnings.length>0&&r("ul",{children:s.warnings.map((m)=>r("li",{children:m},m,!1,void 0,this))},void 0,!1,void 0,this),s.sections.map((m,h)=>r("section",{children:[r("h4",{children:m.title},void 0,!1,void 0,this),r("p",{children:m.reference||"Source location not supplied"},void 0,!1,void 0,this),r("pre",{children:m.markdown},void 0,!1,void 0,this)]},h,!0,void 0,this)),r("div",{class:"attachment-review-actions",children:[r("button",{type:"button",class:"attachment-button",onClick:()=>c(!1),children:"Close review"},void 0,!1,void 0,this),r("button",{type:"button",class:"attachment-button is-primary",disabled:u||i!==s.boardId,onClick:()=>void p("commit"),children:"Add to board"},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 SP(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",py:"Python",rs:"Rust",go:"Go",rb:"Ruby",java:"Java",kt:"Kotlin",swift:"Swift",c:"C",cpp:"C++",h:"C/C++",css:"CSS",html:"HTML",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",toml:"TOML",sql:"SQL",sh:"Shell",bash:"Shell",xml:"XML",graphql:"GraphQL",proto:"Protobuf"}[t]??(t.toUpperCase()||"Text")}var wm=500;function km(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.round(e)} B`;let t=["KB","MB","GB","TB"],n=e/1024,o=0;while(n>=1024&&o<t.length-1)n/=1024,o++;return`${n<10?n.toFixed(1):Math.round(n)} ${t[o]}`}function Ou({node:e,expanded:t=!1}){if(typeof e.data.attachmentId==="string")return r(MS,{node:e,expanded:t},void 0,!1,void 0,this);return r(_P,{node:e,expanded:t},void 0,!1,void 0,this)}function _P({node:e,expanded:t=!1}){let n=e.data.path||e.data.content||"",o=e.data.title||n.split("/").pop()||"File",i=e.data.fileContent,s=e.data.updatedAt,a=e.data.lineCount,l=e.data.byteSize,c=e.data.binary===!0,u=e.data.truncated===!0,p=e.data.mimeType==="application/pdf"||n.toLowerCase().endsWith(".pdf"),f=c||p,[m,h]=E(i??""),[g,v]=E(!i&&!!n&&!f),[b,x]=E(null),[C,y]=E(0);q(()=>{if(!n)return;if(f){v(!1);return}if(i!==void 0){h(i),v(!1);return}let X=!1;return v(!0),x(null),nl(n).then(({content:V})=>{if(X)return;if(!V&&V!==""){x("File not found"),v(!1);return}h(V),v(!1);let ee=V.split(`
94
- `).length;Xe(e.id,{fileContent:V,lineCount:ee}),ln(e.id,{data:{fileContent:V,lineCount:ee}})}).catch(()=>{if(!X)x("Failed to load file"),v(!1)}),()=>{X=!0}},[n,i,f]),q(()=>{if(i!==void 0&&i!==m)h(i)},[i]);let k=oe(()=>{if(!n)return;if(f){y((X)=>X+1);return}v(!0),x(null),Xe(e.id,{fileContent:void 0}),ln(e.id,{data:{fileContent:void 0}}),nl(n).then(({content:X})=>{h(X),v(!1);let V=X.split(`
93
+ `)c++;o.push(i),i="",n.push(o),o=[],a=!1}else i+=u}if(a)o.push(i),n.push(o);let l=n.shift()??[];return{header:l,rows:n.map((c)=>Array.from({length:l.length},(u,d)=>c[d]??""))}}var AS="pmx-canvas-iframe-probe";var vP="/api/canvas/iframe-probe",bP=3000,_n=ie(null);function xP(){let e=new URLSearchParams(window.location.search).get("iframe-mode");return e==="srcdoc"||e==="src"?e:null}function RS(e=bP){return new Promise((t)=>{let n=document.createElement("iframe");n.setAttribute("data-pmx-iframe-probe",""),n.style.cssText="position:fixed;width:1px;height:1px;left:-9999px;border:none",n.setAttribute("sandbox","allow-scripts");let o=(a)=>{window.clearTimeout(s),window.removeEventListener("message",i),n.remove(),t(a)},i=(a)=>{if(a.source!==n.contentWindow)return;if(a.data?.source!==AS)return;o(!0)},s=window.setTimeout(()=>o(!1),e);window.addEventListener("message",i),n.addEventListener("error",()=>o(!1)),n.src=vP,(document.body??document.documentElement).appendChild(n)})}var Ou=null;function wP(){try{return window.self!==window.top}catch{return!0}}function kP(){return window.__PMX_AMP_ORB===!0}function PS(e={}){if(tt())return _n.value="srcdoc",Promise.resolve("srcdoc");if(_n.value)return Promise.resolve(_n.value);if(Ou)return Ou;let t=xP();if(t)return _n.value=t,Promise.resolve(t);if(!(e.embedded??wP()))return _n.value="src",RS(e.probeTimeoutMs).then((n)=>{if(!n&&_n.value==="src")_n.value="srcdoc"}),Promise.resolve("src");if(e.ampOrb??kP())return _n.value="srcdoc",Promise.resolve("srcdoc");return Ou=RS(e.probeTimeoutMs).then((n)=>{let o=n?"src":"srcdoc";return _n.value=o,o}),Ou}function qs(e){let t=tt()&&e.startsWith("/"),[n,o]=E(null);return q(()=>{if(!t)return;let i=!1;return Gt(e).then(async(s)=>{if(!s.ok)throw Error(`Asset read failed: ${s.status}`);let a=new FileReader;a.onload=()=>{if(!i&&typeof a.result==="string")o({path:e,url:a.result})},a.readAsDataURL(await s.blob())}).catch((s)=>console.error("[workbench-asset]",s)),()=>{i=!0}},[e,t]),t?n?.path===e?n.url:void 0:e}function NS({node:e,expanded:t=!1}){let n=String(e.data.attachmentId),o=qs(`/api/canvas/attachments/${encodeURIComponent(n)}/bytes`),i=se.value,[s,a]=E(null),[l,c]=E(t),[u,d]=E(!1);q(()=>{let m=!0,h=async()=>{let v=await pe("readImports",`/api/canvas/imports?boardId=${encodeURIComponent(i??"")}`,null);if(m)a(v?.imports?.find((b)=>b.attachmentId===n)??null)};h();let g=window.setInterval(()=>void h(),2000);return()=>{m=!1,window.clearInterval(g)}},[n,i]),q(()=>{if(!l)return;let m=(h)=>{if(h.key==="Escape")h.stopPropagation(),c(!1)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[l]);let p=async(m)=>{if(!s)return;d(!0);let h=await pe(`import.${m}`,`/api/canvas/imports/${s.id}/${m}`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({consent:!0})});if(d(!1),h?.import){if(a(h.import),c(!1),t&&m==="commit")Cr()}},f=s&&["attached","cancelled","unavailable"].includes(s.status);return r("div",{class:"attachment-node",onPointerDown:(m)=>m.stopPropagation(),children:[r("div",{class:"attachment-status",children:s?.status==="requested"?"Waiting for agent":s?.status==="drafted"?"Ready for review":s?.status==="committed"?"Markdown added":"Original attached"},void 0,!1,void 0,this),r("a",{href:o,download:String(e.data.title??"attachment"),target:"_blank",rel:"noopener noreferrer",children:["Download original · ",Math.ceil(Number(e.data.size??0)/1024)," KB"]},void 0,!0,void 0,this),s?.reason&&r("p",{children:s.reason},void 0,!1,void 0,this),f&&r(be,{children:[r("p",{id:`import-consent-${e.id}`,children:"Asking the agent to import allows it to process this file with its tools and model provider."},void 0,!1,void 0,this),r("button",{type:"button",class:"attachment-button is-primary","aria-describedby":`import-consent-${e.id}`,disabled:u,onClick:()=>void p("request"),children:"Ask agent to import"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s?.status==="requested"&&r("p",{children:"No automatic extraction. Ask your connected agent to check its pending steering or use canvas_import list."},void 0,!1,void 0,this),s?.status==="drafted"&&!l&&r("button",{type:"button",class:"attachment-button is-primary",onClick:()=>t?c(!0):xo(e.id),children:["Review Markdown · ",s.sections.length," ",s.sections.length===1?"card":"cards"]},void 0,!0,void 0,this),s&&["requested","drafted"].includes(s.status)&&r("button",{type:"button",class:"attachment-button",disabled:u,onClick:()=>void p("cancel"),children:"Cancel import"},void 0,!1,void 0,this),l&&s?.status==="drafted"&&r("div",{class:"attachment-review",role:"dialog","aria-label":"Review imported Markdown",children:[r("h3",{children:"Review imported Markdown"},void 0,!1,void 0,this),r("p",{children:["Source material, not instructions or verified knowledge. ",s.agentDescription]},void 0,!0,void 0,this),s.warnings.length>0&&r("ul",{children:s.warnings.map((m)=>r("li",{children:m},m,!1,void 0,this))},void 0,!1,void 0,this),s.sections.map((m,h)=>r("section",{children:[r("h4",{children:m.title},void 0,!1,void 0,this),r("p",{children:m.reference||"Source location not supplied"},void 0,!1,void 0,this),r("pre",{children:m.markdown},void 0,!1,void 0,this)]},h,!0,void 0,this)),r("div",{class:"attachment-review-actions",children:[r("button",{type:"button",class:"attachment-button",onClick:()=>c(!1),children:"Close review"},void 0,!1,void 0,this),r("button",{type:"button",class:"attachment-button is-primary",disabled:u||i!==s.boardId,onClick:()=>void p("commit"),children:"Add to board"},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 SP(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",py:"Python",rs:"Rust",go:"Go",rb:"Ruby",java:"Java",kt:"Kotlin",swift:"Swift",c:"C",cpp:"C++",h:"C/C++",css:"CSS",html:"HTML",json:"JSON",yaml:"YAML",yml:"YAML",md:"Markdown",toml:"TOML",sql:"SQL",sh:"Shell",bash:"Shell",xml:"XML",graphql:"GraphQL",proto:"Protobuf"}[t]??(t.toUpperCase()||"Text")}var _m=500;function Cm(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.round(e)} B`;let t=["KB","MB","GB","TB"],n=e/1024,o=0;while(n>=1024&&o<t.length-1)n/=1024,o++;return`${n<10?n.toFixed(1):Math.round(n)} ${t[o]}`}function Du({node:e,expanded:t=!1}){if(typeof e.data.attachmentId==="string")return r(NS,{node:e,expanded:t},void 0,!1,void 0,this);return r(_P,{node:e,expanded:t},void 0,!1,void 0,this)}function _P({node:e,expanded:t=!1}){let n=e.data.path||e.data.content||"",o=e.data.title||n.split("/").pop()||"File",i=e.data.fileContent,s=e.data.updatedAt,a=e.data.lineCount,l=e.data.byteSize,c=e.data.binary===!0,u=e.data.truncated===!0,p=e.data.mimeType==="application/pdf"||n.toLowerCase().endsWith(".pdf"),f=c||p,[m,h]=E(i??""),[g,v]=E(!i&&!!n&&!f),[b,x]=E(null),[C,y]=E(0);q(()=>{if(!n)return;if(f){v(!1);return}if(i!==void 0){h(i),v(!1);return}let X=!1;return v(!0),x(null),ol(n).then(({content:V})=>{if(X)return;if(!V&&V!==""){x("File not found"),v(!1);return}h(V),v(!1);let ee=V.split(`
94
+ `).length;Xe(e.id,{fileContent:V,lineCount:ee}),ln(e.id,{data:{fileContent:V,lineCount:ee}})}).catch(()=>{if(!X)x("Failed to load file"),v(!1)}),()=>{X=!0}},[n,i,f]),q(()=>{if(i!==void 0&&i!==m)h(i)},[i]);let k=oe(()=>{if(!n)return;if(f){y((X)=>X+1);return}v(!0),x(null),Xe(e.id,{fileContent:void 0}),ln(e.id,{data:{fileContent:void 0}}),ol(n).then(({content:X})=>{h(X),v(!1);let V=X.split(`
95
95
  `).length,ee=new Date().toISOString();Xe(e.id,{fileContent:X,lineCount:V,updatedAt:ee}),ln(e.id,{data:{fileContent:X,lineCount:V,updatedAt:ee}})}).catch(()=>{x("Failed to reload"),v(!1)})},[n,e.id,f]),_=SP(n),I=m.split(`
96
- `),w=`${String(I.length).length+1}ch`,P=ES(n),L=Ke(()=>{if(!P||f||!m)return null;let X=AS(m,P);return X.header.length>=2?X:null},[m,P,f]),N=Ws(f?`/api/canvas/file-bytes?nodeId=${encodeURIComponent(e.id)}${C?`&v=${C}`:""}`:""),Y=_n.value==="srcdoc",B=f||L!==null,J=u?r("div",{class:"file-node-notice",children:["Showing the first ",km(m.length)," of ",km(l??m.length)]},void 0,!0,void 0,this):null;if(!n)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No file path set"},void 0,!1,void 0,this);return r("div",{style:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"var(--font-code)",fontSize:t?"13px":"11px"},children:[r("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 10px",borderBottom:"1px solid var(--c-line)",flexShrink:0},children:[r("span",{style:{fontSize:"9px",padding:"1px 5px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)",borderRadius:"3px",fontWeight:600},children:_},void 0,!1,void 0,this),r("span",{style:{color:"var(--c-text-soft)",fontSize:t?"12px":"10px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:n},void 0,!1,void 0,this),a!==void 0&&r("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:[a," lines"]},void 0,!0,void 0,this),s&&r("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:new Date(s).toLocaleTimeString()},void 0,!1,void 0,this),r(_e,{label:"Mark this file as AX evidence",align:"end",fitWithin:".node-content",children:r("button",{type:"button",class:"ax-node-action","aria-label":"Mark this file as AX evidence",onClick:(X)=>{X.stopPropagation(),ii(e,"ax.evidence.add",{kind:"file",title:n.split("/").pop()||n,ref:n},"Marked as evidence")},style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:r(cS,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Reload file",align:"end",fitWithin:".node-content",children:r("button",{type:"button",onClick:k,"aria-label":"Reload file",style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:r(Ru,{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),r("div",{style:{flex:1,minHeight:0,overflow:B?"hidden":"auto",padding:B?0:"8px 0",background:t?"var(--c-panel-soft)":void 0,borderRadius:t?"0 0 8px 8px":void 0},children:[p&&(Y?r("div",{class:"file-node-placeholder",children:[r("div",{children:"PDF preview is unavailable in this embedded host."},void 0,!1,void 0,this),r("a",{class:"file-node-link",href:N,target:"_blank",rel:"noreferrer",children:"Open PDF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("iframe",{src:N,title:o,sandbox:"",style:{width:"100%",height:"100%",border:"none",display:"block"}},void 0,!1,void 0,this)),!p&&c&&r("div",{class:"file-node-placeholder",children:[r("div",{class:"file-node-placeholder-name",children:o},void 0,!1,void 0,this),r("div",{children:"Binary file"},void 0,!1,void 0,this),l!==void 0&&r("div",{children:km(l)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!f&&r(be,{children:[g&&r("div",{style:{color:"var(--c-dim)",padding:"12px",fontStyle:"italic"},children:"Loading…"},void 0,!1,void 0,this),b&&r("div",{style:{color:"var(--c-danger)",padding:"12px"},children:b},void 0,!1,void 0,this),!g&&!b&&(L?r("div",{class:"file-table-shell",children:[J,L.rows.length>wm&&r("div",{class:"file-node-notice",children:["Showing ",wm," of ",L.rows.length," rows"]},void 0,!0,void 0,this),r("div",{class:"file-table-wrap",children:r("table",{class:"file-table",children:[r("thead",{children:r("tr",{children:L.header.map((X,V)=>r("th",{children:X},V,!1,void 0,this))},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("tbody",{children:L.rows.slice(0,wm).map((X,V)=>r("tr",{children:X.map((ee,he)=>r("td",{children:ee},he,!1,void 0,this))},V,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[J,r("pre",{style:{margin:0,lineHeight:"1.55",tabSize:2},children:I.map((X,V)=>r("div",{style:{display:"flex",minHeight:"1.55em"},children:[r("span",{style:{width:w,minWidth:w,textAlign:"right",color:"var(--c-dim)",paddingRight:"12px",paddingLeft:"10px",userSelect:"none",flexShrink:0,opacity:0.6},children:V+1},void 0,!1,void 0,this),r("code",{style:{color:"var(--c-text)",whiteSpace:"pre",paddingRight:"10px"},children:X||`
97
- `},void 0,!1,void 0,this)]},V,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var CP=new Set(["title","__type","content","strictSize","arrangeLocked"]);function Du({node:e}){let t=e.data,o=(typeof t.content==="string"?t.content:"").split(/\r\n|\r|\n|\\n/).map((s)=>s.trimEnd()).filter((s)=>s.length>0),i=Object.entries(t).filter(([s])=>!CP.has(s));if(o.length===0&&i.length===0)return r("div",{style:{color:"var(--c-dim)",fontSize:"12px",fontStyle:"italic"},children:"No ledger data"},void 0,!1,void 0,this);return r("div",{style:{display:"flex",flexDirection:"column",gap:"4px",fontSize:"12px"},children:[o.length>0&&r("div",{style:{display:"flex",flexDirection:"column"},children:o.map((s,a)=>r("div",{style:{padding:"3px 0",borderBottom:a<o.length-1?"1px solid rgba(45,55,90,0.3)":"none",color:"var(--c-text)",fontFamily:"var(--font-code)",fontSize:"11px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s},a,!1,void 0,this))},void 0,!1,void 0,this),i.map(([s,a])=>r("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px",padding:"3px 0",borderBottom:"1px solid rgba(45,55,90,0.3)"},children:[r("span",{style:{color:"var(--c-muted)",fontSize:"11px",flexShrink:0},children:s.replace(/([A-Z])/g," $1").replace(/^./,(l)=>l.toUpperCase())},void 0,!1,void 0,this),r("span",{style:{color:"var(--c-text)",fontFamily:"var(--font-code)",fontSize:"11px",textAlign:"right",wordBreak:"break-word"},children:typeof a==="object"?JSON.stringify(a):String(a??"—")},void 0,!1,void 0,this)]},s,!0,void 0,this))]},void 0,!0,void 0,this)}function _m(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Vi=_m();function BS(e){Vi=e}var bl={exec:()=>null};function yt(e,t=""){let n=typeof e==="string"?e:e.source,o={replace:(i,s)=>{let a=typeof s==="string"?s:s.source;return a=a.replace(qn.caret,"$1"),n=n.replace(i,a),o},getRegex:()=>new RegExp(n,t)};return o}var qn={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:(e)=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},TP=/^(?:[ \t]*(?:\n|$))+/,IP=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,EP=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,xl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,AP=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Cm=/(?:[*+-]|\d{1,9}[.)])/,FS=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,HS=yt(FS).replace(/bull/g,Cm).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),RP=yt(FS).replace(/bull/g,Cm).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Tm=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,PP=/^[^\n]+/,Im=/(?!\s*\])(?:\\.|[^\[\]\\])+/,NP=yt(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Im).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),MP=yt(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Cm).getRegex(),Zu="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Em=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zP=yt("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",Em).replace("tag",Zu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),US=yt(Tm).replace("hr",xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Zu).getRegex(),$P=yt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",US).getRegex(),Am={blockquote:$P,code:IP,def:NP,fences:EP,heading:AP,hr:xl,html:zP,lheading:HS,list:MP,newline:TP,paragraph:US,table:bl,text:PP},zS=yt("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Zu).getRegex(),LP={...Am,lheading:RP,table:zS,paragraph:yt(Tm).replace("hr",xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",zS).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Zu).getRegex()},OP={...Am,html:yt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Em).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:bl,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:yt(Tm).replace("hr",xl).replace("heading",` *#{1,6} *[^
98
- ]`).replace("lheading",HS).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},DP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,BP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,jS=/^( {2,}|\\)\n(?!\s*$)/,FP=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Wu=/[\p{P}\p{S}]/u,Rm=/[\s\p{P}\p{S}]/u,ZS=/[^\s\p{P}\p{S}]/u,HP=yt(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Rm).getRegex(),WS=/(?!~)[\p{P}\p{S}]/u,UP=/(?!~)[\s\p{P}\p{S}]/u,jP=/(?:[^\s\p{P}\p{S}]|~)/u,ZP=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,qS=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,WP=yt(qS,"u").replace(/punct/g,Wu).getRegex(),qP=yt(qS,"u").replace(/punct/g,WS).getRegex(),GS="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",GP=yt(GS,"gu").replace(/notPunctSpace/g,ZS).replace(/punctSpace/g,Rm).replace(/punct/g,Wu).getRegex(),KP=yt(GS,"gu").replace(/notPunctSpace/g,jP).replace(/punctSpace/g,UP).replace(/punct/g,WS).getRegex(),VP=yt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ZS).replace(/punctSpace/g,Rm).replace(/punct/g,Wu).getRegex(),XP=yt(/\\(punct)/,"gu").replace(/punct/g,Wu).getRegex(),JP=yt(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),YP=yt(Em).replace("(?:-->|$)","-->").getRegex(),QP=yt("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",YP).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Hu=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,e1=yt(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Hu).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),KS=yt(/^!?\[(label)\]\[(ref)\]/).replace("label",Hu).replace("ref",Im).getRegex(),VS=yt(/^!?\[(ref)\](?:\[\])?/).replace("ref",Im).getRegex(),t1=yt("reflink|nolink(?!\\()","g").replace("reflink",KS).replace("nolink",VS).getRegex(),Pm={_backpedal:bl,anyPunctuation:XP,autolink:JP,blockSkip:ZP,br:jS,code:BP,del:bl,emStrongLDelim:WP,emStrongRDelimAst:GP,emStrongRDelimUnd:VP,escape:DP,link:e1,nolink:VS,punctuation:HP,reflink:KS,reflinkSearch:t1,tag:QP,text:FP,url:bl},n1={...Pm,link:yt(/^!?\[(label)\]\((.*?)\)/).replace("label",Hu).getRegex(),reflink:yt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Hu).getRegex()},Sm={...Pm,emStrongRDelimAst:KP,emStrongLDelim:qP,url:yt(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},o1={...Sm,br:yt(jS).replace("{2,}","*").getRegex(),text:yt(Sm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Bu={normal:Am,gfm:LP,pedantic:OP},yl={normal:Pm,gfm:Sm,breaks:o1,pedantic:n1},r1={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},$S=(e)=>r1[e];function Yo(e,t){if(t){if(qn.escapeTest.test(e))return e.replace(qn.escapeReplace,$S)}else if(qn.escapeTestNoEncode.test(e))return e.replace(qn.escapeReplaceNoEncode,$S);return e}function LS(e){try{e=encodeURI(e).replace(qn.percentDecode,"%")}catch{return null}return e}function OS(e,t){let n=e.replace(qn.findPipe,(s,a,l)=>{let c=!1,u=a;while(--u>=0&&l[u]==="\\")c=!c;if(c)return"|";else return" |"}),o=n.split(qn.splitPipe),i=0;if(!o[0].trim())o.shift();if(o.length>0&&!o.at(-1)?.trim())o.pop();if(t)if(o.length>t)o.splice(t);else while(o.length<t)o.push("");for(;i<o.length;i++)o[i]=o[i].trim().replace(qn.slashPipe,"|");return o}function vl(e,t,n){let o=e.length;if(o===0)return"";let i=0;while(i<o){let s=e.charAt(o-i-1);if(s===t&&!n)i++;else if(s!==t&&n)i++;else break}return e.slice(0,o-i)}function i1(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let o=0;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])n++;else if(e[o]===t[1]){if(n--,n<0)return o}if(n>0)return-2;return-1}function DS(e,t,n,o,i){let s=t.href,a=t.title||null,l=e[1].replace(i.other.outputLinkReplace,"$1");o.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:a,text:l,tokens:o.inlineTokens(l)};return o.state.inLink=!1,c}function s1(e,t,n){let o=e.match(n.other.indentCodeCompensation);if(o===null)return t;let i=o[1];return t.split(`
96
+ `),w=`${String(I.length).length+1}ch`,P=IS(n),L=Ke(()=>{if(!P||f||!m)return null;let X=ES(m,P);return X.header.length>=2?X:null},[m,P,f]),N=qs(f?`/api/canvas/file-bytes?nodeId=${encodeURIComponent(e.id)}${C?`&v=${C}`:""}`:""),Y=_n.value==="srcdoc",B=f||L!==null,J=u?r("div",{class:"file-node-notice",children:["Showing the first ",Cm(m.length)," of ",Cm(l??m.length)]},void 0,!0,void 0,this):null;if(!n)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No file path set"},void 0,!1,void 0,this);return r("div",{style:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"var(--font-code)",fontSize:t?"13px":"11px"},children:[r("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 10px",borderBottom:"1px solid var(--c-line)",flexShrink:0},children:[r("span",{style:{fontSize:"9px",padding:"1px 5px",background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)",borderRadius:"3px",fontWeight:600},children:_},void 0,!1,void 0,this),r("span",{style:{color:"var(--c-text-soft)",fontSize:t?"12px":"10px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:n},void 0,!1,void 0,this),a!==void 0&&r("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:[a," lines"]},void 0,!0,void 0,this),s&&r("span",{style:{color:"var(--c-dim)",fontSize:"10px",flexShrink:0},children:new Date(s).toLocaleTimeString()},void 0,!1,void 0,this),r(_e,{label:"Mark this file as AX evidence",align:"end",fitWithin:".node-content",children:r("button",{type:"button",class:"ax-node-action","aria-label":"Mark this file as AX evidence",onClick:(X)=>{X.stopPropagation(),ii(e,"ax.evidence.add",{kind:"file",title:n.split("/").pop()||n,ref:n},"Marked as evidence")},style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:r(lS,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Reload file",align:"end",fitWithin:".node-content",children:r("button",{type:"button",onClick:k,"aria-label":"Reload file",style:{background:"none",border:"none",color:"var(--c-muted)",cursor:"pointer",padding:"2px 4px",fontSize:"12px",flexShrink:0},children:r(Pu,{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),r("div",{style:{flex:1,minHeight:0,overflow:B?"hidden":"auto",padding:B?0:"8px 0",background:t?"var(--c-panel-soft)":void 0,borderRadius:t?"0 0 8px 8px":void 0},children:[p&&(Y?r("div",{class:"file-node-placeholder",children:[r("div",{children:"PDF preview is unavailable in this embedded host."},void 0,!1,void 0,this),r("a",{class:"file-node-link",href:N,target:"_blank",rel:"noreferrer",children:"Open PDF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("iframe",{src:N,title:o,sandbox:"",style:{width:"100%",height:"100%",border:"none",display:"block"}},void 0,!1,void 0,this)),!p&&c&&r("div",{class:"file-node-placeholder",children:[r("div",{class:"file-node-placeholder-name",children:o},void 0,!1,void 0,this),r("div",{children:"Binary file"},void 0,!1,void 0,this),l!==void 0&&r("div",{children:Cm(l)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!f&&r(be,{children:[g&&r("div",{style:{color:"var(--c-dim)",padding:"12px",fontStyle:"italic"},children:"Loading…"},void 0,!1,void 0,this),b&&r("div",{style:{color:"var(--c-danger)",padding:"12px"},children:b},void 0,!1,void 0,this),!g&&!b&&(L?r("div",{class:"file-table-shell",children:[J,L.rows.length>_m&&r("div",{class:"file-node-notice",children:["Showing ",_m," of ",L.rows.length," rows"]},void 0,!0,void 0,this),r("div",{class:"file-table-wrap",children:r("table",{class:"file-table",children:[r("thead",{children:r("tr",{children:L.header.map((X,V)=>r("th",{children:X},V,!1,void 0,this))},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("tbody",{children:L.rows.slice(0,_m).map((X,V)=>r("tr",{children:X.map((ee,he)=>r("td",{children:ee},he,!1,void 0,this))},V,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[J,r("pre",{style:{margin:0,lineHeight:"1.55",tabSize:2},children:I.map((X,V)=>r("div",{style:{display:"flex",minHeight:"1.55em"},children:[r("span",{style:{width:w,minWidth:w,textAlign:"right",color:"var(--c-dim)",paddingRight:"12px",paddingLeft:"10px",userSelect:"none",flexShrink:0,opacity:0.6},children:V+1},void 0,!1,void 0,this),r("code",{style:{color:"var(--c-text)",whiteSpace:"pre",paddingRight:"10px"},children:X||`
97
+ `},void 0,!1,void 0,this)]},V,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var CP=new Set(["title","__type","content","strictSize","arrangeLocked"]);function Bu({node:e}){let t=e.data,o=(typeof t.content==="string"?t.content:"").split(/\r\n|\r|\n|\\n/).map((s)=>s.trimEnd()).filter((s)=>s.length>0),i=Object.entries(t).filter(([s])=>!CP.has(s));if(o.length===0&&i.length===0)return r("div",{style:{color:"var(--c-dim)",fontSize:"12px",fontStyle:"italic"},children:"No ledger data"},void 0,!1,void 0,this);return r("div",{style:{display:"flex",flexDirection:"column",gap:"4px",fontSize:"12px"},children:[o.length>0&&r("div",{style:{display:"flex",flexDirection:"column"},children:o.map((s,a)=>r("div",{style:{padding:"3px 0",borderBottom:a<o.length-1?"1px solid rgba(45,55,90,0.3)":"none",color:"var(--c-text)",fontFamily:"var(--font-code)",fontSize:"11px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s},a,!1,void 0,this))},void 0,!1,void 0,this),i.map(([s,a])=>r("div",{style:{display:"flex",justifyContent:"space-between",gap:"8px",padding:"3px 0",borderBottom:"1px solid rgba(45,55,90,0.3)"},children:[r("span",{style:{color:"var(--c-muted)",fontSize:"11px",flexShrink:0},children:s.replace(/([A-Z])/g," $1").replace(/^./,(l)=>l.toUpperCase())},void 0,!1,void 0,this),r("span",{style:{color:"var(--c-text)",fontFamily:"var(--font-code)",fontSize:"11px",textAlign:"right",wordBreak:"break-word"},children:typeof a==="object"?JSON.stringify(a):String(a??"—")},void 0,!1,void 0,this)]},s,!0,void 0,this))]},void 0,!0,void 0,this)}function Im(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Vi=Im();function DS(e){Vi=e}var bl={exec:()=>null};function yt(e,t=""){let n=typeof e==="string"?e:e.source,o={replace:(i,s)=>{let a=typeof s==="string"?s:s.source;return a=a.replace(qn.caret,"$1"),n=n.replace(i,a),o},getRegex:()=>new RegExp(n,t)};return o}var qn={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:(e)=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:(e)=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},TP=/^(?:[ \t]*(?:\n|$))+/,IP=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,EP=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,xl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,AP=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Em=/(?:[*+-]|\d{1,9}[.)])/,BS=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,FS=yt(BS).replace(/bull/g,Em).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),RP=yt(BS).replace(/bull/g,Em).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Am=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,PP=/^[^\n]+/,Rm=/(?!\s*\])(?:\\.|[^\[\]\\])+/,NP=yt(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Rm).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),MP=yt(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Em).getRegex(),Wu="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Pm=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zP=yt("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",Pm).replace("tag",Wu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),HS=yt(Am).replace("hr",xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Wu).getRegex(),$P=yt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",HS).getRegex(),Nm={blockquote:$P,code:IP,def:NP,fences:EP,heading:AP,hr:xl,html:zP,lheading:FS,list:MP,newline:TP,paragraph:HS,table:bl,text:PP},MS=yt("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Wu).getRegex(),LP={...Nm,lheading:RP,table:MS,paragraph:yt(Am).replace("hr",xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",MS).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Wu).getRegex()},OP={...Nm,html:yt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Pm).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:bl,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:yt(Am).replace("hr",xl).replace("heading",` *#{1,6} *[^
98
+ ]`).replace("lheading",FS).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},DP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,BP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,US=/^( {2,}|\\)\n(?!\s*$)/,FP=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,qu=/[\p{P}\p{S}]/u,Mm=/[\s\p{P}\p{S}]/u,jS=/[^\s\p{P}\p{S}]/u,HP=yt(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Mm).getRegex(),ZS=/(?!~)[\p{P}\p{S}]/u,UP=/(?!~)[\s\p{P}\p{S}]/u,jP=/(?:[^\s\p{P}\p{S}]|~)/u,ZP=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,WS=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,WP=yt(WS,"u").replace(/punct/g,qu).getRegex(),qP=yt(WS,"u").replace(/punct/g,ZS).getRegex(),qS="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",GP=yt(qS,"gu").replace(/notPunctSpace/g,jS).replace(/punctSpace/g,Mm).replace(/punct/g,qu).getRegex(),KP=yt(qS,"gu").replace(/notPunctSpace/g,jP).replace(/punctSpace/g,UP).replace(/punct/g,ZS).getRegex(),VP=yt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,jS).replace(/punctSpace/g,Mm).replace(/punct/g,qu).getRegex(),XP=yt(/\\(punct)/,"gu").replace(/punct/g,qu).getRegex(),JP=yt(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),YP=yt(Pm).replace("(?:-->|$)","-->").getRegex(),QP=yt("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",YP).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Uu=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,e1=yt(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Uu).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),GS=yt(/^!?\[(label)\]\[(ref)\]/).replace("label",Uu).replace("ref",Rm).getRegex(),KS=yt(/^!?\[(ref)\](?:\[\])?/).replace("ref",Rm).getRegex(),t1=yt("reflink|nolink(?!\\()","g").replace("reflink",GS).replace("nolink",KS).getRegex(),zm={_backpedal:bl,anyPunctuation:XP,autolink:JP,blockSkip:ZP,br:US,code:BP,del:bl,emStrongLDelim:WP,emStrongRDelimAst:GP,emStrongRDelimUnd:VP,escape:DP,link:e1,nolink:KS,punctuation:HP,reflink:GS,reflinkSearch:t1,tag:QP,text:FP,url:bl},n1={...zm,link:yt(/^!?\[(label)\]\((.*?)\)/).replace("label",Uu).getRegex(),reflink:yt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Uu).getRegex()},Tm={...zm,emStrongRDelimAst:KP,emStrongLDelim:qP,url:yt(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},o1={...Tm,br:yt(US).replace("{2,}","*").getRegex(),text:yt(Tm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Fu={normal:Nm,gfm:LP,pedantic:OP},yl={normal:zm,gfm:Tm,breaks:o1,pedantic:n1},r1={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},zS=(e)=>r1[e];function Yo(e,t){if(t){if(qn.escapeTest.test(e))return e.replace(qn.escapeReplace,zS)}else if(qn.escapeTestNoEncode.test(e))return e.replace(qn.escapeReplaceNoEncode,zS);return e}function $S(e){try{e=encodeURI(e).replace(qn.percentDecode,"%")}catch{return null}return e}function LS(e,t){let n=e.replace(qn.findPipe,(s,a,l)=>{let c=!1,u=a;while(--u>=0&&l[u]==="\\")c=!c;if(c)return"|";else return" |"}),o=n.split(qn.splitPipe),i=0;if(!o[0].trim())o.shift();if(o.length>0&&!o.at(-1)?.trim())o.pop();if(t)if(o.length>t)o.splice(t);else while(o.length<t)o.push("");for(;i<o.length;i++)o[i]=o[i].trim().replace(qn.slashPipe,"|");return o}function vl(e,t,n){let o=e.length;if(o===0)return"";let i=0;while(i<o){let s=e.charAt(o-i-1);if(s===t&&!n)i++;else if(s!==t&&n)i++;else break}return e.slice(0,o-i)}function i1(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let o=0;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])n++;else if(e[o]===t[1]){if(n--,n<0)return o}if(n>0)return-2;return-1}function OS(e,t,n,o,i){let s=t.href,a=t.title||null,l=e[1].replace(i.other.outputLinkReplace,"$1");o.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:a,text:l,tokens:o.inlineTokens(l)};return o.state.inLink=!1,c}function s1(e,t,n){let o=e.match(n.other.indentCodeCompensation);if(o===null)return t;let i=o[1];return t.split(`
99
99
  `).map((s)=>{let a=s.match(n.other.beginningSpace);if(a===null)return s;let[l]=a;if(l.length>=i.length)return s.slice(i.length);return s}).join(`
100
- `)}var Uu=class{options;rules;lexer;constructor(e){this.options=e||Vi}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:!this.options.pedantic?vl(n,`
100
+ `)}var ju=class{options;rules;lexer;constructor(e){this.options=e||Vi}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:!this.options.pedantic?vl(n,`
101
101
  `):n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],o=s1(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:o}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let o=vl(n,"#");if(this.options.pedantic)n=o.trim();else if(!o||this.rules.other.endingSpaceChar.test(o))n=o.trim()}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:vl(t[0],`
102
102
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=vl(t[0],`
103
103
  `).split(`
@@ -117,9 +117,9 @@ ${d}`:d;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
117
117
  `,1)[0],I;if(f=_,this.options.pedantic)f=f.replace(this.rules.other.listReplaceNesting," "),I=f;else I=f.replace(this.rules.other.tabCharGlobal," ");if(C.test(f))break;if(y.test(f))break;if(k.test(f))break;if(b.test(f))break;if(x.test(f))break;if(I.search(this.rules.other.nonSpaceChar)>=h||!f.trim())d+=`
118
118
  `+I.slice(h);else{if(m)break;if(p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4)break;if(C.test(p))break;if(y.test(p))break;if(x.test(p))break;d+=`
119
119
  `+f}if(!m&&!f.trim())m=!0;u+=_+`
120
- `,e=e.substring(_.length+1),p=I.slice(h)}}if(!i.loose){if(a)i.loose=!0;else if(this.rules.other.doubleBlankLine.test(u))a=!0}let g=null,v;if(this.options.gfm){if(g=this.rules.other.listIsTask.exec(d),g)v=g[0]!=="[ ] ",d=d.replace(this.rules.other.listReplaceTask,"")}i.items.push({type:"list_item",raw:u,task:!!g,checked:v,loose:!1,text:d,tokens:[]}),i.raw+=u}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c=0;c<i.items.length;c++)if(this.lexer.state.top=!1,i.items[c].tokens=this.lexer.blockTokens(i.items[c].text,[]),!i.loose){let u=i.items[c].tokens.filter((p)=>p.type==="space"),d=u.length>0&&u.some((p)=>this.rules.other.anyLine.test(p.raw));i.loose=d}if(i.loose)for(let c=0;c<i.items.length;c++)i.items[c].loose=!0;return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),o=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t)return;if(!this.rules.other.tableDelimiter.test(t[2]))return;let n=OS(t[1]),o=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
121
- `):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length!==o.length)return;for(let a of o)if(this.rules.other.tableAlignRight.test(a))s.align.push("right");else if(this.rules.other.tableAlignCenter.test(a))s.align.push("center");else if(this.rules.other.tableAlignLeft.test(a))s.align.push("left");else s.align.push(null);for(let a=0;a<n.length;a++)s.header.push({text:n[a],tokens:this.lexer.inline(n[a]),header:!0,align:s.align[a]});for(let a of i)s.rows.push(OS(a,s.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:s.align[c]})));return s}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
122
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t){if(!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0]))this.lexer.state.inLink=!0;else if(this.lexer.state.inLink&&this.rules.other.endATag.test(t[0]))this.lexer.state.inLink=!1;if(!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0]))this.lexer.state.inRawBlock=!0;else if(this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0]))this.lexer.state.inRawBlock=!1;return{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=vl(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=i1(t[2],"()");if(s===-2)return;if(s>-1){let l=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,l).trim(),t[3]=""}}let o=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(o);if(s)o=s[1],i=s[3]}else i=t[3]?t[3].slice(1,-1):"";if(o=o.trim(),this.rules.other.startAngleBracket.test(o))if(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n))o=o.slice(1);else o=o.slice(1,-1);return DS(t,{href:o?o.replace(this.rules.inline.anyPunctuation,"$1"):o,title:i?i.replace(this.rules.inline.anyPunctuation,"$1"):i},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[o.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return DS(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o)return;if(o[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(o[1]||o[2])||!n||this.rules.inline.punctuation.exec(n)){let s=[...o[0]].length-1,a,l,c=s,u=0,d=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;d.lastIndex=0,t=t.slice(-1*e.length+s);while((o=d.exec(t))!=null){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(l=[...a].length,o[3]||o[4]){c+=l;continue}else if(o[5]||o[6]){if(s%3&&!((s+l)%3)){u+=l;continue}}if(c-=l,c>0)continue;l=Math.min(l,l+c+u);let p=[...o[0]][0].length,f=e.slice(0,s+o.index+p+l);if(Math.min(s,l)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),o=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);if(o&&i)n=n.substring(1,n.length-1);return{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,o;if(t[2]==="@")n=t[1],o="mailto:"+n;else n=t[1],o=n;return{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,o;if(t[2]==="@")n=t[0],o="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);if(n=t[0],t[1]==="www.")o="http://"+t[0];else o=t[0]}return{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ir=class e{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Vi,this.options.tokenizer=this.options.tokenizer||new Uu,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:qn,block:Bu.normal,inline:yl.normal};if(this.options.pedantic)n.block=Bu.pedantic,n.inline=yl.pedantic;else if(this.options.gfm)if(n.block=Bu.gfm,this.options.breaks)n.inline=yl.breaks;else n.inline=yl.gfm;this.tokenizer.rules=n}static get rules(){return{block:Bu,inline:yl}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(t){t=t.replace(qn.carriageReturn,`
120
+ `,e=e.substring(_.length+1),p=I.slice(h)}}if(!i.loose){if(a)i.loose=!0;else if(this.rules.other.doubleBlankLine.test(u))a=!0}let g=null,v;if(this.options.gfm){if(g=this.rules.other.listIsTask.exec(d),g)v=g[0]!=="[ ] ",d=d.replace(this.rules.other.listReplaceTask,"")}i.items.push({type:"list_item",raw:u,task:!!g,checked:v,loose:!1,text:d,tokens:[]}),i.raw+=u}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c=0;c<i.items.length;c++)if(this.lexer.state.top=!1,i.items[c].tokens=this.lexer.blockTokens(i.items[c].text,[]),!i.loose){let u=i.items[c].tokens.filter((p)=>p.type==="space"),d=u.length>0&&u.some((p)=>this.rules.other.anyLine.test(p.raw));i.loose=d}if(i.loose)for(let c=0;c<i.items.length;c++)i.items[c].loose=!0;return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),o=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t)return;if(!this.rules.other.tableDelimiter.test(t[2]))return;let n=LS(t[1]),o=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
121
+ `):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length!==o.length)return;for(let a of o)if(this.rules.other.tableAlignRight.test(a))s.align.push("right");else if(this.rules.other.tableAlignCenter.test(a))s.align.push("center");else if(this.rules.other.tableAlignLeft.test(a))s.align.push("left");else s.align.push(null);for(let a=0;a<n.length;a++)s.header.push({text:n[a],tokens:this.lexer.inline(n[a]),header:!0,align:s.align[a]});for(let a of i)s.rows.push(LS(a,s.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:s.align[c]})));return s}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
122
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t){if(!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0]))this.lexer.state.inLink=!0;else if(this.lexer.state.inLink&&this.rules.other.endATag.test(t[0]))this.lexer.state.inLink=!1;if(!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0]))this.lexer.state.inRawBlock=!0;else if(this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0]))this.lexer.state.inRawBlock=!1;return{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=vl(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=i1(t[2],"()");if(s===-2)return;if(s>-1){let l=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,l).trim(),t[3]=""}}let o=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(o);if(s)o=s[1],i=s[3]}else i=t[3]?t[3].slice(1,-1):"";if(o=o.trim(),this.rules.other.startAngleBracket.test(o))if(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n))o=o.slice(1);else o=o.slice(1,-1);return OS(t,{href:o?o.replace(this.rules.inline.anyPunctuation,"$1"):o,title:i?i.replace(this.rules.inline.anyPunctuation,"$1"):i},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let o=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[o.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return OS(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(e);if(!o)return;if(o[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(o[1]||o[2])||!n||this.rules.inline.punctuation.exec(n)){let s=[...o[0]].length-1,a,l,c=s,u=0,d=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;d.lastIndex=0,t=t.slice(-1*e.length+s);while((o=d.exec(t))!=null){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(l=[...a].length,o[3]||o[4]){c+=l;continue}else if(o[5]||o[6]){if(s%3&&!((s+l)%3)){u+=l;continue}}if(c-=l,c>0)continue;l=Math.min(l,l+c+u);let p=[...o[0]][0].length,f=e.slice(0,s+o.index+p+l);if(Math.min(s,l)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),o=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);if(o&&i)n=n.substring(1,n.length-1);return{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,o;if(t[2]==="@")n=t[1],o="mailto:"+n;else n=t[1],o=n;return{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,o;if(t[2]==="@")n=t[0],o="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);if(n=t[0],t[1]==="www.")o="http://"+t[0];else o=t[0]}return{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ir=class e{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Vi,this.options.tokenizer=this.options.tokenizer||new ju,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:qn,block:Fu.normal,inline:yl.normal};if(this.options.pedantic)n.block=Fu.pedantic,n.inline=yl.pedantic;else if(this.options.gfm)if(n.block=Fu.gfm,this.options.breaks)n.inline=yl.breaks;else n.inline=yl.gfm;this.tokenizer.rules=n}static get rules(){return{block:Fu,inline:yl}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(t){t=t.replace(qn.carriageReturn,`
123
123
  `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let o=this.inlineQueue[n];this.inlineTokens(o.src,o.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],o=!1){if(this.options.pedantic)t=t.replace(qn.tabCharGlobal," ").replace(qn.spaceLine,"");while(t){let i;if(this.options.extensions?.block?.some((a)=>{if(i=a.call({lexer:this},t,n))return t=t.substring(i.raw.length),n.push(i),!0;return!1}))continue;if(i=this.tokenizer.space(t)){t=t.substring(i.raw.length);let a=n.at(-1);if(i.raw.length===1&&a!==void 0)a.raw+=`
124
124
  `;else n.push(i);continue}if(i=this.tokenizer.code(t)){t=t.substring(i.raw.length);let a=n.at(-1);if(a?.type==="paragraph"||a?.type==="text")a.raw+=`
125
125
  `+i.raw,a.text+=`
@@ -129,7 +129,7 @@ ${d}`:d;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
129
129
  `+i.raw,a.text+=`
130
130
  `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text;else n.push(i);o=s.length!==t.length,t=t.substring(i.raw.length);continue}if(i=this.tokenizer.text(t)){t=t.substring(i.raw.length);let a=n.at(-1);if(a?.type==="text")a.raw+=`
131
131
  `+i.raw,a.text+=`
132
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text;else n.push(i);continue}if(t){let a="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw Error(a)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let o=t,i=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0){while((i=this.tokenizer.rules.inline.reflinkSearch.exec(o))!=null)if(l.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1)))o=o.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex)}}while((i=this.tokenizer.rules.inline.anyPunctuation.exec(o))!=null)o=o.slice(0,i.index)+"++"+o.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);while((i=this.tokenizer.rules.inline.blockSkip.exec(o))!=null)o=o.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let s=!1,a="";while(t){if(!s)a="";s=!1;let l;if(this.options.extensions?.inline?.some((u)=>{if(l=u.call({lexer:this},t,n))return t=t.substring(l.raw.length),n.push(l),!0;return!1}))continue;if(l=this.tokenizer.escape(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.tag(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.link(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(l.raw.length);let u=n.at(-1);if(l.type==="text"&&u?.type==="text")u.raw+=l.raw,u.text+=l.text;else n.push(l);continue}if(l=this.tokenizer.emStrong(t,o,a)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.codespan(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.br(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.del(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.autolink(t)){t=t.substring(l.raw.length),n.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(t))){t=t.substring(l.raw.length),n.push(l);continue}let c=t;if(this.options.extensions?.startInline){let u=1/0,d=t.slice(1),p;if(this.options.extensions.startInline.forEach((f)=>{if(p=f.call({lexer:this},d),typeof p==="number"&&p>=0)u=Math.min(u,p)}),u<1/0&&u>=0)c=t.substring(0,u+1)}if(l=this.tokenizer.inlineText(c)){if(t=t.substring(l.raw.length),l.raw.slice(-1)!=="_")a=l.raw.slice(-1);s=!0;let u=n.at(-1);if(u?.type==="text")u.raw+=l.raw,u.text+=l.text;else n.push(l);continue}if(t){let u="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw Error(u)}}return n}},ju=class{options;parser;constructor(e){this.options=e||Vi}space(e){return""}code({text:e,lang:t,escaped:n}){let o=(t||"").match(qn.notSpaceStart)?.[0],i=e.replace(qn.endingNewline,"")+`
132
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text;else n.push(i);continue}if(t){let a="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw Error(a)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let o=t,i=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0){while((i=this.tokenizer.rules.inline.reflinkSearch.exec(o))!=null)if(l.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1)))o=o.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex)}}while((i=this.tokenizer.rules.inline.anyPunctuation.exec(o))!=null)o=o.slice(0,i.index)+"++"+o.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);while((i=this.tokenizer.rules.inline.blockSkip.exec(o))!=null)o=o.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let s=!1,a="";while(t){if(!s)a="";s=!1;let l;if(this.options.extensions?.inline?.some((u)=>{if(l=u.call({lexer:this},t,n))return t=t.substring(l.raw.length),n.push(l),!0;return!1}))continue;if(l=this.tokenizer.escape(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.tag(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.link(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(l.raw.length);let u=n.at(-1);if(l.type==="text"&&u?.type==="text")u.raw+=l.raw,u.text+=l.text;else n.push(l);continue}if(l=this.tokenizer.emStrong(t,o,a)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.codespan(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.br(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.del(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.autolink(t)){t=t.substring(l.raw.length),n.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(t))){t=t.substring(l.raw.length),n.push(l);continue}let c=t;if(this.options.extensions?.startInline){let u=1/0,d=t.slice(1),p;if(this.options.extensions.startInline.forEach((f)=>{if(p=f.call({lexer:this},d),typeof p==="number"&&p>=0)u=Math.min(u,p)}),u<1/0&&u>=0)c=t.substring(0,u+1)}if(l=this.tokenizer.inlineText(c)){if(t=t.substring(l.raw.length),l.raw.slice(-1)!=="_")a=l.raw.slice(-1);s=!0;let u=n.at(-1);if(u?.type==="text")u.raw+=l.raw,u.text+=l.text;else n.push(l);continue}if(t){let u="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw Error(u)}}return n}},Zu=class{options;parser;constructor(e){this.options=e||Vi}space(e){return""}code({text:e,lang:t,escaped:n}){let o=(t||"").match(qn.notSpaceStart)?.[0],i=e.replace(qn.endingNewline,"")+`
133
133
  `;if(!o)return"<pre><code>"+(n?i:Yo(i,!0))+`</code></pre>
134
134
  `;return'<pre><code class="language-'+Yo(o)+'">'+(n?i:Yo(i,!0))+`</code></pre>
135
135
  `}blockquote({tokens:e}){return`<blockquote>
@@ -147,32 +147,32 @@ ${this.parser.parse(e)}</blockquote>
147
147
  `}tablerow({text:e}){return`<tr>
148
148
  ${e}</tr>
149
149
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
150
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Yo(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let o=this.parser.parseInline(n),i=LS(e);if(i===null)return o;e=i;let s='<a href="'+e+'"';if(t)s+=' title="'+Yo(t)+'"';return s+=">"+o+"</a>",s}image({href:e,title:t,text:n,tokens:o}){if(o)n=this.parser.parseInline(o,this.parser.textRenderer);let i=LS(e);if(i===null)return Yo(n);e=i;let s=`<img src="${e}" alt="${n}"`;if(t)s+=` title="${Yo(t)}"`;return s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):("escaped"in e)&&e.escaped?e.text:Yo(e.text)}},Nm=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}},Er=class e{options;renderer;textRenderer;constructor(t){this.options=t||Vi,this.options.renderer=this.options.renderer||new ju,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Nm}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(t,n=!0){let o="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let l=s,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(l.type)){o+=c||"";continue}}let a=s;switch(a.type){case"space":{o+=this.renderer.space(a);continue}case"hr":{o+=this.renderer.hr(a);continue}case"heading":{o+=this.renderer.heading(a);continue}case"code":{o+=this.renderer.code(a);continue}case"table":{o+=this.renderer.table(a);continue}case"blockquote":{o+=this.renderer.blockquote(a);continue}case"list":{o+=this.renderer.list(a);continue}case"html":{o+=this.renderer.html(a);continue}case"paragraph":{o+=this.renderer.paragraph(a);continue}case"text":{let l=a,c=this.renderer.text(l);while(i+1<t.length&&t[i+1].type==="text")l=t[++i],c+=`
151
- `+this.renderer.text(l);if(n)o+=this.renderer.paragraph({type:"paragraph",raw:c,text:c,tokens:[{type:"text",raw:c,text:c,escaped:!0}]});else o+=c;continue}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";else throw Error(l)}}}return o}parseInline(t,n=this.renderer){let o="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){o+=l||"";continue}}let a=s;switch(a.type){case"escape":{o+=n.text(a);break}case"html":{o+=n.html(a);break}case"link":{o+=n.link(a);break}case"image":{o+=n.image(a);break}case"strong":{o+=n.strong(a);break}case"em":{o+=n.em(a);break}case"codespan":{o+=n.codespan(a);break}case"br":{o+=n.br(a);break}case"del":{o+=n.del(a);break}case"text":{o+=n.text(a);break}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";else throw Error(l)}}}return o}},Fu=class{options;block;constructor(e){this.options=e||Vi}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?Ir.lex:Ir.lexInline}provideParser(){return this.block?Er.parse:Er.parseInline}},Mm=class{defaults=_m();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Er;Renderer=ju;TextRenderer=Nm;Lexer=Ir;Tokenizer=Uu;Hooks=Fu;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let i=o;for(let s of i.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of i.rows)for(let a of s)n=n.concat(this.walkTokens(a.tokens,t));break}case"list":{let i=o;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=o;if(this.defaults.extensions?.childTokens?.[i.type])this.defaults.extensions.childTokens[i.type].forEach((s)=>{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))});else if(i.tokens)n=n.concat(this.walkTokens(i.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((n)=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions)n.extensions.forEach((i)=>{if(!i.name)throw Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];if(s)t.renderers[i.name]=function(...a){let l=i.renderer.apply(this,a);if(l===!1)l=s.apply(this,a);return l};else t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let s=t[i.level];if(s)s.unshift(i.tokenizer);else t[i.level]=[i.tokenizer];if(i.start){if(i.level==="block")if(t.startBlock)t.startBlock.push(i.start);else t.startBlock=[i.start];else if(i.level==="inline")if(t.startInline)t.startInline.push(i.start);else t.startInline=[i.start]}}if("childTokens"in i&&i.childTokens)t.childTokens[i.name]=i.childTokens}),o.extensions=t;if(n.renderer){let i=this.defaults.renderer||new ju(this.defaults);for(let s in n.renderer){if(!(s in i))throw Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,l=n.renderer[a],c=i[a];i[a]=(...u)=>{let d=l.apply(i,u);if(d===!1)d=c.apply(i,u);return d||""}}o.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Uu(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,l=n.tokenizer[a],c=i[a];i[a]=(...u)=>{let d=l.apply(i,u);if(d===!1)d=c.apply(i,u);return d}}o.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new Fu;for(let s in n.hooks){if(!(s in i))throw Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,l=n.hooks[a],c=i[a];if(Fu.passThroughHooks.has(s))i[a]=(u)=>{if(this.defaults.async)return Promise.resolve(l.call(i,u)).then((p)=>c.call(i,p));let d=l.call(i,u);return c.call(i,d)};else i[a]=(...u)=>{let d=l.apply(i,u);if(d===!1)d=c.apply(i,u);return d}}o.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;o.walkTokens=function(a){let l=[];if(l.push(s.call(this,a)),i)l=l.concat(i.call(this,a));return l}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ir.lex(e,t??this.defaults)}parser(e,t){return Er.parse(e,t??this.defaults)}parseMarkdown(e){return(n,o)=>{let i={...o},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(Error("marked(): input parameter is undefined or null"));if(typeof n!=="string")return a(Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks)s.hooks.options=s,s.hooks.block=e;let l=s.hooks?s.hooks.provideLexer():e?Ir.lex:Ir.lexInline,c=s.hooks?s.hooks.provideParser():e?Er.parse:Er.parseInline;if(s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(n):n).then((u)=>l(u,s)).then((u)=>s.hooks?s.hooks.processAllTokens(u):u).then((u)=>s.walkTokens?Promise.all(this.walkTokens(u,s.walkTokens)).then(()=>u):u).then((u)=>c(u,s)).then((u)=>s.hooks?s.hooks.postprocess(u):u).catch(a);try{if(s.hooks)n=s.hooks.preprocess(n);let u=l(n,s);if(s.hooks)u=s.hooks.processAllTokens(u);if(s.walkTokens)this.walkTokens(u,s.walkTokens);let d=c(u,s);if(s.hooks)d=s.hooks.postprocess(d);return d}catch(u){return a(u)}}}onError(e,t){return(n)=>{if(n.message+=`
152
- Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+Yo(n.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);return o}if(t)return Promise.reject(n);throw n}}},Ki=new Mm;function It(e,t){return Ki.parse(e,t)}It.options=It.setOptions=function(e){return Ki.setOptions(e),It.defaults=Ki.defaults,BS(It.defaults),It};It.getDefaults=_m;It.defaults=Vi;It.use=function(...e){return Ki.use(...e),It.defaults=Ki.defaults,BS(It.defaults),It};It.walkTokens=function(e,t){return Ki.walkTokens(e,t)};It.parseInline=Ki.parseInline;It.Parser=Er;It.parser=Er.parse;It.Renderer=ju;It.TextRenderer=Nm;It.Lexer=Ir;It.lexer=Ir.lex;It.Tokenizer=Uu;It.Hooks=Fu;It.parse=It;var{options:vU,setOptions:bU,use:xU,walkTokens:wU,parseInline:kU}=It;var SU=Er.parse,_U=Ir.lex;var wl=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),XS=wl?"⌘":"Ctrl";function Ft(e){return wl?`${XS}${e}`:`${XS}+${e}`}function qu(e,t){let{selectionStart:n,selectionEnd:o,value:i}=e,s=i.slice(n,o),a=i.slice(Math.max(0,n-t.length),n),l=i.slice(o,o+t.length);if(a===t&&l===t){let c=i.slice(0,n-t.length)+s+i.slice(o+t.length);Qo(e,c,n-t.length,o-t.length);return}if(s){let c=i.slice(0,n)+t+s+t+i.slice(o);Qo(e,c,n+t.length,o+t.length)}else{let c=i.slice(0,n)+t+t+i.slice(o);Qo(e,c,n+t.length,n+t.length)}}function kl(e,t){let{selectionStart:n,selectionEnd:o,value:i}=e,s=i.lastIndexOf(`
150
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Yo(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let o=this.parser.parseInline(n),i=$S(e);if(i===null)return o;e=i;let s='<a href="'+e+'"';if(t)s+=' title="'+Yo(t)+'"';return s+=">"+o+"</a>",s}image({href:e,title:t,text:n,tokens:o}){if(o)n=this.parser.parseInline(o,this.parser.textRenderer);let i=$S(e);if(i===null)return Yo(n);e=i;let s=`<img src="${e}" alt="${n}"`;if(t)s+=` title="${Yo(t)}"`;return s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):("escaped"in e)&&e.escaped?e.text:Yo(e.text)}},$m=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}},Er=class e{options;renderer;textRenderer;constructor(t){this.options=t||Vi,this.options.renderer=this.options.renderer||new Zu,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new $m}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(t,n=!0){let o="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let l=s,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(l.type)){o+=c||"";continue}}let a=s;switch(a.type){case"space":{o+=this.renderer.space(a);continue}case"hr":{o+=this.renderer.hr(a);continue}case"heading":{o+=this.renderer.heading(a);continue}case"code":{o+=this.renderer.code(a);continue}case"table":{o+=this.renderer.table(a);continue}case"blockquote":{o+=this.renderer.blockquote(a);continue}case"list":{o+=this.renderer.list(a);continue}case"html":{o+=this.renderer.html(a);continue}case"paragraph":{o+=this.renderer.paragraph(a);continue}case"text":{let l=a,c=this.renderer.text(l);while(i+1<t.length&&t[i+1].type==="text")l=t[++i],c+=`
151
+ `+this.renderer.text(l);if(n)o+=this.renderer.paragraph({type:"paragraph",raw:c,text:c,tokens:[{type:"text",raw:c,text:c,escaped:!0}]});else o+=c;continue}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";else throw Error(l)}}}return o}parseInline(t,n=this.renderer){let o="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){o+=l||"";continue}}let a=s;switch(a.type){case"escape":{o+=n.text(a);break}case"html":{o+=n.html(a);break}case"link":{o+=n.link(a);break}case"image":{o+=n.image(a);break}case"strong":{o+=n.strong(a);break}case"em":{o+=n.em(a);break}case"codespan":{o+=n.codespan(a);break}case"br":{o+=n.br(a);break}case"del":{o+=n.del(a);break}case"text":{o+=n.text(a);break}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";else throw Error(l)}}}return o}},Hu=class{options;block;constructor(e){this.options=e||Vi}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?Ir.lex:Ir.lexInline}provideParser(){return this.block?Er.parse:Er.parseInline}},Lm=class{defaults=Im();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Er;Renderer=Zu;TextRenderer=$m;Lexer=Ir;Tokenizer=ju;Hooks=Hu;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let o of e)switch(n=n.concat(t.call(this,o)),o.type){case"table":{let i=o;for(let s of i.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of i.rows)for(let a of s)n=n.concat(this.walkTokens(a.tokens,t));break}case"list":{let i=o;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=o;if(this.defaults.extensions?.childTokens?.[i.type])this.defaults.extensions.childTokens[i.type].forEach((s)=>{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))});else if(i.tokens)n=n.concat(this.walkTokens(i.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((n)=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions)n.extensions.forEach((i)=>{if(!i.name)throw Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];if(s)t.renderers[i.name]=function(...a){let l=i.renderer.apply(this,a);if(l===!1)l=s.apply(this,a);return l};else t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let s=t[i.level];if(s)s.unshift(i.tokenizer);else t[i.level]=[i.tokenizer];if(i.start){if(i.level==="block")if(t.startBlock)t.startBlock.push(i.start);else t.startBlock=[i.start];else if(i.level==="inline")if(t.startInline)t.startInline.push(i.start);else t.startInline=[i.start]}}if("childTokens"in i&&i.childTokens)t.childTokens[i.name]=i.childTokens}),o.extensions=t;if(n.renderer){let i=this.defaults.renderer||new Zu(this.defaults);for(let s in n.renderer){if(!(s in i))throw Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,l=n.renderer[a],c=i[a];i[a]=(...u)=>{let d=l.apply(i,u);if(d===!1)d=c.apply(i,u);return d||""}}o.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new ju(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,l=n.tokenizer[a],c=i[a];i[a]=(...u)=>{let d=l.apply(i,u);if(d===!1)d=c.apply(i,u);return d}}o.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new Hu;for(let s in n.hooks){if(!(s in i))throw Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,l=n.hooks[a],c=i[a];if(Hu.passThroughHooks.has(s))i[a]=(u)=>{if(this.defaults.async)return Promise.resolve(l.call(i,u)).then((p)=>c.call(i,p));let d=l.call(i,u);return c.call(i,d)};else i[a]=(...u)=>{let d=l.apply(i,u);if(d===!1)d=c.apply(i,u);return d}}o.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;o.walkTokens=function(a){let l=[];if(l.push(s.call(this,a)),i)l=l.concat(i.call(this,a));return l}}this.defaults={...this.defaults,...o}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ir.lex(e,t??this.defaults)}parser(e,t){return Er.parse(e,t??this.defaults)}parseMarkdown(e){return(n,o)=>{let i={...o},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(Error("marked(): input parameter is undefined or null"));if(typeof n!=="string")return a(Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks)s.hooks.options=s,s.hooks.block=e;let l=s.hooks?s.hooks.provideLexer():e?Ir.lex:Ir.lexInline,c=s.hooks?s.hooks.provideParser():e?Er.parse:Er.parseInline;if(s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(n):n).then((u)=>l(u,s)).then((u)=>s.hooks?s.hooks.processAllTokens(u):u).then((u)=>s.walkTokens?Promise.all(this.walkTokens(u,s.walkTokens)).then(()=>u):u).then((u)=>c(u,s)).then((u)=>s.hooks?s.hooks.postprocess(u):u).catch(a);try{if(s.hooks)n=s.hooks.preprocess(n);let u=l(n,s);if(s.hooks)u=s.hooks.processAllTokens(u);if(s.walkTokens)this.walkTokens(u,s.walkTokens);let d=c(u,s);if(s.hooks)d=s.hooks.postprocess(d);return d}catch(u){return a(u)}}}onError(e,t){return(n)=>{if(n.message+=`
152
+ Please report this to https://github.com/markedjs/marked.`,e){let o="<p>An error occurred:</p><pre>"+Yo(n.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);return o}if(t)return Promise.reject(n);throw n}}},Ki=new Lm;function It(e,t){return Ki.parse(e,t)}It.options=It.setOptions=function(e){return Ki.setOptions(e),It.defaults=Ki.defaults,DS(It.defaults),It};It.getDefaults=Im;It.defaults=Vi;It.use=function(...e){return Ki.use(...e),It.defaults=Ki.defaults,DS(It.defaults),It};It.walkTokens=function(e,t){return Ki.walkTokens(e,t)};It.parseInline=Ki.parseInline;It.Parser=Er;It.parser=Er.parse;It.Renderer=Zu;It.TextRenderer=$m;It.Lexer=Ir;It.lexer=Ir.lex;It.Tokenizer=ju;It.Hooks=Hu;It.parse=It;var{options:vU,setOptions:bU,use:xU,walkTokens:wU,parseInline:kU}=It;var SU=Er.parse,_U=Ir.lex;var wl=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),VS=wl?"⌘":"Ctrl";function Ft(e){return wl?`${VS}${e}`:`${VS}+${e}`}function Gu(e,t){let{selectionStart:n,selectionEnd:o,value:i}=e,s=i.slice(n,o),a=i.slice(Math.max(0,n-t.length),n),l=i.slice(o,o+t.length);if(a===t&&l===t){let c=i.slice(0,n-t.length)+s+i.slice(o+t.length);Qo(e,c,n-t.length,o-t.length);return}if(s){let c=i.slice(0,n)+t+s+t+i.slice(o);Qo(e,c,n+t.length,o+t.length)}else{let c=i.slice(0,n)+t+t+i.slice(o);Qo(e,c,n+t.length,n+t.length)}}function kl(e,t){let{selectionStart:n,selectionEnd:o,value:i}=e,s=i.lastIndexOf(`
153
153
  `,n-1)+1,a=i.indexOf(`
154
154
  `,o),l=a===-1?i.length:a,c=i.slice(s,l);if(c.startsWith(t)){let d=i.slice(0,s)+c.slice(t.length)+i.slice(l);Qo(e,d,Math.max(s,n-t.length),Math.max(s,o-t.length));return}let u=i.slice(0,s)+t+i.slice(s);Qo(e,u,n+t.length,o+t.length)}function a1(e){let{selectionStart:t,selectionEnd:n,value:o}=e,i=o.slice(t,n);if(i){let s=o.slice(0,t)+`[${i}](url)`+o.slice(n),a=t+i.length+3;Qo(e,s,a,a+3)}else{let s=o.slice(0,t)+"[text](url)"+o.slice(n);Qo(e,s,t+1,t+5)}}function l1(e){let{selectionStart:t,selectionEnd:n,value:o}=e,i=o.slice(t,n),s="```";if(i){let a=o.slice(0,t)+`\`\`\`
155
155
  ${i}
156
- \`\`\``+o.slice(n);Qo(e,a,t+3+1,t+3+1+i.length)}else{let a=o.slice(0,t)+"```\n\n```"+o.slice(n);Qo(e,a,t+3+1,t+3+1)}}function JS(e,t){let{selectionStart:n,selectionEnd:o,value:i}=e,s=i.lastIndexOf(`
156
+ \`\`\``+o.slice(n);Qo(e,a,t+3+1,t+3+1+i.length)}else{let a=o.slice(0,t)+"```\n\n```"+o.slice(n);Qo(e,a,t+3+1,t+3+1)}}function XS(e,t){let{selectionStart:n,selectionEnd:o,value:i}=e,s=i.lastIndexOf(`
157
157
  `,n-1)+1,a=i.indexOf(`
158
158
  `,o),l=a===-1?i.length:a,c=i.slice(s,l).split(`
159
159
  `),u=n,d=o,p=c.map((m,h)=>{if(t){if(m.startsWith(" ")){if(h===0)u=Math.max(s,u-2);return d-=2,m.slice(2)}else if(m.startsWith("\t")){if(h===0)u=Math.max(s,u-1);return d-=1,m.slice(1)}return m}else{if(h===0)u+=2;return d+=2," "+m}}),f=i.slice(0,s)+p.join(`
160
- `)+i.slice(l);Qo(e,f,u,d)}function Qo(e,t,n,o){let i=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;if(i)i.call(e,t);else e.value=t;e.selectionStart=n,e.selectionEnd=o,e.dispatchEvent(new Event("input",{bubbles:!0}))}var Gu=[{key:"bold",label:"Bold",icon:"B",shortcut:"b",action:(e)=>qu(e,"**")},{key:"italic",label:"Italic",icon:"I",shortcut:"i",action:(e)=>qu(e,"_")},{key:"strike",label:"Strikethrough",icon:"S",shortcut:"u",action:(e)=>qu(e,"~~")},{key:"code",label:"Inline code",icon:"`",shortcut:"e",action:(e)=>qu(e,"`")},{key:"link",label:"Link",icon:"\uD83D\uDD17",shortcut:"k",action:a1},{key:"h1",label:"Heading 1",icon:"H1",action:(e)=>kl(e,"# ")},{key:"h2",label:"Heading 2",icon:"H2",action:(e)=>kl(e,"## ")},{key:"quote",label:"Blockquote",icon:"❝",action:(e)=>kl(e,"> ")},{key:"ul",label:"Bullet list",icon:"•",action:(e)=>kl(e,"- ")},{key:"ol",label:"Numbered list",icon:"1.",action:(e)=>kl(e,"1. ")},{key:"codeblock",label:"Code block",icon:"{ }",action:l1}];function YS(e,t){if(!(e.metaKey||e.ctrlKey))return!1;let n=Gu.find((o)=>o.shortcut===e.key);if(!n)return!1;return e.preventDefault(),n.action(t),!0}function QS(e){if(e.selectionStart===e.selectionEnd)return null;let t=document.createElement("div"),n=getComputedStyle(e),o=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","wordSpacing","textIndent","whiteSpace","wordWrap","overflowWrap","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","width"];for(let d of o)t.style[d]=n[d];t.style.position="absolute",t.style.visibility="hidden",t.style.overflow="hidden",t.style.height="auto",t.style.top="0",t.style.left="0";let i=e.value,s=document.createTextNode(i.slice(0,e.selectionStart)),a=document.createElement("span");a.textContent=i.slice(e.selectionStart,e.selectionEnd)||".",t.appendChild(s),t.appendChild(a),t.appendChild(document.createTextNode(i.slice(e.selectionEnd))),document.body.appendChild(t);let l=a.getBoundingClientRect(),c=t.getBoundingClientRect(),u=e.getBoundingClientRect();return document.body.removeChild(t),{top:u.top+(l.top-c.top)-e.scrollTop,left:u.left+(l.left-c.left)-e.scrollLeft,width:l.width}}var c1=Gu.filter((e)=>e.shortcut),u1=Gu.filter((e)=>!e.shortcut);function zm({textareaRef:e}){let[t,n]=E(!1),[o,i]=E({top:0,left:0}),s=D(null),a=D(null),l=oe(()=>{let u=e.current;if(!u||u.selectionStart===u.selectionEnd){n(!1);return}let d=QS(u);if(!d){n(!1);return}let p=380,f=Math.max(8,Math.min(d.left+d.width/2-p/2,window.innerWidth-p-8));i({top:d.top-40,left:f}),n(!0)},[e]);q(()=>{let u=e.current;if(!u)return;let d=()=>{if(a.current)clearTimeout(a.current);a.current=setTimeout(l,50)},p=()=>{a.current=setTimeout(()=>n(!1),200)},f=(m)=>{if(m.shiftKey||m.key.startsWith("Arrow"))d()};return u.addEventListener("select",d),u.addEventListener("mouseup",d),u.addEventListener("keyup",f),u.addEventListener("blur",p),()=>{if(u.removeEventListener("select",d),u.removeEventListener("mouseup",d),u.removeEventListener("keyup",f),u.removeEventListener("blur",p),a.current)clearTimeout(a.current)}},[e,l]);let c=oe((u)=>{let d=e.current;if(d)u.action(d),d.focus()},[e]);if(!t)return null;return r("div",{ref:s,class:"md-format-bar",style:{top:`${o.top}px`,left:`${o.left}px`},onMouseDown:(u)=>u.preventDefault(),children:[c1.map((u)=>r(_e,{label:u.label,shortcut:Ft(u.shortcut.toUpperCase()),children:r("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,"aria-label":u.label,onClick:()=>c(u),children:u.icon},void 0,!1,void 0,this)},u.key,!1,void 0,this)),r("div",{class:"md-format-divider"},void 0,!1,void 0,this),u1.map((u)=>r(_e,{label:u.label,children:r("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,"aria-label":u.label,onClick:()=>c(u),children:u.icon},void 0,!1,void 0,this)},u.key,!1,void 0,this))]},void 0,!0,void 0,this)}var X0=lE(h0(),1);function T1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o))e[o]=n[o]}return e}function Hm(e,t){return Array(t+1).join(e)}function v0(e){return e.replace(/^\n*/,"")}function b0(e){var t=e.length;while(t>0&&e[t-1]===`
161
- `)t--;return e.substring(0,t)}function x0(e){return b0(v0(e))}var I1=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function Um(e){return jm(e,I1)}var w0=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function k0(e){return jm(e,w0)}function E1(e){return _0(e,w0)}var S0=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function A1(e){return jm(e,S0)}function R1(e){return _0(e,S0)}function jm(e,t){return t.indexOf(e.nodeName)>=0}function _0(e,t){return e.getElementsByTagName&&t.some(function(n){return e.getElementsByTagName(n).length})}var P1=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function C0(e){return P1.reduce(function(t,n){return t.replace(n[0],n[1])},e)}var Dn={};Dn.paragraph={filter:"p",replacement:function(e){return`
160
+ `)+i.slice(l);Qo(e,f,u,d)}function Qo(e,t,n,o){let i=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;if(i)i.call(e,t);else e.value=t;e.selectionStart=n,e.selectionEnd=o,e.dispatchEvent(new Event("input",{bubbles:!0}))}var Ku=[{key:"bold",label:"Bold",icon:"B",shortcut:"b",action:(e)=>Gu(e,"**")},{key:"italic",label:"Italic",icon:"I",shortcut:"i",action:(e)=>Gu(e,"_")},{key:"strike",label:"Strikethrough",icon:"S",shortcut:"u",action:(e)=>Gu(e,"~~")},{key:"code",label:"Inline code",icon:"`",shortcut:"e",action:(e)=>Gu(e,"`")},{key:"link",label:"Link",icon:"\uD83D\uDD17",shortcut:"k",action:a1},{key:"h1",label:"Heading 1",icon:"H1",action:(e)=>kl(e,"# ")},{key:"h2",label:"Heading 2",icon:"H2",action:(e)=>kl(e,"## ")},{key:"quote",label:"Blockquote",icon:"❝",action:(e)=>kl(e,"> ")},{key:"ul",label:"Bullet list",icon:"•",action:(e)=>kl(e,"- ")},{key:"ol",label:"Numbered list",icon:"1.",action:(e)=>kl(e,"1. ")},{key:"codeblock",label:"Code block",icon:"{ }",action:l1}];function JS(e,t){if(!(e.metaKey||e.ctrlKey))return!1;let n=Ku.find((o)=>o.shortcut===e.key);if(!n)return!1;return e.preventDefault(),n.action(t),!0}function YS(e){if(e.selectionStart===e.selectionEnd)return null;let t=document.createElement("div"),n=getComputedStyle(e),o=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","wordSpacing","textIndent","whiteSpace","wordWrap","overflowWrap","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing","width"];for(let d of o)t.style[d]=n[d];t.style.position="absolute",t.style.visibility="hidden",t.style.overflow="hidden",t.style.height="auto",t.style.top="0",t.style.left="0";let i=e.value,s=document.createTextNode(i.slice(0,e.selectionStart)),a=document.createElement("span");a.textContent=i.slice(e.selectionStart,e.selectionEnd)||".",t.appendChild(s),t.appendChild(a),t.appendChild(document.createTextNode(i.slice(e.selectionEnd))),document.body.appendChild(t);let l=a.getBoundingClientRect(),c=t.getBoundingClientRect(),u=e.getBoundingClientRect();return document.body.removeChild(t),{top:u.top+(l.top-c.top)-e.scrollTop,left:u.left+(l.left-c.left)-e.scrollLeft,width:l.width}}var c1=Ku.filter((e)=>e.shortcut),u1=Ku.filter((e)=>!e.shortcut);function Om({textareaRef:e}){let[t,n]=E(!1),[o,i]=E({top:0,left:0}),s=D(null),a=D(null),l=oe(()=>{let u=e.current;if(!u||u.selectionStart===u.selectionEnd){n(!1);return}let d=YS(u);if(!d){n(!1);return}let p=380,f=Math.max(8,Math.min(d.left+d.width/2-p/2,window.innerWidth-p-8));i({top:d.top-40,left:f}),n(!0)},[e]);q(()=>{let u=e.current;if(!u)return;let d=()=>{if(a.current)clearTimeout(a.current);a.current=setTimeout(l,50)},p=()=>{a.current=setTimeout(()=>n(!1),200)},f=(m)=>{if(m.shiftKey||m.key.startsWith("Arrow"))d()};return u.addEventListener("select",d),u.addEventListener("mouseup",d),u.addEventListener("keyup",f),u.addEventListener("blur",p),()=>{if(u.removeEventListener("select",d),u.removeEventListener("mouseup",d),u.removeEventListener("keyup",f),u.removeEventListener("blur",p),a.current)clearTimeout(a.current)}},[e,l]);let c=oe((u)=>{let d=e.current;if(d)u.action(d),d.focus()},[e]);if(!t)return null;return r("div",{ref:s,class:"md-format-bar",style:{top:`${o.top}px`,left:`${o.left}px`},onMouseDown:(u)=>u.preventDefault(),children:[c1.map((u)=>r(_e,{label:u.label,shortcut:Ft(u.shortcut.toUpperCase()),children:r("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,"aria-label":u.label,onClick:()=>c(u),children:u.icon},void 0,!1,void 0,this)},u.key,!1,void 0,this)),r("div",{class:"md-format-divider"},void 0,!1,void 0,this),u1.map((u)=>r(_e,{label:u.label,children:r("button",{type:"button",class:`md-format-btn md-format-btn-${u.key}`,"aria-label":u.label,onClick:()=>c(u),children:u.icon},void 0,!1,void 0,this)},u.key,!1,void 0,this))]},void 0,!0,void 0,this)}var V0=lE(m0(),1);function T1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o))e[o]=n[o]}return e}function Zm(e,t){return Array(t+1).join(e)}function y0(e){return e.replace(/^\n*/,"")}function v0(e){var t=e.length;while(t>0&&e[t-1]===`
161
+ `)t--;return e.substring(0,t)}function b0(e){return v0(y0(e))}var I1=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function Wm(e){return qm(e,I1)}var x0=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function w0(e){return qm(e,x0)}function E1(e){return S0(e,x0)}var k0=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function A1(e){return qm(e,k0)}function R1(e){return S0(e,k0)}function qm(e,t){return t.indexOf(e.nodeName)>=0}function S0(e,t){return e.getElementsByTagName&&t.some(function(n){return e.getElementsByTagName(n).length})}var P1=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function _0(e){return P1.reduce(function(t,n){return t.replace(n[0],n[1])},e)}var Dn={};Dn.paragraph={filter:"p",replacement:function(e){return`
162
162
 
163
163
  `+e+`
164
164
 
165
165
  `}};Dn.lineBreak={filter:"br",replacement:function(e,t,n){return n.br+`
166
- `}};Dn.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(e,t,n){var o=Number(t.nodeName.charAt(1));if(n.headingStyle==="setext"&&o<3){var i=Hm(o===1?"=":"-",e.length);return`
166
+ `}};Dn.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(e,t,n){var o=Number(t.nodeName.charAt(1));if(n.headingStyle==="setext"&&o<3){var i=Zm(o===1?"=":"-",e.length);return`
167
167
 
168
168
  `+e+`
169
169
  `+i+`
170
170
 
171
171
  `}else return`
172
172
 
173
- `+Hm("#",o)+" "+e+`
173
+ `+Zm("#",o)+" "+e+`
174
174
 
175
- `}};Dn.blockquote={filter:"blockquote",replacement:function(e){return e=x0(e).replace(/^/gm,"> "),`
175
+ `}};Dn.blockquote={filter:"blockquote",replacement:function(e){return e=b0(e).replace(/^/gm,"> "),`
176
176
 
177
177
  `+e+`
178
178
 
@@ -181,7 +181,7 @@ ${i}
181
181
 
182
182
  `+e+`
183
183
 
184
- `}};Dn.listItem={filter:"li",replacement:function(e,t,n){var o=n.bulletListMarker+" ",i=t.parentNode;if(i.nodeName==="OL"){var s=i.getAttribute("start"),a=Array.prototype.indexOf.call(i.children,t);o=(s?Number(s)+a:a+1)+". "}var l=/\n$/.test(e);return e=x0(e)+(l?`
184
+ `}};Dn.listItem={filter:"li",replacement:function(e,t,n){var o=n.bulletListMarker+" ",i=t.parentNode;if(i.nodeName==="OL"){var s=i.getAttribute("start"),a=Array.prototype.indexOf.call(i.children,t);o=(s?Number(s)+a:a+1)+". "}var l=/\n$/.test(e);return e=b0(e)+(l?`
185
185
  `:""),e=e.replace(/\n/gm,`
186
186
  `+" ".repeat(o.length)),o+e+(t.nextSibling?`
187
187
  `:"")}};Dn.indentedCodeBlock={filter:function(e,t){return t.codeBlockStyle==="indented"&&e.nodeName==="PRE"&&e.firstChild&&e.firstChild.nodeName==="CODE"},replacement:function(e,t,n){return`
@@ -189,7 +189,7 @@ ${i}
189
189
  `+t.firstChild.textContent.replace(/\n/g,`
190
190
  `)+`
191
191
 
192
- `}};Dn.fencedCodeBlock={filter:function(e,t){return t.codeBlockStyle==="fenced"&&e.nodeName==="PRE"&&e.firstChild&&e.firstChild.nodeName==="CODE"},replacement:function(e,t,n){var o=t.firstChild.getAttribute("class")||"",i=(o.match(/language-(\S+)/)||[null,""])[1],s=t.firstChild.textContent,a=n.fence.charAt(0),l=3,c=new RegExp("^"+a+"{3,}","gm"),u;while(u=c.exec(s))if(u[0].length>=l)l=u[0].length+1;var d=Hm(a,l);return`
192
+ `}};Dn.fencedCodeBlock={filter:function(e,t){return t.codeBlockStyle==="fenced"&&e.nodeName==="PRE"&&e.firstChild&&e.firstChild.nodeName==="CODE"},replacement:function(e,t,n){var o=t.firstChild.getAttribute("class")||"",i=(o.match(/language-(\S+)/)||[null,""])[1],s=t.firstChild.textContent,a=n.fence.charAt(0),l=3,c=new RegExp("^"+a+"{3,}","gm"),u;while(u=c.exec(s))if(u[0].length>=l)l=u[0].length+1;var d=Zm(a,l);return`
193
193
 
194
194
  `+d+i+`
195
195
  `+s.replace(/\n$/,"")+`
@@ -199,13 +199,13 @@ ${i}
199
199
 
200
200
  `+n.hr+`
201
201
 
202
- `}};Dn.inlineLink={filter:function(e,t){return t.linkStyle==="inlined"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t){var n=Zm(t.getAttribute("href")),o=Wm(Ku(t.getAttribute("title"))),i=o?' "'+o+'"':"";return"["+e+"]("+n+i+")"}};Dn.referenceLink={filter:function(e,t){return t.linkStyle==="referenced"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t,n){var o=Zm(t.getAttribute("href")),i=Ku(t.getAttribute("title"));if(i)i=' "'+Wm(i)+'"';var s,a;switch(n.linkReferenceStyle){case"collapsed":s="["+e+"][]",a="["+e+"]: "+o+i;break;case"shortcut":s="["+e+"]",a="["+e+"]: "+o+i;break;default:var l=this.references.length+1;s="["+e+"]["+l+"]",a="["+l+"]: "+o+i}return this.references.push(a),s},references:[],append:function(e){var t="";if(this.references.length)t=`
202
+ `}};Dn.inlineLink={filter:function(e,t){return t.linkStyle==="inlined"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t){var n=Gm(t.getAttribute("href")),o=Km(Vu(t.getAttribute("title"))),i=o?' "'+o+'"':"";return"["+e+"]("+n+i+")"}};Dn.referenceLink={filter:function(e,t){return t.linkStyle==="referenced"&&e.nodeName==="A"&&e.getAttribute("href")},replacement:function(e,t,n){var o=Gm(t.getAttribute("href")),i=Vu(t.getAttribute("title"));if(i)i=' "'+Km(i)+'"';var s,a;switch(n.linkReferenceStyle){case"collapsed":s="["+e+"][]",a="["+e+"]: "+o+i;break;case"shortcut":s="["+e+"]",a="["+e+"]: "+o+i;break;default:var l=this.references.length+1;s="["+e+"]["+l+"]",a="["+l+"]: "+o+i}return this.references.push(a),s},references:[],append:function(e){var t="";if(this.references.length)t=`
203
203
 
204
204
  `+this.references.join(`
205
205
  `)+`
206
206
 
207
- `,this.references=[];return t}};Dn.emphasis={filter:["em","i"],replacement:function(e,t,n){if(!e.trim())return"";return n.emDelimiter+e+n.emDelimiter}};Dn.strong={filter:["strong","b"],replacement:function(e,t,n){if(!e.trim())return"";return n.strongDelimiter+e+n.strongDelimiter}};Dn.code={filter:function(e){var t=e.previousSibling||e.nextSibling,n=e.parentNode.nodeName==="PRE"&&!t;return e.nodeName==="CODE"&&!n},replacement:function(e){if(!e)return"";e=e.replace(/\r?\n|\r/g," ");var t=/^`|^ .*?[^ ].* $|`$/.test(e)?" ":"",n="`",o=e.match(/`+/gm)||[];while(o.indexOf(n)!==-1)n=n+"`";return n+t+e+t+n}};Dn.image={filter:"img",replacement:function(e,t){var n=C0(Ku(t.getAttribute("alt"))),o=Zm(t.getAttribute("src")||""),i=Ku(t.getAttribute("title")),s=i?' "'+Wm(i)+'"':"";return o?"!["+n+"]("+o+s+")":""}};function Ku(e){return e?e.replace(/(\n+\s*)+/g,`
208
- `):""}function Zm(e){var t=e.replace(/([<>()])/g,"\\$1");return t.indexOf(" ")>=0?"<"+t+">":t}function Wm(e){return e.replace(/"/g,"\\\"")}function T0(e){this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[];for(var t in e.rules)this.array.push(e.rules[t])}T0.prototype={add:function(e,t){this.array.unshift(t)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return""}})},forNode:function(e){if(e.isBlank)return this.blankRule;var t;if(t=Dm(this.array,e,this.options))return t;if(t=Dm(this._keep,e,this.options))return t;if(t=Dm(this._remove,e,this.options))return t;return this.defaultRule},forEach:function(e){for(var t=0;t<this.array.length;t++)e(this.array[t],t)}};function Dm(e,t,n){for(var o=0;o<e.length;o++){var i=e[o];if(N1(i,t,n))return i}return}function N1(e,t,n){var o=e.filter;if(typeof o==="string"){if(o===t.nodeName.toLowerCase())return!0}else if(Array.isArray(o)){if(o.indexOf(t.nodeName.toLowerCase())>-1)return!0}else if(typeof o==="function"){if(o.call(e,t,n))return!0}else throw TypeError("`filter` needs to be a string, array, or function")}function M1(e){var{element:t,isBlock:n,isVoid:o}=e,i=e.isPre||function(p){return p.nodeName==="PRE"};if(!t.firstChild||i(t))return;var s=null,a=!1,l=null,c=g0(l,t,i);while(c!==t){if(c.nodeType===3||c.nodeType===4){var u=c.data.replace(/[ \r\n\t]+/g," ");if((!s||/ $/.test(s.data))&&!a&&u[0]===" ")u=u.substr(1);if(!u){c=Bm(c);continue}c.data=u,s=c}else if(c.nodeType===1){if(n(c)||c.nodeName==="BR"){if(s)s.data=s.data.replace(/ $/,"");s=null,a=!1}else if(o(c)||i(c))s=null,a=!0;else if(s)a=!1}else{c=Bm(c);continue}var d=g0(l,c,i);l=c,c=d}if(s){if(s.data=s.data.replace(/ $/,""),!s.data)Bm(s)}}function Bm(e){var t=e.nextSibling||e.parentNode;return e.parentNode.removeChild(e),t}function g0(e,t,n){if(e&&e.parentNode===t||n(t))return t.nextSibling||t.parentNode;return t.firstChild||t.nextSibling||t.parentNode}var qm=typeof window<"u"?window:{};function z1(){var e=qm.DOMParser,t=!1;try{if(new e().parseFromString("","text/html"))t=!0}catch(n){}return t}function $1(){var e=function(){};if(L1())e.prototype.parseFromString=function(t){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(t),n.close(),n};else e.prototype.parseFromString=function(t){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(t),n.close(),n};return e}function L1(){var e=!1;try{document.implementation.createHTMLDocument("").open()}catch(t){if(qm.ActiveXObject)e=!0}return e}var O1=z1()?qm.DOMParser:$1();function D1(e,t){var n;if(typeof e==="string"){var o=B1().parseFromString('<x-turndown id="turndown-root">'+e+"</x-turndown>","text/html");n=o.getElementById("turndown-root")}else n=e.cloneNode(!0);return M1({element:n,isBlock:Um,isVoid:k0,isPre:t.preformattedCode?F1:null}),n}var Fm;function B1(){return Fm=Fm||new O1,Fm}function F1(e){return e.nodeName==="PRE"||e.nodeName==="CODE"}function H1(e,t){return e.isBlock=Um(e),e.isCode=e.nodeName==="CODE"||e.parentNode.isCode,e.isBlank=U1(e),e.flankingWhitespace=j1(e,t),e}function U1(e){return!k0(e)&&!A1(e)&&/^\s*$/i.test(e.textContent)&&!E1(e)&&!R1(e)}function j1(e,t){if(e.isBlock||t.preformattedCode&&e.isCode)return{leading:"",trailing:""};var n=Z1(e.textContent);if(n.leadingAscii&&y0("left",e,t))n.leading=n.leadingNonAscii;if(n.trailingAscii&&y0("right",e,t))n.trailing=n.trailingNonAscii;return{leading:n.leading,trailing:n.trailing}}function Z1(e){var t=e.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:t[1],leadingAscii:t[2],leadingNonAscii:t[3],trailing:t[4],trailingNonAscii:t[5],trailingAscii:t[6]}}function y0(e,t,n){var o,i,s;if(e==="left")o=t.previousSibling,i=/ $/;else o=t.nextSibling,i=/^ /;if(o){if(o.nodeType===3)s=i.test(o.nodeValue);else if(n.preformattedCode&&o.nodeName==="CODE")s=!1;else if(o.nodeType===1&&!Um(o))s=i.test(o.textContent)}return s}var W1=Array.prototype.reduce;function Sl(e){if(!(this instanceof Sl))return new Sl(e);var t={rules:Dn,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(n,o){return o.isBlock?`
207
+ `,this.references=[];return t}};Dn.emphasis={filter:["em","i"],replacement:function(e,t,n){if(!e.trim())return"";return n.emDelimiter+e+n.emDelimiter}};Dn.strong={filter:["strong","b"],replacement:function(e,t,n){if(!e.trim())return"";return n.strongDelimiter+e+n.strongDelimiter}};Dn.code={filter:function(e){var t=e.previousSibling||e.nextSibling,n=e.parentNode.nodeName==="PRE"&&!t;return e.nodeName==="CODE"&&!n},replacement:function(e){if(!e)return"";e=e.replace(/\r?\n|\r/g," ");var t=/^`|^ .*?[^ ].* $|`$/.test(e)?" ":"",n="`",o=e.match(/`+/gm)||[];while(o.indexOf(n)!==-1)n=n+"`";return n+t+e+t+n}};Dn.image={filter:"img",replacement:function(e,t){var n=_0(Vu(t.getAttribute("alt"))),o=Gm(t.getAttribute("src")||""),i=Vu(t.getAttribute("title")),s=i?' "'+Km(i)+'"':"";return o?"!["+n+"]("+o+s+")":""}};function Vu(e){return e?e.replace(/(\n+\s*)+/g,`
208
+ `):""}function Gm(e){var t=e.replace(/([<>()])/g,"\\$1");return t.indexOf(" ")>=0?"<"+t+">":t}function Km(e){return e.replace(/"/g,"\\\"")}function C0(e){this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[];for(var t in e.rules)this.array.push(e.rules[t])}C0.prototype={add:function(e,t){this.array.unshift(t)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return""}})},forNode:function(e){if(e.isBlank)return this.blankRule;var t;if(t=Hm(this.array,e,this.options))return t;if(t=Hm(this._keep,e,this.options))return t;if(t=Hm(this._remove,e,this.options))return t;return this.defaultRule},forEach:function(e){for(var t=0;t<this.array.length;t++)e(this.array[t],t)}};function Hm(e,t,n){for(var o=0;o<e.length;o++){var i=e[o];if(N1(i,t,n))return i}return}function N1(e,t,n){var o=e.filter;if(typeof o==="string"){if(o===t.nodeName.toLowerCase())return!0}else if(Array.isArray(o)){if(o.indexOf(t.nodeName.toLowerCase())>-1)return!0}else if(typeof o==="function"){if(o.call(e,t,n))return!0}else throw TypeError("`filter` needs to be a string, array, or function")}function M1(e){var{element:t,isBlock:n,isVoid:o}=e,i=e.isPre||function(p){return p.nodeName==="PRE"};if(!t.firstChild||i(t))return;var s=null,a=!1,l=null,c=h0(l,t,i);while(c!==t){if(c.nodeType===3||c.nodeType===4){var u=c.data.replace(/[ \r\n\t]+/g," ");if((!s||/ $/.test(s.data))&&!a&&u[0]===" ")u=u.substr(1);if(!u){c=Um(c);continue}c.data=u,s=c}else if(c.nodeType===1){if(n(c)||c.nodeName==="BR"){if(s)s.data=s.data.replace(/ $/,"");s=null,a=!1}else if(o(c)||i(c))s=null,a=!0;else if(s)a=!1}else{c=Um(c);continue}var d=h0(l,c,i);l=c,c=d}if(s){if(s.data=s.data.replace(/ $/,""),!s.data)Um(s)}}function Um(e){var t=e.nextSibling||e.parentNode;return e.parentNode.removeChild(e),t}function h0(e,t,n){if(e&&e.parentNode===t||n(t))return t.nextSibling||t.parentNode;return t.firstChild||t.nextSibling||t.parentNode}var Vm=typeof window<"u"?window:{};function z1(){var e=Vm.DOMParser,t=!1;try{if(new e().parseFromString("","text/html"))t=!0}catch(n){}return t}function $1(){var e=function(){};if(L1())e.prototype.parseFromString=function(t){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(t),n.close(),n};else e.prototype.parseFromString=function(t){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(t),n.close(),n};return e}function L1(){var e=!1;try{document.implementation.createHTMLDocument("").open()}catch(t){if(Vm.ActiveXObject)e=!0}return e}var O1=z1()?Vm.DOMParser:$1();function D1(e,t){var n;if(typeof e==="string"){var o=B1().parseFromString('<x-turndown id="turndown-root">'+e+"</x-turndown>","text/html");n=o.getElementById("turndown-root")}else n=e.cloneNode(!0);return M1({element:n,isBlock:Wm,isVoid:w0,isPre:t.preformattedCode?F1:null}),n}var jm;function B1(){return jm=jm||new O1,jm}function F1(e){return e.nodeName==="PRE"||e.nodeName==="CODE"}function H1(e,t){return e.isBlock=Wm(e),e.isCode=e.nodeName==="CODE"||e.parentNode.isCode,e.isBlank=U1(e),e.flankingWhitespace=j1(e,t),e}function U1(e){return!w0(e)&&!A1(e)&&/^\s*$/i.test(e.textContent)&&!E1(e)&&!R1(e)}function j1(e,t){if(e.isBlock||t.preformattedCode&&e.isCode)return{leading:"",trailing:""};var n=Z1(e.textContent);if(n.leadingAscii&&g0("left",e,t))n.leading=n.leadingNonAscii;if(n.trailingAscii&&g0("right",e,t))n.trailing=n.trailingNonAscii;return{leading:n.leading,trailing:n.trailing}}function Z1(e){var t=e.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:t[1],leadingAscii:t[2],leadingNonAscii:t[3],trailing:t[4],trailingNonAscii:t[5],trailingAscii:t[6]}}function g0(e,t,n){var o,i,s;if(e==="left")o=t.previousSibling,i=/ $/;else o=t.nextSibling,i=/^ /;if(o){if(o.nodeType===3)s=i.test(o.nodeValue);else if(n.preformattedCode&&o.nodeName==="CODE")s=!1;else if(o.nodeType===1&&!Wm(o))s=i.test(o.textContent)}return s}var W1=Array.prototype.reduce;function Sl(e){if(!(this instanceof Sl))return new Sl(e);var t={rules:Dn,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(n,o){return o.isBlock?`
209
209
 
210
210
  `:""},keepReplacement:function(n,o){return o.isBlock?`
211
211
 
@@ -215,17 +215,17 @@ ${i}
215
215
 
216
216
  `+n+`
217
217
 
218
- `:n}};this.options=T1({},t,e),this.rules=new T0(this.options)}Sl.prototype={turndown:function(e){if(!K1(e))throw TypeError(e+" is not a string, or an element/document/fragment node.");if(e==="")return"";var t=I0.call(this,new D1(e,this.options));return q1.call(this,t)},use:function(e){if(Array.isArray(e))for(var t=0;t<e.length;t++)this.use(e[t]);else if(typeof e==="function")e(this);else throw TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(e,t){return this.rules.add(e,t),this},keep:function(e){return this.rules.keep(e),this},remove:function(e){return this.rules.remove(e),this},escape:function(e){return C0(e)}};function I0(e){var t=this;return W1.call(e.childNodes,function(n,o){o=new H1(o,t.options);var i="";if(o.nodeType===3)i=o.isCode?o.nodeValue:t.escape(o.nodeValue);else if(o.nodeType===1)i=G1.call(t,o);return E0(n,i)},"")}function q1(e){var t=this;return this.rules.forEach(function(n){if(typeof n.append==="function")e=E0(e,n.append(t.options))}),e.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function G1(e){var t=this.rules.forNode(e),n=I0.call(this,e),o=e.flankingWhitespace;if(o.leading||o.trailing)n=n.trim();return o.leading+t.replacement(n,e,this.options)+o.trailing}function E0(e,t){var n=b0(e),o=v0(t),i=Math.max(e.length-n.length,t.length-o.length),s=`
218
+ `:n}};this.options=T1({},t,e),this.rules=new C0(this.options)}Sl.prototype={turndown:function(e){if(!K1(e))throw TypeError(e+" is not a string, or an element/document/fragment node.");if(e==="")return"";var t=T0.call(this,new D1(e,this.options));return q1.call(this,t)},use:function(e){if(Array.isArray(e))for(var t=0;t<e.length;t++)this.use(e[t]);else if(typeof e==="function")e(this);else throw TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(e,t){return this.rules.add(e,t),this},keep:function(e){return this.rules.keep(e),this},remove:function(e){return this.rules.remove(e),this},escape:function(e){return _0(e)}};function T0(e){var t=this;return W1.call(e.childNodes,function(n,o){o=new H1(o,t.options);var i="";if(o.nodeType===3)i=o.isCode?o.nodeValue:t.escape(o.nodeValue);else if(o.nodeType===1)i=G1.call(t,o);return I0(n,i)},"")}function q1(e){var t=this;return this.rules.forEach(function(n){if(typeof n.append==="function")e=I0(e,n.append(t.options))}),e.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function G1(e){var t=this.rules.forNode(e),n=T0.call(this,e),o=e.flankingWhitespace;if(o.leading||o.trailing)n=n.trim();return o.leading+t.replacement(n,e,this.options)+o.trailing}function I0(e,t){var n=v0(e),o=y0(t),i=Math.max(e.length-n.length,t.length-o.length),s=`
219
219
 
220
- `.substring(0,i);return n+s+o}function K1(e){return e!=null&&(typeof e==="string"||e.nodeType&&(e.nodeType===1||e.nodeType===9||e.nodeType===11))}function Vu(){let e=window.getSelection(),t=e&&e.rangeCount>0?e.getRangeAt(0).cloneRange():null;On("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 i=window.getSelection();i?.removeAllRanges(),i?.addRange(t)}document.execCommand("createLink",!1,n)})}function A0(){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 i=document.createRange();i.setStartAfter(o),i.setEndAfter(o),e.removeAllRanges(),e.addRange(i)}var Xu=8,V1=[{kind:"exec",command:"bold",icon:"B",title:`Bold (${Ft("B")})`},{kind:"exec",command:"italic",icon:"I",title:`Italic (${Ft("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 (${Ft("K")})`,dividerBefore:!0}];function X1(e){switch(e.kind){case"exec":document.execCommand(e.command);return;case"block":document.execCommand("formatBlock",!1,e.tag);return;case"code":A0();return;case"link":Vu();return}}function R0({hostRef:e,onChange:t}){let[n,o]=E(!1),[i,s]=E({top:0,left:0}),[a,l]=E(0),c=D(null),u=D(null),d=oe(()=>{let m=e.current;if(!m){o(!1);return}let h=window.getSelection();if(!h||h.rangeCount===0||h.isCollapsed){o(!1);return}let g=h.getRangeAt(0);if(!m.contains(g.commonAncestorContainer)){o(!1);return}let v=g.getBoundingClientRect();if(v.width===0&&v.height===0){o(!1);return}let b=a||420,x=Math.max(Xu,Math.min(v.left+v.width/2-b/2,window.innerWidth-b-Xu)),C=Math.max(Xu,v.top-Xu-36);s({top:C,left:x}),o(!0)},[e,a]),p=oe(()=>{if(u.current!==null)return;u.current=requestAnimationFrame(()=>{u.current=null,d()})},[d]);q(()=>(document.addEventListener("selectionchange",p),window.addEventListener("scroll",p,!0),window.addEventListener("resize",p),()=>{if(document.removeEventListener("selectionchange",p),window.removeEventListener("scroll",p,!0),window.removeEventListener("resize",p),u.current!==null)cancelAnimationFrame(u.current)}),[p]),Me(()=>{if(!n)return;let m=c.current;if(!m)return;let h=m.getBoundingClientRect().width;if(h&&Math.abs(h-a)>1)l(h)},[n,a]);let f=oe((m)=>{X1(m),t(),d()},[t,d]);if(!n)return null;return r("div",{ref:c,class:"md-inline-format-bar",style:{top:`${i.top}px`,left:`${i.left}px`},onMouseDown:(m)=>m.preventDefault(),children:V1.flatMap((m,h)=>{let g=r(_e,{label:m.title,children:r("button",{type:"button",class:"md-inline-format-btn","aria-label":m.title,onClick:()=>f(m),children:m.icon},void 0,!1,void 0,this)},`btn-${h}`,!1,void 0,this);return m.dividerBefore?[r("span",{class:"md-inline-format-divider"},`div-${h}`,!1,void 0,this),g]:[g]})},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 P0(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 J1(e){if(Array.isArray(e))return e}function Y1(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var o,i,s,a,l=[],c=!0,u=!1;try{if(s=(n=n.call(e)).next,t===0);else for(;!(c=(o=s.call(n)).done)&&(l.push(o.value),l.length!==t);c=!0);}catch(d){u=!0,i=d}finally{try{if(!c&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return l}}function Q1(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
221
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function eN(e,t){return J1(e)||Y1(e,t)||tN(e,t)||Q1()}function tN(e,t){if(e){if(typeof e=="string")return P0(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)?P0(e,t):void 0}}var{entries:q0,setPrototypeOf:N0,isFrozen:nN,getPrototypeOf:oN,getOwnPropertyDescriptor:rN,freeze:Cn,seal:Tn,create:Ks}=Object,G0=typeof Reflect<"u"&&Reflect,{apply:Ym,construct:Qm}=G0;if(!Cn)Cn=function(t){return t};if(!Tn)Tn=function(t){return t};if(!Ym)Ym=function(t,n){for(var o=arguments.length,i=Array(o>2?o-2:0),s=2;s<o;s++)i[s-2]=arguments[s];return t.apply(n,i)};if(!Qm)Qm=function(t){for(var n=arguments.length,o=Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return new t(...o)};var qs=nn(Array.prototype.forEach),iN=nn(Array.prototype.lastIndexOf),M0=nn(Array.prototype.pop),Gs=nn(Array.prototype.push),sN=nn(Array.prototype.splice),li=Array.isArray,Tl=nn(String.prototype.toLowerCase),Gm=nn(String.prototype.toString),z0=nn(String.prototype.match),_l=nn(String.prototype.replace),$0=nn(String.prototype.indexOf),aN=nn(String.prototype.trim),lN=nn(Number.prototype.toString),cN=nn(Boolean.prototype.toString),L0=typeof BigInt>"u"?null:nn(BigInt.prototype.toString),O0=typeof Symbol>"u"?null:nn(Symbol.prototype.toString),yn=nn(Object.prototype.hasOwnProperty),Cl=nn(Object.prototype.toString),gn=nn(RegExp.prototype.test),Xi=uN(TypeError);function nn(e){return function(t){if(t instanceof RegExp)t.lastIndex=0;for(var n=arguments.length,o=Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return Ym(e,t,o)}}function uN(e){return function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];return Qm(e,n)}}function at(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Tl;if(N0)N0(e,null);if(!li(t))return e;let o=t.length;while(o--){let i=t[o];if(typeof i==="string"){let s=n(i);if(s!==i){if(!nN(t))t[o]=s;i=s}}e[i]=!0}return e}function dN(e){for(let t=0;t<e.length;t++)if(!yn(e,t))e[t]=null;return e}function Bn(e){let t=Ks(null);for(let o of q0(e)){var n=eN(o,2);let i=n[0],s=n[1];if(yn(e,i))if(li(s))t[i]=dN(s);else if(s&&typeof s==="object"&&s.constructor===Object)t[i]=Bn(s);else t[i]=s}return t}function pN(e){switch(typeof e){case"string":return e;case"number":return lN(e);case"boolean":return cN(e);case"bigint":return L0?L0(e):"0";case"symbol":return O0?O0(e):"Symbol()";case"undefined":return Cl(e);case"function":case"object":{if(e===null)return Cl(e);let t=e,n=Ho(t,"toString");if(typeof n==="function"){let o=n(t);return typeof o==="string"?o:Cl(o)}return Cl(e)}default:return Cl(e)}}function Ho(e,t){while(e!==null){let o=rN(e,t);if(o){if(o.get)return nn(o.get);if(typeof o.value==="function")return nn(o.value)}e=oN(e)}function n(){return null}return n}function fN(e){try{return gn(e,""),!0}catch(t){return!1}}var D0=Cn(["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"]),Km=Cn(["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"]),Vm=Cn(["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"]),mN=Cn(["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"]),Xm=Cn(["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"]),hN=Cn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),B0=Cn(["#text"]),F0=Cn(["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"]),Jm=Cn(["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"]),H0=Cn(["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"]),Ju=Cn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),gN=Tn(/{{[\w\W]*|^[\w\W]*}}/g),yN=Tn(/<%[\w\W]*|^[\w\W]*%>/g),vN=Tn(/\${[\w\W]*/g),bN=Tn(/^data-[\-\w.\u00B7-\uFFFF]+$/),xN=Tn(/^aria-[\-\w]+$/),U0=Tn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),wN=Tn(/^(?:\w+script|data):/i),kN=Tn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),SN=Tn(/^html$/i),_N=Tn(/^[a-z][.\w]*(-[.\w]+)+$/i),j0=Tn(/<[/\w!]/g),Z0=Tn(/<[/\w]/g),CN=Tn(/<\/no(script|embed|frames)/i),TN=Tn(/\/>/i),po={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},IN=function(){return typeof window>"u"?null:window},EN=function(t,n){if(typeof t!=="object"||typeof t.createPolicy!=="function")return null;let o=null,i="data-tt-policy-suffix";if(n&&n.hasAttribute(i))o=n.getAttribute(i);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}},W0=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},ai=function(t,n,o,i){return yn(t,n)&&li(t[n])?at(i.base?Bn(i.base):{},t[n],i.transform):o};function K0(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:IN(),t=(me)=>K0(me);if(t.version="3.4.13",t.removed=[],!e||!e.document||e.document.nodeType!==po.document||!e.Element)return t.isSupported=!1,t;let n=e.document,o=n,i=o.currentScript;e.DocumentFragment;let{HTMLTemplateElement:s,Node:a,Element:l,NodeFilter:c,NamedNodeMap:u}=e;u===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let{DOMParser:d,trustedTypes:p}=e,f=l.prototype,m=Ho(f,"cloneNode"),h=Ho(f,"remove"),g=Ho(f,"nextSibling"),v=Ho(f,"childNodes"),b=Ho(f,"parentNode"),x=Ho(f,"shadowRoot"),C=Ho(f,"attributes"),y=a&&a.prototype?Ho(a.prototype,"nodeType"):null,k=a&&a.prototype?Ho(a.prototype,"nodeName"):null,_=a&&a.prototype?Ho(a.prototype,"ownerDocument"):null;if(typeof s==="function"){let me=n.createElement("template");if(me.content&&me.content.ownerDocument)n=me.content.ownerDocument}let I,w="",P,L=!1,N=0,Y=function(){if(N>0)throw Xi('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.')},B=function(T){Y(),N++;try{return I.createHTML(T)}finally{N--}},J=function(T){Y(),N++;try{return I.createScriptURL(T)}finally{N--}},X=function(){if(!L)P=EN(p,i),L=!0;return P},V=n,{implementation:ee,createNodeIterator:he,createDocumentFragment:A,getElementsByTagName:te}=V,M=o.importNode,O=W0();t.isSupported=typeof q0==="function"&&typeof b==="function"&&ee&&ee.createHTMLDocument!==void 0;let Pe=gN,Fe=yN,De=vN,Ae=bN,ve=xN,z=wN,re=kN,Ne=_N,ke=U0,ae=null,Se=at({},[...D0,...Km,...Vm,...Xm,...B0]),pe=null,Ue=at({},[...F0,...Jm,...H0,...Ju]),xe=Object.seal(Ks(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}})),qe=null,W=null,ye=Object.seal(Ks(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),He=!0,R=!0,ne=!1,Ce=!0,Ie=!1,fe=!0,it=!1,Ht=!1,Ye=null,Lt=null,F=!1,Ee=!1,S=!1,K=!1,ue=!0,$e=!1,je="user-content-",le=!0,we=!1,ge={},Le=null,Rt=at({},["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"]),pt=null,pn=at({},["audio","video","img","source","image","track"]),on=null,fs=at({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Pn="http://www.w3.org/1998/Math/MathML",xn="http://www.w3.org/2000/svg",fn="http://www.w3.org/1999/xhtml",cr=fn,ms=!1,ft=null,Ca=at({},[Pn,xn,fn],Gm),Ta=Cn(["mi","mo","mn","ms","mtext"]),ot=at({},Ta),Ot=Cn(["annotation-xml"]),Hn=at({},Ot),Lr=at({},["title","style","font","a","script"]),ur=null,cc=["application/xhtml+xml","text/html"],uc="text/html",Ut=null,hs=null,ZI=n.createElement("form"),Dg=function(T){return T instanceof RegExp||T instanceof Function},vp=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(hs&&hs===T)return;if(!T||typeof T!=="object")T={};T=Bn(T),ur=cc.indexOf(T.PARSER_MEDIA_TYPE)===-1?uc:T.PARSER_MEDIA_TYPE,Ut=ur==="application/xhtml+xml"?Gm:Tl,ae=ai(T,"ALLOWED_TAGS",Se,{transform:Ut}),pe=ai(T,"ALLOWED_ATTR",Ue,{transform:Ut}),ft=ai(T,"ALLOWED_NAMESPACES",Ca,{transform:Gm}),on=ai(T,"ADD_URI_SAFE_ATTR",fs,{transform:Ut,base:fs}),pt=ai(T,"ADD_DATA_URI_TAGS",pn,{transform:Ut,base:pn}),Le=ai(T,"FORBID_CONTENTS",Rt,{transform:Ut}),qe=ai(T,"FORBID_TAGS",Bn({}),{transform:Ut}),W=ai(T,"FORBID_ATTR",Bn({}),{transform:Ut}),ge=yn(T,"USE_PROFILES")?T.USE_PROFILES&&typeof T.USE_PROFILES==="object"?Bn(T.USE_PROFILES):T.USE_PROFILES:!1,He=T.ALLOW_ARIA_ATTR!==!1,R=T.ALLOW_DATA_ATTR!==!1,ne=T.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ie=T.SAFE_FOR_TEMPLATES||!1,fe=T.SAFE_FOR_XML!==!1,it=T.WHOLE_DOCUMENT||!1,Ee=T.RETURN_DOM||!1,S=T.RETURN_DOM_FRAGMENT||!1,K=T.RETURN_TRUSTED_TYPE||!1,F=T.FORCE_BODY||!1,ue=T.SANITIZE_DOM!==!1,$e=T.SANITIZE_NAMED_PROPS||!1,le=T.KEEP_CONTENT!==!1,we=T.IN_PLACE||!1,ke=fN(T.ALLOWED_URI_REGEXP)?T.ALLOWED_URI_REGEXP:U0,cr=typeof T.NAMESPACE==="string"?T.NAMESPACE:fn,ot=yn(T,"MATHML_TEXT_INTEGRATION_POINTS")&&T.MATHML_TEXT_INTEGRATION_POINTS&&typeof T.MATHML_TEXT_INTEGRATION_POINTS==="object"?Bn(T.MATHML_TEXT_INTEGRATION_POINTS):at({},Ta),Hn=yn(T,"HTML_INTEGRATION_POINTS")&&T.HTML_INTEGRATION_POINTS&&typeof T.HTML_INTEGRATION_POINTS==="object"?Bn(T.HTML_INTEGRATION_POINTS):at({},Ot);let Z=yn(T,"CUSTOM_ELEMENT_HANDLING")&&T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING==="object"?Bn(T.CUSTOM_ELEMENT_HANDLING):Ks(null);if(xe=Ks(null),yn(Z,"tagNameCheck")&&Dg(Z.tagNameCheck))xe.tagNameCheck=Z.tagNameCheck;if(yn(Z,"attributeNameCheck")&&Dg(Z.attributeNameCheck))xe.attributeNameCheck=Z.attributeNameCheck;if(yn(Z,"allowCustomizedBuiltInElements")&&typeof Z.allowCustomizedBuiltInElements==="boolean")xe.allowCustomizedBuiltInElements=Z.allowCustomizedBuiltInElements;if(Tn(xe),Ie)R=!1;if(S)Ee=!0;if(ge){if(ae=at({},B0),pe=Ks(null),ge.html===!0)at(ae,D0),at(pe,F0);if(ge.svg===!0)at(ae,Km),at(pe,Jm),at(pe,Ju);if(ge.svgFilters===!0)at(ae,Vm),at(pe,Jm),at(pe,Ju);if(ge.mathMl===!0)at(ae,Xm),at(pe,H0),at(pe,Ju)}if(ye.tagCheck=null,ye.attributeCheck=null,yn(T,"ADD_TAGS")){if(typeof T.ADD_TAGS==="function")ye.tagCheck=T.ADD_TAGS;else if(li(T.ADD_TAGS)){if(ae===Se)ae=Bn(ae);at(ae,T.ADD_TAGS,Ut)}}if(yn(T,"ADD_ATTR")){if(typeof T.ADD_ATTR==="function")ye.attributeCheck=T.ADD_ATTR;else if(li(T.ADD_ATTR)){if(pe===Ue)pe=Bn(pe);at(pe,T.ADD_ATTR,Ut)}}if(yn(T,"ADD_URI_SAFE_ATTR")&&li(T.ADD_URI_SAFE_ATTR))at(on,T.ADD_URI_SAFE_ATTR,Ut);if(yn(T,"FORBID_CONTENTS")&&li(T.FORBID_CONTENTS)){if(Le===Rt)Le=Bn(Le);at(Le,T.FORBID_CONTENTS,Ut)}if(yn(T,"ADD_FORBID_CONTENTS")&&li(T.ADD_FORBID_CONTENTS)){if(Le===Rt)Le=Bn(Le);at(Le,T.ADD_FORBID_CONTENTS,Ut)}if(le)ae["#text"]=!0;if(it)at(ae,["html","head","body"]);if(ae.table)at(ae,["tbody"]),delete qe.tbody;if(T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!=="function")throw Xi('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!=="function")throw Xi('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let ce=I;I=T.TRUSTED_TYPES_POLICY;try{w=B("")}catch(ze){throw I=ce,ze}}else if(T.TRUSTED_TYPES_POLICY===null)I=void 0,w="";else{if(I===void 0)I=X();if(I&&typeof w==="string")w=B("")}if(Cn)Cn(T);hs=T},Bg=at({},[...Km,...Vm,...mN]),Fg=at({},[...Xm,...hN]),WI=function(T,Z,ce){if(Z.namespaceURI===fn)return T==="svg";if(Z.namespaceURI===Pn)return T==="svg"&&(ce==="annotation-xml"||ot[ce]);return Boolean(Bg[T])},qI=function(T,Z,ce){if(Z.namespaceURI===fn)return T==="math";if(Z.namespaceURI===xn)return T==="math"&&Hn[ce];return Boolean(Fg[T])},GI=function(T,Z,ce){if(Z.namespaceURI===xn&&!Hn[ce])return!1;if(Z.namespaceURI===Pn&&!ot[ce])return!1;return!Fg[T]&&(Lr[T]||!Bg[T])},KI=function(T){let Z=b(T);if(!Z||!Z.tagName)Z={namespaceURI:cr,tagName:"template"};let ce=Tl(T.tagName),ze=Tl(Z.tagName);if(!ft[T.namespaceURI])return!1;if(T.namespaceURI===xn)return WI(ce,Z,ze);if(T.namespaceURI===Pn)return qI(ce,Z,ze);if(T.namespaceURI===fn)return GI(ce,Z,ze);if(ur==="application/xhtml+xml"&&ft[T.namespaceURI])return!0;return!1},Or=function(T){Gs(t.removed,{element:T});try{b(T).removeChild(T)}catch(Z){if(h(T),!b(T))throw Xi("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},dc=function(T){Ia(T);let Z=v(T);if(Z){let ze=[];qs(Z,(Be)=>{Gs(ze,Be)}),qs(ze,(Be)=>{try{h(Be)}catch(Qe){}})}let ce=C(T);if(ce)for(let ze=ce.length-1;ze>=0;--ze){let Be=ce[ze],Qe=Be&&Be.name;if(typeof Qe==="string")try{T.removeAttribute(Qe)}catch(St){}}},Si=function(T,Z){try{Gs(t.removed,{attribute:Z.getAttributeNode(T),from:Z})}catch(ce){Gs(t.removed,{attribute:null,from:Z})}if(Z.removeAttribute(T),T==="is")if(Ee||S)try{Or(Z)}catch(ce){}else try{Z.setAttribute(T,"")}catch(ce){}},VI=function(T){let Z=C(T);if(!Z)return;for(let ce=Z.length-1;ce>=0;--ce){let ze=Z[ce],Be=ze&&ze.name;if(typeof Be!=="string"||pe[Ut(Be)])continue;try{T.removeAttribute(Be)}catch(Qe){}}},Ia=function(T){let Z=[T];while(Z.length>0){let ce=Z.pop();if((y?y(ce):ce.nodeType)===po.element)VI(ce);let Be=v(ce);if(Be)for(let Qe=Be.length-1;Qe>=0;--Qe)Z.push(Be[Qe])}},XI=function(T){if(!fe)return;let Z=[T];while(Z.length>0){let ce=Z.pop(),ze=y?y(ce):ce.nodeType;if(ze===po.processingInstruction||ze===po.comment&&gn(Z0,ce.data)){try{h(ce)}catch(Qe){}continue}if(ze===po.element){let Qe=ce,St=Ut(k?k(ce):ce.nodeName);try{if(Qe.hasAttribute&&Qe.hasAttribute("patchsrc"))Qe.removeAttribute("patchsrc");if(Qe.hasAttribute&&Qe.hasAttribute("for")&&St!=="label"&&St!=="output")Qe.removeAttribute("for")}catch(jt){}}let Be=v(ce);if(Be)for(let Qe=Be.length-1;Qe>=0;--Qe)Z.push(Be[Qe])}},Hg=function(T){let Z=null,ce=null;if(F)T="<remove></remove>"+T;else{let Qe=z0(T,/^[\r\n\t ]+/);ce=Qe&&Qe[0]}if(ur==="application/xhtml+xml"&&cr===fn)T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>";let ze=I?B(T):T;if(cr===fn)try{Z=new d().parseFromString(ze,ur)}catch(Qe){}if(!Z||!Z.documentElement){Z=ee.createDocument(cr,"template",null);try{Z.documentElement.innerHTML=ms?w:ze}catch(Qe){}}let Be=Z.body||Z.documentElement;if(T&&ce)Be.insertBefore(n.createTextNode(ce),Be.childNodes[0]||null);if(cr===fn)return te.call(Z,it?"html":"body")[0];return it?Z.documentElement:Be},Ug=function(T){let Z=_?_(T):T.ownerDocument;return he.call(Z||T,T,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},pc=function(T){return T=_l(T,Pe," "),T=_l(T,Fe," "),T=_l(T,De," "),T},bp=function(T){var Z;T.normalize();let ce=_?_(T):T.ownerDocument,ze=he.call(ce||T,T,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),Be=ze.nextNode();while(Be)Be.data=pc(Be.data),Be=ze.nextNode();let Qe=(Z=T.querySelectorAll)===null||Z===void 0?void 0:Z.call(T,"template");if(Qe)qs(Qe,(St)=>{if(gs(St.content))bp(St.content)})},fc=function(T){let Z=k?k(T):null;if(typeof Z!=="string")return!1;if(Ut(Z)!=="form")return!1;return typeof T.nodeName!=="string"||typeof T.textContent!=="string"||typeof T.removeChild!=="function"||T.attributes!==C(T)||typeof T.removeAttribute!=="function"||typeof T.setAttribute!=="function"||typeof T.namespaceURI!=="string"||typeof T.insertBefore!=="function"||typeof T.hasChildNodes!=="function"||T.nodeType!==y(T)||T.childNodes!==v(T)},gs=function(T){if(!y||typeof T!=="object"||T===null)return!1;try{return y(T)===po.documentFragment}catch(Z){return!1}},Ea=function(T){if(!y||typeof T!=="object"||T===null)return!1;try{return typeof y(T)==="number"}catch(Z){return!1}};function Uo(me,T,Z){if(me.length===0)return;qs(me,(ce)=>{ce.call(t,T,Z,hs)})}let JI=function(T,Z){if(fe&&T.hasChildNodes()&&!Ea(T.firstElementChild)&&gn(j0,T.textContent)&&gn(j0,T.innerHTML))return!0;if(fe&&T.namespaceURI===fn&&Z==="style"&&Ea(T.firstElementChild))return!0;if(T.nodeType===po.processingInstruction)return!0;if(fe&&T.nodeType===po.comment&&gn(Z0,T.data))return!0;return!1},YI=function(T,Z,ce){if(!qe[Z]&&qg(Z)){if(xe.tagNameCheck instanceof RegExp&&gn(xe.tagNameCheck,Z))return!1;if(xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Z))return!1}if(le&&!Le[Z]){let ze=b(T),Be=v(T);if(Be&&ze){let Qe=Be.length;for(let St=Qe-1;St>=0;--St){let jt=T===ce?m(Be[St],!0):Be[St];ze.insertBefore(jt,g(T))}}}return Or(T),!0},jg=function(T,Z,ce,ze){if(T.length===0)return Z;return Z===ce||Z===ze?Bn(Z):Z},Zg=function(T,Z){if(Uo(O.beforeSanitizeElements,T,null),T!==Z&&b(T)===null){if(we)Ia(T);return!0}if(fc(T))return Or(T),!0;let ce=Ut(k?k(T):T.nodeName);if(ae=jg(O.uponSanitizeElement,ae,Se,Ye),Uo(O.uponSanitizeElement,T,{tagName:ce,allowedTags:ae}),T!==Z&&b(T)===null){if(we)Ia(T);return!0}if(JI(T,ce))return Or(T),!0;if(qe[ce]||!(ye.tagCheck instanceof Function&&ye.tagCheck(ce))&&!ae[ce]){let Be=YI(T,ce,Z);if(Be===!1)Uo(O.afterSanitizeElements,T,null);return Be}if((y?y(T):T.nodeType)===po.element&&!KI(T))return Or(T),!0;if((ce==="noscript"||ce==="noembed"||ce==="noframes")&&gn(CN,T.innerHTML))return Or(T),!0;if(Ie&&T.nodeType===po.text){let Be=pc(T.textContent);if(T.textContent!==Be)Gs(t.removed,{element:T.cloneNode()}),T.textContent=Be}return Uo(O.afterSanitizeElements,T,null),!1},Wg=function(T,Z,ce){if(W[Z])return!1;if(fe&&Z==="patchsrc")return!1;if(fe&&Z==="for"&&T!=="label"&&T!=="output")return!1;if(ue&&(Z==="id"||Z==="name")&&((ce in n)||(ce in ZI)))return!1;let ze=pe[Z]||ye.attributeCheck instanceof Function&&ye.attributeCheck(Z,T);if(R&&gn(Ae,Z));else if(He&&gn(ve,Z));else if(!ze)if(qg(T)&&(xe.tagNameCheck instanceof RegExp&&gn(xe.tagNameCheck,T)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(T))&&(xe.attributeNameCheck instanceof RegExp&&gn(xe.attributeNameCheck,Z)||xe.attributeNameCheck instanceof Function&&xe.attributeNameCheck(Z,T))||Z==="is"&&xe.allowCustomizedBuiltInElements&&(xe.tagNameCheck instanceof RegExp&&gn(xe.tagNameCheck,ce)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(ce)));else return!1;else if(on[Z]);else if(gn(ke,_l(ce,re,"")));else if((Z==="src"||Z==="xlink:href"||Z==="href")&&T!=="script"&&$0(ce,"data:")===0&&pt[T]);else if(ne&&!gn(z,_l(ce,re,"")));else if(ce)return!1;return!0},QI=at({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),qg=function(T){return!QI[Tl(T)]&&gn(Ne,T)},eE=function(T,Z,ce,ze){if(I&&typeof p==="object"&&typeof p.getAttributeType==="function"&&!ce)switch(p.getAttributeType(T,Z)){case"TrustedHTML":return B(ze);case"TrustedScriptURL":return J(ze)}return ze},tE=function(T,Z,ce,ze){try{if(ce)T.setAttributeNS(ce,Z,ze);else T.setAttribute(Z,ze);if(fc(T))Or(T);else M0(t.removed)}catch(Be){Si(Z,T)}},Gg=function(T){Uo(O.beforeSanitizeAttributes,T,null);let Z=T.attributes;if(!Z||fc(T))return;pe=jg(O.uponSanitizeAttribute,pe,Ue,Lt);let ce={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0},ze=Z.length,Be=Ut(T.nodeName);while(ze--){let Qe=Z[ze],{name:St,namespaceURI:jt,value:Kn}=Qe,Vn=Ut(St),wp=Kn,Un=St==="value"?wp:aN(wp);if(ce.attrName=Vn,ce.attrValue=Un,ce.keepAttr=!0,ce.forceKeepAttr=void 0,Uo(O.uponSanitizeAttribute,T,ce),Un=ce.attrValue,$e&&(Vn==="id"||Vn==="name")&&$0(Un,je)!==0)Si(St,T),Un=je+Un;if(fe&&gn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Un)){Si(St,T);continue}if(Vn==="attributename"&&z0(Un,"href")){Si(St,T);continue}if(ce.forceKeepAttr)continue;if(!ce.keepAttr){Si(St,T);continue}if(!Ce&&gn(TN,Un)){Si(St,T);continue}if(Ie)Un=pc(Un);if(!Wg(Be,Vn,Un)){Si(St,T);continue}if(Un=eE(Be,Vn,jt,Un),Un!==wp)tE(T,St,jt,Un)}Uo(O.afterSanitizeAttributes,T,null)},mc=function(T){let Z=null,ce=Ug(T);Uo(O.beforeSanitizeShadowDOM,T,null);while(Z=ce.nextNode()){if(Uo(O.uponSanitizeShadowNode,Z,null),Zg(Z,T),Gg(Z),gs(Z.content))mc(Z.content);if((y?y(Z):Z.nodeType)===po.element){let Be=x(Z);if(gs(Be))xp(Be),mc(Be)}}Uo(O.afterSanitizeShadowDOM,T,null)},xp=function(T){let Z=[{node:T,shadow:null}];while(Z.length>0){let ce=Z.pop();if(ce.shadow){mc(ce.shadow);continue}let ze=ce.node,Qe=(y?y(ze):ze.nodeType)===po.element,St=v(ze);if(St)for(let jt=St.length-1;jt>=0;--jt)Z.push({node:St[jt],shadow:null});if(Qe){let jt=k?k(ze):null;if(typeof jt==="string"&&Ut(jt)==="template"){let Kn=ze.content;if(gs(Kn))Z.push({node:Kn,shadow:null})}}if(Qe){let jt=x(ze);if(gs(jt))Z.push({node:null,shadow:jt},{node:jt,shadow:null})}}};return t.sanitize=function(me){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,ce=null,ze=null,Be=null;if(ms=!me,ms)me="<!-->";if(typeof me!=="string"&&!Ea(me)){if(me=pN(me),typeof me!=="string")throw Xi("dirty is not a string, aborting")}if(!t.isSupported)return me;if(Ht)ae=Ye,pe=Lt;else vp(T);if(O.uponSanitizeElement.length>0||O.uponSanitizeAttribute.length>0)ae=Bn(ae);if(O.uponSanitizeAttribute.length>0)pe=Bn(pe);t.removed=[];let Qe=we&&typeof me!=="string"&&Ea(me);if(Qe){XI(me);let Kn=k?k(me):me.nodeName;if(typeof Kn==="string"){let Vn=Ut(Kn);if(!ae[Vn]||qe[Vn])throw dc(me),Xi("root node is forbidden and cannot be sanitized in-place")}if(fc(me))throw dc(me),Xi("root node is clobbered and cannot be sanitized in-place");try{xp(me)}catch(Vn){throw dc(me),Vn}}else if(Ea(me)){if(Z=Hg("<!---->"),ce=Z.ownerDocument.importNode(me,!0),ce.nodeType===po.element&&ce.nodeName==="BODY")Z=ce;else if(ce.nodeName==="HTML")Z=ce;else Z.appendChild(ce);xp(ce)}else{if(!Ee&&!Ie&&!it&&me.indexOf("<")===-1)return I&&K?B(me):me;if(Z=Hg(me),!Z)return Ee?null:K?w:""}if(Z&&F)Or(Z.firstChild);let St=Qe?me:Z;try{let Kn=Ug(St);while(ze=Kn.nextNode())if(Zg(ze,St),Gg(ze),gs(ze.content))mc(ze.content)}catch(Kn){if(Qe)dc(me),qs(t.removed,(Vn)=>{if(Vn.element)Ia(Vn.element)});throw Kn}if(Qe){if(qs(t.removed,(Kn)=>{if(Kn.element)Ia(Kn.element)}),Ie)bp(me);return me}if(Ee){if(Ie)bp(Z);if(S){Be=A.call(Z.ownerDocument);while(Z.firstChild)Be.appendChild(Z.firstChild)}else Be=Z;if(pe.shadowroot||pe.shadowrootmode)Be=M.call(o,Be,!0);return Be}let jt=it?Z.outerHTML:Z.innerHTML;if(it&&ae["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&gn(SN,Z.ownerDocument.doctype.name))jt="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
222
- `+jt;if(Ie)jt=pc(jt);return I&&K?B(jt):jt},t.setConfig=function(){let me=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};vp(me),Ht=!0,Ye=ae,Lt=pe},t.clearConfig=function(){hs=null,Ht=!1,Ye=null,Lt=null,I=P,w=""},t.isValidAttribute=function(me,T,Z){if(!hs)vp({});let ce=Ut(me),ze=Ut(T);return Wg(ce,ze,Z)},t.addHook=function(me,T){if(typeof T!=="function")return;if(!yn(O,me))return;Gs(O[me],T)},t.removeHook=function(me,T){if(!yn(O,me))return;if(T!==void 0){let Z=iN(O[me],T);return Z===-1?void 0:sN(O[me],Z,1)[0]}return M0(O[me])},t.removeHooks=function(me){if(!yn(O,me))return;O[me]=[]},t.removeAllHooks=function(){O=W0()},t}var V0=K0();function er(e){return V0.sanitize(e,{FORBID_TAGS:["form","svg","math"]})}var eh=null;function AN(){if(eh)return eh;let e=new Sl({headingStyle:"atx",codeBlockStyle:"fenced",emDelimiter:"*",bulletListMarker:"-"});return e.use(X0.gfm),e.addRule("wikiLink",{filter:(t)=>t.nodeName==="A"&&t.hasAttribute("data-wiki-markdown"),replacement:(t,n)=>{let o=n.textContent??"";return o===n.getAttribute("data-wiki-label")?n.getAttribute("data-wiki-markdown"):`[[${n.getAttribute("data-wiki-ref")}|${o}]]`}}),eh=e,e}function J0({markdown:e,initialHtml:t,className:n,onChange:o,onSave:i}){let s=D(null),a=D(!1),l=D(!1),c=D(e),u=D(e);Me(()=>{let v=s.current;if(!v)return;let b=er(t),x=u.current!==e;if(u.current=e,!a.current||x&&c.current!==e){a.current=!0,c.current=e,l.current=!1,v.innerHTML=b;for(let k of v.querySelectorAll('input[type="checkbox"][disabled]'))k.removeAttribute("disabled");return}let C=document.createElement("div");C.innerHTML=b;let y=new Map([...C.querySelectorAll("a[data-wiki-ref]")].map((k)=>[k.getAttribute("data-wiki-ref"),k]));for(let k of v.querySelectorAll("a[data-wiki-ref]")){let _=y.get(k.getAttribute("data-wiki-ref"));if(!_)continue;for(let I of["data-wiki-board","data-wiki-card","data-wiki-missing"]){let w=_.getAttribute(I);if(w===null)k.removeAttribute(I);else k.setAttribute(I,w)}k.classList.toggle("is-unresolved",_.classList.contains("is-unresolved"))}},[t,e]);let d=oe(()=>{let v=s.current;if(!v)return"";return AN().turndown(v.innerHTML)},[]),p=oe(()=>{l.current=!0;let v=d();c.current=v,o(v)},[o,d]),f=oe(()=>{let v=s.current;if(!v||!v.isConnected||v.innerHTML==="")return;i?.(l.current?d():e)},[e,i,d]),m=oe((v)=>{if(!(v.metaKey||v.ctrlKey))return;if(v.key==="s"){v.preventDefault(),f();return}if(v.key==="b"){v.preventDefault(),document.execCommand("bold"),p();return}if(v.key==="i"){v.preventDefault(),document.execCommand("italic"),p();return}if(v.key==="k")v.preventDefault(),Vu(),p()},[p,f]),h=oe((v)=>{let b=v.target;if(b instanceof HTMLInputElement&&b.type==="checkbox")b.toggleAttribute("checked",b.checked),p()},[p]),g=oe((v)=>{let b=v.clipboardData?.getData("text/plain");if(b==null)return;v.preventDefault(),document.execCommand("insertText",!1,b),p()},[p]);return r(be,{children:[r("div",{ref:s,class:n,contentEditable:!0,spellcheck:!1,onInput:p,onKeyDown:m,onPaste:g,onClick:h,onBlur:f},void 0,!1,void 0,this),r(R0,{hostRef:s,onChange:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Q0(e,t){let n=e.target.closest("a.wiki-link");if(!n)return!1;if(e.preventDefault(),e.stopPropagation(),n.dataset.wikiBoard)zt({boardId:n.dataset.wikiBoard,...n.dataset.wikiCard?{cardId:n.dataset.wikiCard}:{}});else{let o=n.dataset.wikiRef??"",i=o.split("#")[0];if(n.dataset.wikiMissing||o.includes("#")||Ge.value.some((s)=>s.name.toLocaleLowerCase()===i.toLocaleLowerCase()||s.id===i))hn("remove","Link unavailable","The target is missing or ambiguous. Use a board/card ID in the wiki link to choose it explicitly.");else window.dispatchEvent(new CustomEvent("pmx-open-board-link",{detail:{sourceNodeId:t,wikiRef:i}}))}return!0}function th({html:e,className:t,style:n,onTaskToggle:o,nodeId:i}){let s=D(null),a=D(o);return a.current=o,q(()=>{let c=s.current;if(!c)return;if(c.replaceChildren(),!e)return;let u=document.createElement("template");if(u.innerHTML=er(e),c.append(u.content.cloneNode(!0)),a.current)for(let d of c.querySelectorAll('input[type="checkbox"][data-pmx-task][disabled]'))d.removeAttribute("disabled")},[e]),r("div",{ref:s,class:t,style:n,onClick:(c)=>{if(Q0(c,i))return;let u=c.target,d=a.current;if(!s.current||!d)return;let f=null;if(u instanceof HTMLInputElement&&u.matches('input[type="checkbox"][data-pmx-task]'))f=u;else{let h=u.closest("li")?.querySelector(":scope > input[data-pmx-task], :scope > p > input[data-pmx-task]");if(h&&c.clientX<=h.getBoundingClientRect().right+6)f=h}if(!f)return;c.preventDefault(),c.stopPropagation(),d(Number(f.dataset.pmxTask))}},void 0,!1,void 0,this)}var Y0=new Mm({gfm:!0,breaks:!0});function RN(e,t){let n=(d)=>{let p=[];return Y0.walkTokens(Y0.lexer(d),(f)=>{if(f.type==="list_item"&&f.task)p.push(!!f.checked)}),p},o=n(e);if(!Number.isInteger(t)||t<0||t>=o.length)return e;let i=[...e.matchAll(/(?:[-*+]|\d{1,9}[.)])[ \t]+\[[ xX]\](?=[ \t]|$)/gm)].map((d)=>d.index+d[0].lastIndexOf("[")+1),s=(d,p)=>{let f=e;for(let m=p;m>=d;m--){let h=i[m];f=f.slice(0,h)+(f[h]===" "?"x":" ")+f.slice(h+1)}return f},a=0,l=i.length-1;while(a<l){let d=Math.floor((a+l)/2);if(n(s(a,d))[t]!==o[t])l=d;else a=d+1}let c=s(a,a),u=n(c);return u.length===o.length&&u.every((d,p)=>d===(p===t?!o[p]:o[p]))?c:e}var Ar=new Map;function nh(e,t){let n=Ar.get(JSON.stringify([e,t]));return!!n&&(n.dirty.value||n.pending.value>0)}async function oh(e,t){let n=Ik(),o=wt,i=Ar.get(JSON.stringify([e,t]));return await i?.saveQueue.current,n()&&o===wt&&se.value===e&&!i?.dirty.value}function Yu({node:e,expanded:t=!1}){let n=Yn(),o=se.value,i=JSON.stringify([o,e.id]),s=Ke(()=>{let A=Ar.get(i);if(A)return A;let te={latestMdRef:{current:typeof e.data.content==="string"?e.data.content:""},renderedMdRef:{current:null},dirty:ie(!1),editBase:{current:{boardId:o,revision:e.contentRevision??0}},saveQueue:{current:Promise.resolve()},nativeSaveAttempts:new Set,pending:ie(0),owners:0};return Ar.set(i,te),te},[i]),{latestMdRef:a,renderedMdRef:l,editBase:c,saveQueue:u}=s,d=e.data.path,[p,f]=E(""),[m,h]=E(""),[g,v]=E(!1),[b,x]=E(!1),[C,y]=E(!1),k=s.dirty.value,_=D(null),I=Ke(()=>({current:null}),[s]),w=Ke(()=>({current:null}),[s]),P=e.data.reviewActive,L=JSON.stringify(e.data.wikiLinks??[]);Me(()=>{s.owners++,Ar.set(i,s),f(a.current);let A=l.current,te=A?.markdown===a.current;return h(te?A.html:""),v(te),()=>{if(s.owners--,!s.owners&&!s.pending.value&&!s.dirty.value&&Ar.get(i)===s)Ar.delete(i)}},[s]),q(()=>{let A=s.dirty.value||s.pending.value>0;if(!A)c.current={boardId:o,revision:e.contentRevision??0};let te=!1;return(async()=>{let M;if(A)M=a.current;else if(d){let Pe=await nl(d);if(te)return;M=Pe.content}else if(typeof e.data.content==="string")M=e.data.content;else{v(!0);return}let O=await Vo(M,e.id,o);if(O===null||te||se.value!==o||(A||s.dirty.value?a.current!==M:!d&&H.value.get(e.id)?.data.content!==M))return;if(l.current={markdown:M,html:O},h(O),v(!0),!A&&!s.dirty.value)a.current=M,f(M),Xe(e.id,{content:M,rendered:O});else if(H.value.get(e.id)?.data.content===M)Xe(e.id,{rendered:O})})(),()=>{te=!0}},[o,d,e.id,e.data.content,L,e.linksRevision]);let N=oe(async(A)=>{let te=A.target.value;s.dirty.value=!0,a.current=te,f(te);let M=await Vo(te,e.id,o);if(M===null||se.value!==o||a.current!==te)return;l.current={markdown:te,html:M},h(M)},[o,s,e.id]),Y=oe(async(A)=>{let te=wt,M={revision:H.value.get(e.id)?.contentRevision??0};s.nativeSaveAttempts.add(M),s.pending.value++,u.current=u.current.then(async()=>{if(te!==wt||se.value!==o||a.current!==A)return;if(tt()){y(!0);let Ae=await ln(e.id,{content:A,expectedBoardId:c.current.boardId,expectedContentRevision:c.current.revision});if(y(!1),!Ae.ok||te!==wt)return;c.current.revision=Ae.contentRevision??c.current.revision;let ve=await Vo(A,e.id,o);if(te!==wt||se.value!==o||a.current!==A)return;let z=H.value.get(e.id);if(!z||(z.contentRevision??0)>c.current.revision)return;if(H.value=new Map(H.value).set(e.id,{...z,contentRevision:c.current.revision,lastEditedBy:Ae.lastEditedBy,data:{...z.data,content:A,...ve!==null?{rendered:ve}:{}}}),s.dirty.value=!1,ve!==null)l.current={markdown:A,html:ve},h(ve);return}let O=await Vo(A,e.id,o);if(O===null||te!==wt||se.value!==o||a.current!==A)return;if(se.value===o&&a.current===A&&l.current?.markdown!==A)l.current={markdown:A,html:O},h(O);let Pe=M.revision,Fe=await ln(e.id,{content:A,data:{rendered:O},expectedBoardId:o,expectedContentRevision:Pe,...d?{persistFile:!0}:{}});if(te!==wt)return;if(Fe.ok&&Fe.contentRevision!==void 0){for(let Ae of s.nativeSaveAttempts)if(Ae.revision===Pe)Ae.revision=Fe.contentRevision}let De=H.value.get(e.id);if(Fe.ok&&Fe.contentRevision!==void 0&&De&&se.value===o&&(De.contentRevision??0)<=Fe.contentRevision){let Ae=l.current,ve=Ae?.markdown!==A;if(H.value=new Map(H.value).set(e.id,{...De,contentRevision:Fe.contentRevision,lastEditedBy:Fe.lastEditedBy,data:{...De.data,content:A,rendered:Ae?.markdown===A?Ae.html:O}}),a.current===A){if(ve)l.current={markdown:A,html:O},h(O);s.dirty.value=!1,f(A)}}});try{await u.current}finally{if(s.nativeSaveAttempts.delete(M),s.pending.value--,!s.owners&&!s.pending.value&&!s.dirty.value&&Ar.get(i)===s)Ar.delete(i)}},[o,d,e.id,s]),B=oe(async()=>{if(!k)return;await Y(p)},[k,p,Y]),J=oe(async()=>{if(l.current?.markdown!==p){let te=await Vo(p,e.id,o);if(te===null||se.value!==o||a.current!==p)return;if(l.current?.markdown!==p)l.current={markdown:p,html:te}}if(se.value!==o||a.current!==p)return;let A=l.current;if(A?.markdown!==p)return;h(A.html),v(!0),x(!1)},[o,p,e.id]),X=oe((A)=>{if((A.metaKey||A.ctrlKey)&&A.key==="s"){A.preventDefault(),B();return}let te=_.current;if(te&&YS(A,te))return;if(te&&A.key==="Tab")A.preventDefault(),JS(te,A.shiftKey)},[B]);w.current=Y;let V=oe((A)=>{if(s.dirty.value=!0,f(A),a.current=A,I.current!==null)window.clearTimeout(I.current);I.current=window.setTimeout(()=>{I.current=null,Y(A)},800)},[Y,s]),ee=oe((A)=>{if(!s.dirty.value&&A===a.current)return;if(s.dirty.value=!0,f(A),a.current=A,I.current!==null)window.clearTimeout(I.current),I.current=null;Y(A)},[Y,s]);q(()=>()=>{if(I.current===null)return;window.clearTimeout(I.current),I.current=null;let A=w.current;if(A)A(a.current)},[s]);let he=P?r("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(b&&t)return r("div",{class:"md-editor-expanded",onKeyDown:X,children:[r("div",{class:"md-editor-toolbar",children:[r("button",{type:"button",class:"md-toolbar-btn",onClick:J,children:[r(dS,{size:14},void 0,!1,void 0,this)," Back to document"]},void 0,!0,void 0,this),r("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&r("span",{class:"md-toolbar-path",children:d.split("/").pop()},void 0,!1,void 0,this),r("button",{type:"button",class:`md-toolbar-btn${k?" md-toolbar-btn-primary":""}`,onClick:B,disabled:!k||C,children:C?"Saving…":k?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"md-editor-split",children:[r("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[r("textarea",{ref:_,value:p,onInput:N,spellcheck:!1},void 0,!1,void 0,this),r(zm,{textareaRef:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(th,{nodeId:e.id,html:m,className:"md-preview"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(b)return r("div",{class:"md-editor-split",style:{height:"100%"},onKeyDown:X,children:[r("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[r("textarea",{ref:_,value:p,onInput:N,spellcheck:!1},void 0,!1,void 0,this),r(zm,{textareaRef:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(th,{nodeId:e.id,html:m,className:"md-preview"},void 0,!1,void 0,this),r("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[r("button",{type:"button",onClick:J,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),r("button",{type:"button",onClick:B,disabled:!k||C,style:{padding:"4px 10px",fontSize:"11px",background:k?"color-mix(in srgb, var(--c-accent) 25%, transparent)":"var(--c-input-bg)",border:`1px solid ${k?"var(--c-accent)":"var(--c-line)"}`,borderRadius:"6px",color:k?"var(--c-text)":"var(--c-dim)",cursor:k?"pointer":"default"},children:C?"Saving…":k?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(t)return r("div",{class:"md-expanded-document",style:{height:"100%",position:"relative"},onClick:async(A)=>{if(!A.target.closest("a.wiki-link"))return;A.preventDefault(),A.stopPropagation();let te=document.activeElement;if(te instanceof HTMLElement&&A.currentTarget.contains(te))te.blur();if(!await oh(o,e.id))return;Q0(A,e.id)},children:[he,r("div",{class:"md-reader",children:g?r(J0,{markdown:p,initialHtml:m||"<p><br></p>",className:"md-reader-content md-reader-editable",onChange:V,onSave:ee},e.id,!1,void 0,this):r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"24px"},children:"Loading…"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",class:"md-edit-fab",onClick:()=>x(!0),children:"</> Source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{class:"md-card-preview",children:[r("div",{class:"md-card-content",children:[he,r(th,{nodeId:e.id,html:m,style:{padding:m?"0":"12px",color:m?void 0:"var(--c-dim)"},onTaskToggle:(A)=>{let te=l.current;if(te?.html!==m||te.markdown!==a.current)return;let M=RN(te.markdown,A);if(M!==p)ee(M)}},void 0,!1,void 0,this),!g&&r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Loading…"},void 0,!1,void 0,this),g&&!m&&r("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&&r("div",{class:"md-import-source",children:["Source material ·"," ",r("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),r("div",{class:"md-card-actions",children:[n&&r("button",{type:"button",class:"md-readme-btn","aria-pressed":n.readmeNodeId===e.id,onClick:()=>void Pk(n.id,n.readmeNodeId===e.id?null:e.id),children:n.readmeNodeId===e.id?"README":"Set as README"},void 0,!1,void 0,this),r("button",{type:"button",class:"md-card-edit",onClick:()=>xo(e.id),children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Qu="pmx-canvas-ax",ed="pmx-canvas-ax-ack",Qn="pmx-canvas-html-node",rh="pmx-canvas-json-state",td="pmx-canvas-ext-app-alive",ih="pmx-canvas-ext-app-paint-probe";function e_(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 sh="allow-scripts allow-popups allow-popups-to-escape-sandbox";function Vs(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 Il(e,t={}){let n=new URLSearchParams;if(n.set("theme",t.theme??Qt.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 nd(e){return e_(e.type,e.data)}async function od(e){if(tt()){hn("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=Il(e.id);if(!(await yk(e.id,t)).opened)window.open(t,"_blank","noopener")}var PN={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 t_(e){return PN[e]}function n_(e,t,n,o,i){return e.x<o.position.x+o.size.width+i&&e.x+t+i>o.position.x&&e.y<o.position.y+o.size.height+i&&e.y+n+i>o.position.y}function NN(e,t,n,o,i){return o.some((s)=>n_(e,t,n,s,i))}function rd(e,t,n,o,i){return o.find((s)=>n_(e,t,n,s,i))}function id(e,t,n,o=24){if(e.length===0)return{x:40,y:80};let i=e[e.length-1],s={x:i.position.x+i.size.width+o,y:i.position.y};if(!NN(s,t,n,e,o))return s;let a=40,l=80,c=3000,u=l;for(let p=0;p<20;p++){let f=a;while(f+t<c){let g=rd({x:f,y:u},t,n,e,o);if(!g)return{x:f,y:u};f=g.position.x+g.size.width+o}u=e.filter((g)=>g.position.y<=u+n+o&&g.position.y+g.size.height+o>u).reduce((g,v)=>Math.max(g,v.position.y+v.size.height),u)+o}let d=e.reduce((p,f)=>Math.max(p,f.position.y+f.size.height),0);return{x:a,y:d+o}}var Xs=37,MN=600,zN=1400,$N=24;function LN(e){return e.type==="html"||e.type==="mermaid"||e.type==="json-render"||e.type==="graph"||e.type==="mcp-app"||e.type==="webpage"}function ON(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 o_(e){return e.collapsed===!0||e.data.strictSize===!0||e.data.userResized===!0||e.type==="group"}function ah(e){return!o_(e)&&!LN(e)}function r_(e,t){if(!ah(e)||t<=0)return null;let n=Math.min(t+Xs,MN),o=t_(e.type);return o?Math.max(n,o.height):n}function lh(e){return ON(e)&&!o_(e)}function i_(e,t){if(!lh(e)||!Number.isFinite(t)||t<=0)return null;let n=Math.min(t+Xs+$N,zN);return n>e.size.height+8?n:null}function s_(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"),i={...e.position},s=rd(i,e.size.width,t,o,24);while(s)i.y=s.position.y+s.size.height+24,s=rd(i,e.size.width,t,o,24);return i}function Js(e,t,n){q(()=>{if(!n)return;let o=null,i=null,s=()=>Wo.value===e.id||Ja.value.some((d)=>d.grabbingNodeId===e.id);function a(){if(o=null,s()||i===null)return;let d=i;i=null;let p=H.value.get(e.id);if(!p)return;let f=i_(p,d);if(f===null)return;let m=s_(p,f,Array.from(H.value.values())),h=m.x!==p.position.x||m.y!==p.position.y,g={size:{width:p.size.width,height:f},...h?{position:m}:{}};un(p.id,g),gu([{id:p.id,...g}],{recordHistory:h})}function l(){if(o!==null)clearTimeout(o);o=i!==null&&!s()?setTimeout(a,300):null}let c=sn(()=>{s(),l()});function u(d){if(d.source!==t.current?.contentWindow)return;let p=d.data;if(!p||p.source!=="pmx-canvas-frame"||p.type!=="content-height"||p.token!==n)return;if(typeof p.height!=="number"||!Number.isFinite(p.height)||p.height<=0)return;i=p.height,l()}return window.addEventListener("message",u),()=>{if(window.removeEventListener("message",u),c(),o!==null)clearTimeout(o)}},[e.id,n])}function DN(e){if(tt())return e.startsWith("/")&&!e.startsWith("//");try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Ys(e){let t=_n.value,[n,o]=E(null),i=Boolean(e)&&DN(e),s=t==="srcdoc"&&i;if(q(()=>{if(!s)return;let a=!1;return Gt(`${e}${e.includes("?")?"&":"?"}inline-assets=1`,{credentials:"same-origin"}).then((l)=>l.ok?l.text():Promise.reject(Error(`HTTP ${l.status}`))).then((l)=>{if(!a)o({url:e,html:l})}).catch((l)=>{if(console.error("[surface-frame] srcdoc fetch failed, falling back to src:",e,l),!a)o({url:e,html:""})}),()=>{a=!0}},[s,e]),!e)return{};if(!s)return t===null&&i?{}:{src:e};if(n)return n.html?{srcdoc:n.html}:{src:n.url};return{}}function sd({node:e,expanded:t=!1}){let n=D(null),o=Qt.value,i=Ke(()=>`theme-${crypto.randomUUID()}`,[]),s=Ke(()=>`frame-${crypto.randomUUID()}`,[]),a=typeof e.data.content==="string"?e.data.content:"",l=e.data.fit==="none"?"none":"contain",c=Ke(()=>Vs(`${l}:${a}`),[a,l]),u=Ke(()=>a?Il(e.id,{theme:o,themeToken:i,v:c,frameToken:s}):"",[a,i,c,e.id,s]),d=Ys(u);Js(e,n,t?"":s);let p=()=>{n.current?.contentWindow?.postMessage({source:Qn,type:"theme-update",token:i,theme:o},"*")};if(q(p,[o,i]),!a)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No diagram source set"},void 0,!1,void 0,this);return r("iframe",{ref:n,class:"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"Mermaid diagram",sandbox:"allow-scripts",...d,onLoad:p,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 ch=["harbor","daylight","high-contrast","midnight","sepia","arctic","ember","forest","volt"];function El(e){return typeof e==="string"&&ch.includes(e)}function uh(e,t="harbor"){return El(e)?e:t}var Qs={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 ea(e){return Qs[uh(e)].scheme}var ci="io.modelcontextprotocol/related-task",ld="2.0",In=_w((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),a_=rt([U(),Ze().int()]),l_=U(),o4=Zn({ttl:rt([Ze(),Sf()]).optional(),pollInterval:Ze().optional()}),BN=G({ttl:Ze().optional()}),FN=G({taskId:U()}),dh=Zn({progressToken:a_.optional(),[ci]:FN.optional()}),fo=G({_meta:dh.optional()}),Al=fo.extend({task:BN.optional()}),c_=(e)=>Al.safeParse(e).success,En=G({method:U(),params:fo.loose().optional()}),wo=G({_meta:dh.optional()}),ko=G({method:U(),params:wo.loose().optional()}),An=Zn({_meta:dh.optional()}),na=rt([U(),Ze().int()]),u_=G({jsonrpc:j(ld),id:na,...En.shape}).strict(),ph=(e)=>u_.safeParse(e).success,d_=G({jsonrpc:j(ld),...ko.shape}).strict(),p_=(e)=>d_.safeParse(e).success,fh=G({jsonrpc:j(ld),id:na,result:An}).strict(),Rl=(e)=>fh.safeParse(e).success;var vt;(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"})(vt||(vt={}));var mh=G({jsonrpc:j(ld),id:na.optional(),error:G({code:Ze().int(),message:U(),data:_t().optional()})}).strict();var f_=(e)=>mh.safeParse(e).success;var m_=rt([u_,d_,fh,mh]),r4=rt([fh,mh]),hh=An.strict(),HN=wo.extend({requestId:na.optional(),reason:U().optional()}),cd=ko.extend({method:j("notifications/cancelled"),params:HN}),UN=G({src:U(),mimeType:U().optional(),sizes:We(U()).optional(),theme:mn(["light","dark"]).optional()}),Pl=G({icons:We(UN).optional()}),ta=G({name:U(),title:U().optional()}),Nl=ta.extend({...ta.shape,...Pl.shape,version:U(),websiteUrl:U().optional(),description:U().optional()}),jN=Vc(G({applyDefaults:ht().optional()}),bt(U(),_t())),ZN=Tf((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Vc(G({form:jN.optional(),url:In.optional()}),bt(U(),_t()).optional())),WN=Zn({list:In.optional(),cancel:In.optional(),requests:Zn({sampling:Zn({createMessage:In.optional()}).optional(),elicitation:Zn({create:In.optional()}).optional()}).optional()}),qN=Zn({list:In.optional(),cancel:In.optional(),requests:Zn({tools:Zn({call:In.optional()}).optional()}).optional()}),GN=G({experimental:bt(U(),In).optional(),sampling:G({context:In.optional(),tools:In.optional()}).optional(),elicitation:ZN.optional(),roots:G({listChanged:ht().optional()}).optional(),tasks:WN.optional()}),KN=fo.extend({protocolVersion:U(),capabilities:GN,clientInfo:Nl}),VN=En.extend({method:j("initialize"),params:KN});var XN=G({experimental:bt(U(),In).optional(),logging:In.optional(),completions:In.optional(),prompts:G({listChanged:ht().optional()}).optional(),resources:G({subscribe:ht().optional(),listChanged:ht().optional()}).optional(),tools:G({listChanged:ht().optional()}).optional(),tasks:qN.optional()}),JN=An.extend({protocolVersion:U(),capabilities:XN,serverInfo:Nl,instructions:U().optional()}),YN=ko.extend({method:j("notifications/initialized"),params:wo.optional()});var Ji=En.extend({method:j("ping"),params:fo.optional()}),QN=G({progress:Ze(),total:Wt(Ze()),message:Wt(U())}),eM=G({...wo.shape,...QN.shape,progressToken:a_}),ud=ko.extend({method:j("notifications/progress"),params:eM}),tM=fo.extend({cursor:l_.optional()}),Ml=En.extend({params:tM.optional()}),zl=An.extend({nextCursor:l_.optional()}),nM=mn(["working","input_required","completed","failed","cancelled"]),$l=G({taskId:U(),status:nM,ttl:rt([Ze(),Sf()]),createdAt:U(),lastUpdatedAt:U(),pollInterval:Wt(Ze()),statusMessage:Wt(U())}),dd=An.extend({task:$l}),oM=wo.merge($l),Ll=ko.extend({method:j("notifications/tasks/status"),params:oM}),pd=En.extend({method:j("tasks/get"),params:fo.extend({taskId:U()})}),fd=An.merge($l),md=En.extend({method:j("tasks/result"),params:fo.extend({taskId:U()})}),i4=An.loose(),hd=Ml.extend({method:j("tasks/list")}),gd=zl.extend({tasks:We($l)}),yd=En.extend({method:j("tasks/cancel"),params:fo.extend({taskId:U()})}),h_=An.merge($l),g_=G({uri:U(),mimeType:Wt(U()),_meta:bt(U(),_t()).optional()}),y_=g_.extend({text:U()}),gh=U().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),v_=g_.extend({blob:gh}),Ol=mn(["user","assistant"]),oa=G({audience:We(Ol).optional(),priority:Ze().min(0).max(1).optional(),lastModified:vf({offset:!0}).optional()}),b_=G({...ta.shape,...Pl.shape,uri:U(),description:Wt(U()),mimeType:Wt(U()),annotations:oa.optional(),_meta:Wt(Zn({}))}),rM=G({...ta.shape,...Pl.shape,uriTemplate:U(),description:Wt(U()),mimeType:Wt(U()),annotations:oa.optional(),_meta:Wt(Zn({}))}),yh=Ml.extend({method:j("resources/list")}),vd=zl.extend({resources:We(b_)}),vh=Ml.extend({method:j("resources/templates/list")}),bh=zl.extend({resourceTemplates:We(rM)}),xh=fo.extend({uri:U()}),iM=xh,wh=En.extend({method:j("resources/read"),params:iM}),bd=An.extend({contents:We(rt([y_,v_]))}),kh=ko.extend({method:j("notifications/resources/list_changed"),params:wo.optional()}),sM=xh,aM=En.extend({method:j("resources/subscribe"),params:sM}),lM=xh,cM=En.extend({method:j("resources/unsubscribe"),params:lM}),uM=wo.extend({uri:U()}),dM=ko.extend({method:j("notifications/resources/updated"),params:uM}),pM=G({name:U(),description:Wt(U()),required:Wt(ht())}),fM=G({...ta.shape,...Pl.shape,description:Wt(U()),arguments:Wt(We(pM)),_meta:Wt(Zn({}))}),Sh=Ml.extend({method:j("prompts/list")}),_h=zl.extend({prompts:We(fM)}),mM=fo.extend({name:U(),arguments:bt(U(),U()).optional()}),hM=En.extend({method:j("prompts/get"),params:mM}),Ch=G({type:j("text"),text:U(),annotations:oa.optional(),_meta:bt(U(),_t()).optional()}),Th=G({type:j("image"),data:gh,mimeType:U(),annotations:oa.optional(),_meta:bt(U(),_t()).optional()}),Ih=G({type:j("audio"),data:gh,mimeType:U(),annotations:oa.optional(),_meta:bt(U(),_t()).optional()}),gM=G({type:j("tool_use"),name:U(),id:U(),input:bt(U(),_t()),_meta:bt(U(),_t()).optional()}),Eh=G({type:j("resource"),resource:rt([y_,v_]),annotations:oa.optional(),_meta:bt(U(),_t()).optional()}),Ah=b_.extend({type:j("resource_link")}),ra=rt([Ch,Th,Ih,Ah,Eh]),yM=G({role:Ol,content:ra}),vM=An.extend({description:U().optional(),messages:We(yM)}),Rh=ko.extend({method:j("notifications/prompts/list_changed"),params:wo.optional()}),bM=G({title:U().optional(),readOnlyHint:ht().optional(),destructiveHint:ht().optional(),idempotentHint:ht().optional(),openWorldHint:ht().optional()}),xM=G({taskSupport:mn(["required","optional","forbidden"]).optional()}),xd=G({...ta.shape,...Pl.shape,description:U().optional(),inputSchema:G({type:j("object"),properties:bt(U(),In).optional(),required:We(U()).optional()}).catchall(_t()),outputSchema:G({type:j("object"),properties:bt(U(),In).optional(),required:We(U()).optional()}).catchall(_t()).optional(),annotations:bM.optional(),execution:xM.optional(),_meta:bt(U(),_t()).optional()}),wd=Ml.extend({method:j("tools/list")}),wM=zl.extend({tools:We(xd)}),Yi=An.extend({content:We(ra).default([]),structuredContent:bt(U(),_t()).optional(),isError:ht().optional()}),s4=Yi.or(An.extend({toolResult:_t()})),kM=Al.extend({name:U(),arguments:bt(U(),_t()).optional()}),kd=En.extend({method:j("tools/call"),params:kM}),Ph=ko.extend({method:j("notifications/tools/list_changed"),params:wo.optional()}),a4=G({autoRefresh:ht().default(!0),debounceMs:Ze().int().nonnegative().default(300)}),x_=mn(["debug","info","notice","warning","error","critical","alert","emergency"]),SM=fo.extend({level:x_}),_M=En.extend({method:j("logging/setLevel"),params:SM}),CM=wo.extend({level:x_,logger:U().optional(),data:_t()}),Nh=ko.extend({method:j("notifications/message"),params:CM}),TM=G({name:U().optional()}),IM=G({hints:We(TM).optional(),costPriority:Ze().min(0).max(1).optional(),speedPriority:Ze().min(0).max(1).optional(),intelligencePriority:Ze().min(0).max(1).optional()}),EM=G({mode:mn(["auto","required","none"]).optional()}),AM=G({type:j("tool_result"),toolUseId:U().describe("The unique identifier for the corresponding tool call."),content:We(ra).default([]),structuredContent:G({}).loose().optional(),isError:ht().optional(),_meta:bt(U(),_t()).optional()}),RM=Cf("type",[Ch,Th,Ih]),ad=Cf("type",[Ch,Th,Ih,gM,AM]),PM=G({role:Ol,content:rt([ad,We(ad)]),_meta:bt(U(),_t()).optional()}),NM=Al.extend({messages:We(PM),modelPreferences:IM.optional(),systemPrompt:U().optional(),includeContext:mn(["none","thisServer","allServers"]).optional(),temperature:Ze().optional(),maxTokens:Ze().int(),stopSequences:We(U()).optional(),metadata:In.optional(),tools:We(xd).optional(),toolChoice:EM.optional()}),MM=En.extend({method:j("sampling/createMessage"),params:NM}),zM=An.extend({model:U(),stopReason:Wt(mn(["endTurn","stopSequence","maxTokens"]).or(U())),role:Ol,content:RM}),$M=An.extend({model:U(),stopReason:Wt(mn(["endTurn","stopSequence","maxTokens","toolUse"]).or(U())),role:Ol,content:rt([ad,We(ad)])}),LM=G({type:j("boolean"),title:U().optional(),description:U().optional(),default:ht().optional()}),OM=G({type:j("string"),title:U().optional(),description:U().optional(),minLength:Ze().optional(),maxLength:Ze().optional(),format:mn(["email","uri","date","date-time"]).optional(),default:U().optional()}),DM=G({type:mn(["number","integer"]),title:U().optional(),description:U().optional(),minimum:Ze().optional(),maximum:Ze().optional(),default:Ze().optional()}),BM=G({type:j("string"),title:U().optional(),description:U().optional(),enum:We(U()),default:U().optional()}),FM=G({type:j("string"),title:U().optional(),description:U().optional(),oneOf:We(G({const:U(),title:U()})),default:U().optional()}),HM=G({type:j("string"),title:U().optional(),description:U().optional(),enum:We(U()),enumNames:We(U()).optional(),default:U().optional()}),UM=rt([BM,FM]),jM=G({type:j("array"),title:U().optional(),description:U().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:G({type:j("string"),enum:We(U())}),default:We(U()).optional()}),ZM=G({type:j("array"),title:U().optional(),description:U().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:G({anyOf:We(G({const:U(),title:U()}))}),default:We(U()).optional()}),WM=rt([jM,ZM]),qM=rt([HM,UM,WM]),GM=rt([qM,LM,OM,DM]),KM=Al.extend({mode:j("form").optional(),message:U(),requestedSchema:G({type:j("object"),properties:bt(U(),GM),required:We(U()).optional()})}),VM=Al.extend({mode:j("url"),message:U(),elicitationId:U(),url:U().url()}),XM=rt([KM,VM]),JM=En.extend({method:j("elicitation/create"),params:XM}),YM=wo.extend({elicitationId:U()}),QM=ko.extend({method:j("notifications/elicitation/complete"),params:YM}),ez=An.extend({action:mn(["accept","decline","cancel"]),content:Tf((e)=>e===null?void 0:e,bt(U(),rt([U(),Ze(),ht(),We(U())])).optional())}),tz=G({type:j("ref/resource"),uri:U()});var nz=G({type:j("ref/prompt"),name:U()}),oz=fo.extend({ref:rt([nz,tz]),argument:G({name:U(),value:U()}),context:G({arguments:bt(U(),U()).optional()}).optional()}),rz=En.extend({method:j("completion/complete"),params:oz});var iz=An.extend({completion:Zn({values:We(U()).max(100),total:Wt(Ze().int()),hasMore:Wt(ht())})}),sz=G({uri:U().startsWith("file://"),name:U().optional(),_meta:bt(U(),_t()).optional()}),az=En.extend({method:j("roots/list"),params:fo.optional()}),lz=An.extend({roots:We(sz)}),cz=ko.extend({method:j("notifications/roots/list_changed"),params:wo.optional()}),l4=rt([Ji,VN,rz,_M,hM,Sh,yh,vh,wh,aM,cM,kd,wd,pd,md,hd,yd]),c4=rt([cd,ud,YN,cz,Ll]),u4=rt([hh,zM,$M,ez,lz,fd,gd,dd]),d4=rt([Ji,MM,JM,az,pd,md,hd,yd]),p4=rt([cd,ud,Nh,dM,kh,Ph,Rh,Ll,QM]),f4=rt([hh,JN,iz,vM,_h,vd,bh,bd,Yi,wM,fd,gd,dd]);class lt 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===vt.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new w_(o.elicitations,t)}return new lt(e,t,n)}}class w_ extends lt{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(vt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Sd(e){return!!e._zod}function _d(e,t){if(Sd(e))return Oa(e,t);return e.safeParse(t)}function k_(e){if(!e)return;let t;if(Sd(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 S_(e){if(Sd(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 ui(e){return e==="completed"||e==="failed"||e==="cancelled"}var uz=Symbol("Let zodToJsonSchema decide on which parser to use");var i5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mh(e){let n=k_(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=S_(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function zh(e,t){let n=_d(e,t);if(!n.success)throw n.error;return n.data}var gz=60000;class Cd{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(cd,(t)=>{this._oncancel(t)}),this.setNotificationHandler(ud,(t)=>{this._onprogress(t)}),this.setRequestHandler(Ji,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(pd,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new lt(vt.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(md,async(t,n)=>{let o=async()=>{let i=t.params.taskId;if(this._taskMessageQueue){let a;while(a=await this._taskMessageQueue.dequeue(i,n.sessionId)){if(a.type==="response"||a.type==="error"){let l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{let d=l,p=new lt(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new lt(vt.InvalidParams,`Task not found: ${i}`);if(!ui(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ui(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[ci]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(hd,async(t,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new lt(vt.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(yd,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new lt(vt.InvalidParams,`Task not found: ${t.params.taskId}`);if(ui(o.status))throw new lt(vt.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 i=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!i)throw new lt(vt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...i}}catch(o){if(o instanceof lt)throw o;throw new lt(vt.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,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),lt.fromError(vt.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=(i)=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{if(o?.(i,s),Rl(i)||f_(i))this._onresponse(i);else if(ph(i))this._onrequest(i,s);else if(p_(i))this._onnotification(i);else this._onerror(Error(`Unknown message type: ${JSON.stringify(i)}`))},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=lt.fromError(vt.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,i=e.params?._meta?.[ci]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:vt.MethodNotFound,message:"Method not found"}};if(i&&this._taskMessageQueue)this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=c_(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,c={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(s.signal.aborted)return;let d={relatedRequestId:e.id};if(i)d.relatedTask={taskId:i};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(s.signal.aborted)throw new lt(vt.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};if(i&&!f.relatedTask)f.relatedTask={taskId:i};let m=f.relatedTask?.taskId??i;if(m&&l)await l.updateTaskStatus(m,"input_required");return await this.request(u,d,f)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(a)this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async(u)=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(i&&this._taskMessageQueue)await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:vt.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(i&&this._taskMessageQueue)await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===s)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),i=this._progressHandlers.get(o);if(!i){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(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(l);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),Rl(e))n(e);else{let s=new lt(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 i=!1;if(Rl(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")i=!0,this._taskProgressTokens.set(a.taskId,t)}}if(!i)this._progressHandlers.delete(t);if(Rl(e))o(e);else{let s=lt.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 lt?s:new lt(vt.InternalError,String(s))}}return}let i;try{let s=await this.request(e,dd,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new lt(vt.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},ui(a.status)){if(a.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:i},t,n)};else if(a.status==="failed")yield{type:"error",error:new lt(vt.InternalError,`Task ${i} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new lt(vt.InternalError,`Task ${i} was cancelled`)};return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},t,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof lt?s:new lt(vt.InternalError,String(s))}}}request(e,t,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{let d=(b)=>{u(b)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};if(n?.onprogress)this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(a)f.params={...f.params,task:a};if(l)f.params={...f.params,_meta:{...f.params?._meta||{},[ci]:l}};let m=(b)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch((C)=>this._onerror(Error(`Failed to send cancellation: ${C}`)));let x=b instanceof lt?b:new lt(vt.RequestTimeout,String(b));u(x)};this._responseHandlers.set(p,(b)=>{if(n?.signal?.aborted)return;if(b instanceof Error)return u(b);try{let x=_d(t,b.result);if(!x.success)u(x.error);else c(x.data)}catch(x){u(x)}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??gz,g=()=>m(lt.fromError(vt.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=l?.taskId;if(v){let b=(x)=>{let C=this._responseHandlers.get(p);if(C)C(x);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch((x)=>{this._cleanupTimeout(p),u(x)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch((b)=>{this._cleanupTimeout(p),u(b)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},fd,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},gd,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},h_,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||{},[ci]: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||{},[ci]:t.relatedTask}}};this._transport?.send(a,t).catch((l)=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ci]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let n=Mh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=zh(e,o);return Promise.resolve(t(s,i))})}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=Mh(e);this._notificationHandlers.set(n,(o)=>{let i=zh(e,o);return Promise.resolve(t(i))})}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"&&ph(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);if(s)s(new lt(vt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i);else this._onerror(Error(`Resolver missing for request ${i} 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,i)=>{if(t.aborted){i(new lt(vt.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new lt(vt.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 i=await n.getTask(o,t);if(!i)throw new lt(vt.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,t);let a=await n.getTask(o,t);if(a){let l=Ll.parse({method:"notifications/tasks/status",params:a});if(await this.notification(l),ui(a.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>n.getTaskResult(o,t),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,t);if(!a)throw new lt(vt.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ui(a.status))throw new lt(vt.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,t);let l=await n.getTask(o,t);if(l){let c=Ll.parse({method:"notifications/tasks/status",params:l});if(await this.notification(c),ui(l.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>n.listTasks(o,t)}}}var T_="2026-01-26";var yz="ui/notifications/tool-input-partial";var vz=rt([j("light"),j("dark")]).describe("Color theme preference for the host environment."),Bl=rt([j("inline"),j("fullscreen"),j("pip")]).describe("Display mode for UI presentation."),bz=rt([j("--color-background-primary"),j("--color-background-secondary"),j("--color-background-tertiary"),j("--color-background-inverse"),j("--color-background-ghost"),j("--color-background-info"),j("--color-background-danger"),j("--color-background-success"),j("--color-background-warning"),j("--color-background-disabled"),j("--color-text-primary"),j("--color-text-secondary"),j("--color-text-tertiary"),j("--color-text-inverse"),j("--color-text-ghost"),j("--color-text-info"),j("--color-text-danger"),j("--color-text-success"),j("--color-text-warning"),j("--color-text-disabled"),j("--color-border-primary"),j("--color-border-secondary"),j("--color-border-tertiary"),j("--color-border-inverse"),j("--color-border-ghost"),j("--color-border-info"),j("--color-border-danger"),j("--color-border-success"),j("--color-border-warning"),j("--color-border-disabled"),j("--color-ring-primary"),j("--color-ring-secondary"),j("--color-ring-inverse"),j("--color-ring-info"),j("--color-ring-danger"),j("--color-ring-success"),j("--color-ring-warning"),j("--font-sans"),j("--font-mono"),j("--font-weight-normal"),j("--font-weight-medium"),j("--font-weight-semibold"),j("--font-weight-bold"),j("--font-text-xs-size"),j("--font-text-sm-size"),j("--font-text-md-size"),j("--font-text-lg-size"),j("--font-heading-xs-size"),j("--font-heading-sm-size"),j("--font-heading-md-size"),j("--font-heading-lg-size"),j("--font-heading-xl-size"),j("--font-heading-2xl-size"),j("--font-heading-3xl-size"),j("--font-text-xs-line-height"),j("--font-text-sm-line-height"),j("--font-text-md-line-height"),j("--font-text-lg-line-height"),j("--font-heading-xs-line-height"),j("--font-heading-sm-line-height"),j("--font-heading-md-line-height"),j("--font-heading-lg-line-height"),j("--font-heading-xl-line-height"),j("--font-heading-2xl-line-height"),j("--font-heading-3xl-line-height"),j("--border-radius-xs"),j("--border-radius-sm"),j("--border-radius-md"),j("--border-radius-lg"),j("--border-radius-xl"),j("--border-radius-full"),j("--border-width-regular"),j("--shadow-hairline"),j("--shadow-sm"),j("--shadow-md"),j("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),xz=bt(bz.describe(`Style variables for theming MCP apps.
220
+ `.substring(0,i);return n+s+o}function K1(e){return e!=null&&(typeof e==="string"||e.nodeType&&(e.nodeType===1||e.nodeType===9||e.nodeType===11))}function Xu(){let e=window.getSelection(),t=e&&e.rangeCount>0?e.getRangeAt(0).cloneRange():null;On("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 i=window.getSelection();i?.removeAllRanges(),i?.addRange(t)}document.execCommand("createLink",!1,n)})}function E0(){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 i=document.createRange();i.setStartAfter(o),i.setEndAfter(o),e.removeAllRanges(),e.addRange(i)}var Ju=8,V1=[{kind:"exec",command:"bold",icon:"B",title:`Bold (${Ft("B")})`},{kind:"exec",command:"italic",icon:"I",title:`Italic (${Ft("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 (${Ft("K")})`,dividerBefore:!0}];function X1(e){switch(e.kind){case"exec":document.execCommand(e.command);return;case"block":document.execCommand("formatBlock",!1,e.tag);return;case"code":E0();return;case"link":Xu();return}}function A0({hostRef:e,onChange:t}){let[n,o]=E(!1),[i,s]=E({top:0,left:0}),[a,l]=E(0),c=D(null),u=D(null),d=oe(()=>{let m=e.current;if(!m){o(!1);return}let h=window.getSelection();if(!h||h.rangeCount===0||h.isCollapsed){o(!1);return}let g=h.getRangeAt(0);if(!m.contains(g.commonAncestorContainer)){o(!1);return}let v=g.getBoundingClientRect();if(v.width===0&&v.height===0){o(!1);return}let b=a||420,x=Math.max(Ju,Math.min(v.left+v.width/2-b/2,window.innerWidth-b-Ju)),C=Math.max(Ju,v.top-Ju-36);s({top:C,left:x}),o(!0)},[e,a]),p=oe(()=>{if(u.current!==null)return;u.current=requestAnimationFrame(()=>{u.current=null,d()})},[d]);q(()=>(document.addEventListener("selectionchange",p),window.addEventListener("scroll",p,!0),window.addEventListener("resize",p),()=>{if(document.removeEventListener("selectionchange",p),window.removeEventListener("scroll",p,!0),window.removeEventListener("resize",p),u.current!==null)cancelAnimationFrame(u.current)}),[p]),Me(()=>{if(!n)return;let m=c.current;if(!m)return;let h=m.getBoundingClientRect().width;if(h&&Math.abs(h-a)>1)l(h)},[n,a]);let f=oe((m)=>{X1(m),t(),d()},[t,d]);if(!n)return null;return r("div",{ref:c,class:"md-inline-format-bar",style:{top:`${i.top}px`,left:`${i.left}px`},onMouseDown:(m)=>m.preventDefault(),children:V1.flatMap((m,h)=>{let g=r(_e,{label:m.title,children:r("button",{type:"button",class:"md-inline-format-btn","aria-label":m.title,onClick:()=>f(m),children:m.icon},void 0,!1,void 0,this)},`btn-${h}`,!1,void 0,this);return m.dividerBefore?[r("span",{class:"md-inline-format-divider"},`div-${h}`,!1,void 0,this),g]:[g]})},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 R0(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 J1(e){if(Array.isArray(e))return e}function Y1(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var o,i,s,a,l=[],c=!0,u=!1;try{if(s=(n=n.call(e)).next,t===0);else for(;!(c=(o=s.call(n)).done)&&(l.push(o.value),l.length!==t);c=!0);}catch(d){u=!0,i=d}finally{try{if(!c&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return l}}function Q1(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
221
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function eN(e,t){return J1(e)||Y1(e,t)||tN(e,t)||Q1()}function tN(e,t){if(e){if(typeof e=="string")return R0(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)?R0(e,t):void 0}}var{entries:W0,setPrototypeOf:P0,isFrozen:nN,getPrototypeOf:oN,getOwnPropertyDescriptor:rN,freeze:Cn,seal:Tn,create:Vs}=Object,q0=typeof Reflect<"u"&&Reflect,{apply:th,construct:nh}=q0;if(!Cn)Cn=function(t){return t};if(!Tn)Tn=function(t){return t};if(!th)th=function(t,n){for(var o=arguments.length,i=Array(o>2?o-2:0),s=2;s<o;s++)i[s-2]=arguments[s];return t.apply(n,i)};if(!nh)nh=function(t){for(var n=arguments.length,o=Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return new t(...o)};var Gs=nn(Array.prototype.forEach),iN=nn(Array.prototype.lastIndexOf),N0=nn(Array.prototype.pop),Ks=nn(Array.prototype.push),sN=nn(Array.prototype.splice),li=Array.isArray,Tl=nn(String.prototype.toLowerCase),Xm=nn(String.prototype.toString),M0=nn(String.prototype.match),_l=nn(String.prototype.replace),z0=nn(String.prototype.indexOf),aN=nn(String.prototype.trim),lN=nn(Number.prototype.toString),cN=nn(Boolean.prototype.toString),$0=typeof BigInt>"u"?null:nn(BigInt.prototype.toString),L0=typeof Symbol>"u"?null:nn(Symbol.prototype.toString),yn=nn(Object.prototype.hasOwnProperty),Cl=nn(Object.prototype.toString),gn=nn(RegExp.prototype.test),Xi=uN(TypeError);function nn(e){return function(t){if(t instanceof RegExp)t.lastIndex=0;for(var n=arguments.length,o=Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return th(e,t,o)}}function uN(e){return function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];return nh(e,n)}}function at(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Tl;if(P0)P0(e,null);if(!li(t))return e;let o=t.length;while(o--){let i=t[o];if(typeof i==="string"){let s=n(i);if(s!==i){if(!nN(t))t[o]=s;i=s}}e[i]=!0}return e}function dN(e){for(let t=0;t<e.length;t++)if(!yn(e,t))e[t]=null;return e}function Bn(e){let t=Vs(null);for(let o of W0(e)){var n=eN(o,2);let i=n[0],s=n[1];if(yn(e,i))if(li(s))t[i]=dN(s);else if(s&&typeof s==="object"&&s.constructor===Object)t[i]=Bn(s);else t[i]=s}return t}function pN(e){switch(typeof e){case"string":return e;case"number":return lN(e);case"boolean":return cN(e);case"bigint":return $0?$0(e):"0";case"symbol":return L0?L0(e):"Symbol()";case"undefined":return Cl(e);case"function":case"object":{if(e===null)return Cl(e);let t=e,n=Fo(t,"toString");if(typeof n==="function"){let o=n(t);return typeof o==="string"?o:Cl(o)}return Cl(e)}default:return Cl(e)}}function Fo(e,t){while(e!==null){let o=rN(e,t);if(o){if(o.get)return nn(o.get);if(typeof o.value==="function")return nn(o.value)}e=oN(e)}function n(){return null}return n}function fN(e){try{return gn(e,""),!0}catch(t){return!1}}var O0=Cn(["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"]),Jm=Cn(["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"]),Ym=Cn(["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"]),mN=Cn(["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"]),Qm=Cn(["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"]),hN=Cn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),D0=Cn(["#text"]),B0=Cn(["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"]),eh=Cn(["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"]),F0=Cn(["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"]),Yu=Cn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),gN=Tn(/{{[\w\W]*|^[\w\W]*}}/g),yN=Tn(/<%[\w\W]*|^[\w\W]*%>/g),vN=Tn(/\${[\w\W]*/g),bN=Tn(/^data-[\-\w.\u00B7-\uFFFF]+$/),xN=Tn(/^aria-[\-\w]+$/),H0=Tn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),wN=Tn(/^(?:\w+script|data):/i),kN=Tn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),SN=Tn(/^html$/i),_N=Tn(/^[a-z][.\w]*(-[.\w]+)+$/i),U0=Tn(/<[/\w!]/g),j0=Tn(/<[/\w]/g),CN=Tn(/<\/no(script|embed|frames)/i),TN=Tn(/\/>/i),po={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},IN=function(){return typeof window>"u"?null:window},EN=function(t,n){if(typeof t!=="object"||typeof t.createPolicy!=="function")return null;let o=null,i="data-tt-policy-suffix";if(n&&n.hasAttribute(i))o=n.getAttribute(i);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}},Z0=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},ai=function(t,n,o,i){return yn(t,n)&&li(t[n])?at(i.base?Bn(i.base):{},t[n],i.transform):o};function G0(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:IN(),t=(me)=>G0(me);if(t.version="3.4.13",t.removed=[],!e||!e.document||e.document.nodeType!==po.document||!e.Element)return t.isSupported=!1,t;let n=e.document,o=n,i=o.currentScript;e.DocumentFragment;let{HTMLTemplateElement:s,Node:a,Element:l,NodeFilter:c,NamedNodeMap:u}=e;u===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let{DOMParser:d,trustedTypes:p}=e,f=l.prototype,m=Fo(f,"cloneNode"),h=Fo(f,"remove"),g=Fo(f,"nextSibling"),v=Fo(f,"childNodes"),b=Fo(f,"parentNode"),x=Fo(f,"shadowRoot"),C=Fo(f,"attributes"),y=a&&a.prototype?Fo(a.prototype,"nodeType"):null,k=a&&a.prototype?Fo(a.prototype,"nodeName"):null,_=a&&a.prototype?Fo(a.prototype,"ownerDocument"):null;if(typeof s==="function"){let me=n.createElement("template");if(me.content&&me.content.ownerDocument)n=me.content.ownerDocument}let I,w="",P,L=!1,N=0,Y=function(){if(N>0)throw Xi('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.')},B=function(T){Y(),N++;try{return I.createHTML(T)}finally{N--}},J=function(T){Y(),N++;try{return I.createScriptURL(T)}finally{N--}},X=function(){if(!L)P=EN(p,i),L=!0;return P},V=n,{implementation:ee,createNodeIterator:he,createDocumentFragment:A,getElementsByTagName:te}=V,M=o.importNode,O=Z0();t.isSupported=typeof W0==="function"&&typeof b==="function"&&ee&&ee.createHTMLDocument!==void 0;let Pe=gN,Fe=yN,De=vN,Ae=bN,ve=xN,z=wN,re=kN,Ne=_N,ke=H0,ae=null,Se=at({},[...O0,...Jm,...Ym,...Qm,...D0]),de=null,Ue=at({},[...B0,...eh,...F0,...Yu]),xe=Object.seal(Vs(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}})),qe=null,W=null,ye=Object.seal(Vs(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),He=!0,R=!0,ne=!1,Ce=!0,Te=!1,fe=!0,it=!1,Ht=!1,Ye=null,Lt=null,F=!1,Ie=!1,S=!1,K=!1,ue=!0,$e=!1,je="user-content-",le=!0,we=!1,ge={},Le=null,Rt=at({},["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"]),pt=null,pn=at({},["audio","video","img","source","image","track"]),on=null,fs=at({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Pn="http://www.w3.org/1998/Math/MathML",xn="http://www.w3.org/2000/svg",fn="http://www.w3.org/1999/xhtml",cr=fn,ms=!1,ft=null,Ta=at({},[Pn,xn,fn],Xm),Ia=Cn(["mi","mo","mn","ms","mtext"]),ot=at({},Ia),Ot=Cn(["annotation-xml"]),Hn=at({},Ot),Lr=at({},["title","style","font","a","script"]),ur=null,cc=["application/xhtml+xml","text/html"],uc="text/html",Ut=null,hs=null,ZI=n.createElement("form"),Fg=function(T){return T instanceof RegExp||T instanceof Function},bp=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(hs&&hs===T)return;if(!T||typeof T!=="object")T={};T=Bn(T),ur=cc.indexOf(T.PARSER_MEDIA_TYPE)===-1?uc:T.PARSER_MEDIA_TYPE,Ut=ur==="application/xhtml+xml"?Xm:Tl,ae=ai(T,"ALLOWED_TAGS",Se,{transform:Ut}),de=ai(T,"ALLOWED_ATTR",Ue,{transform:Ut}),ft=ai(T,"ALLOWED_NAMESPACES",Ta,{transform:Xm}),on=ai(T,"ADD_URI_SAFE_ATTR",fs,{transform:Ut,base:fs}),pt=ai(T,"ADD_DATA_URI_TAGS",pn,{transform:Ut,base:pn}),Le=ai(T,"FORBID_CONTENTS",Rt,{transform:Ut}),qe=ai(T,"FORBID_TAGS",Bn({}),{transform:Ut}),W=ai(T,"FORBID_ATTR",Bn({}),{transform:Ut}),ge=yn(T,"USE_PROFILES")?T.USE_PROFILES&&typeof T.USE_PROFILES==="object"?Bn(T.USE_PROFILES):T.USE_PROFILES:!1,He=T.ALLOW_ARIA_ATTR!==!1,R=T.ALLOW_DATA_ATTR!==!1,ne=T.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Te=T.SAFE_FOR_TEMPLATES||!1,fe=T.SAFE_FOR_XML!==!1,it=T.WHOLE_DOCUMENT||!1,Ie=T.RETURN_DOM||!1,S=T.RETURN_DOM_FRAGMENT||!1,K=T.RETURN_TRUSTED_TYPE||!1,F=T.FORCE_BODY||!1,ue=T.SANITIZE_DOM!==!1,$e=T.SANITIZE_NAMED_PROPS||!1,le=T.KEEP_CONTENT!==!1,we=T.IN_PLACE||!1,ke=fN(T.ALLOWED_URI_REGEXP)?T.ALLOWED_URI_REGEXP:H0,cr=typeof T.NAMESPACE==="string"?T.NAMESPACE:fn,ot=yn(T,"MATHML_TEXT_INTEGRATION_POINTS")&&T.MATHML_TEXT_INTEGRATION_POINTS&&typeof T.MATHML_TEXT_INTEGRATION_POINTS==="object"?Bn(T.MATHML_TEXT_INTEGRATION_POINTS):at({},Ia),Hn=yn(T,"HTML_INTEGRATION_POINTS")&&T.HTML_INTEGRATION_POINTS&&typeof T.HTML_INTEGRATION_POINTS==="object"?Bn(T.HTML_INTEGRATION_POINTS):at({},Ot);let Z=yn(T,"CUSTOM_ELEMENT_HANDLING")&&T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING==="object"?Bn(T.CUSTOM_ELEMENT_HANDLING):Vs(null);if(xe=Vs(null),yn(Z,"tagNameCheck")&&Fg(Z.tagNameCheck))xe.tagNameCheck=Z.tagNameCheck;if(yn(Z,"attributeNameCheck")&&Fg(Z.attributeNameCheck))xe.attributeNameCheck=Z.attributeNameCheck;if(yn(Z,"allowCustomizedBuiltInElements")&&typeof Z.allowCustomizedBuiltInElements==="boolean")xe.allowCustomizedBuiltInElements=Z.allowCustomizedBuiltInElements;if(Tn(xe),Te)R=!1;if(S)Ie=!0;if(ge){if(ae=at({},D0),de=Vs(null),ge.html===!0)at(ae,O0),at(de,B0);if(ge.svg===!0)at(ae,Jm),at(de,eh),at(de,Yu);if(ge.svgFilters===!0)at(ae,Ym),at(de,eh),at(de,Yu);if(ge.mathMl===!0)at(ae,Qm),at(de,F0),at(de,Yu)}if(ye.tagCheck=null,ye.attributeCheck=null,yn(T,"ADD_TAGS")){if(typeof T.ADD_TAGS==="function")ye.tagCheck=T.ADD_TAGS;else if(li(T.ADD_TAGS)){if(ae===Se)ae=Bn(ae);at(ae,T.ADD_TAGS,Ut)}}if(yn(T,"ADD_ATTR")){if(typeof T.ADD_ATTR==="function")ye.attributeCheck=T.ADD_ATTR;else if(li(T.ADD_ATTR)){if(de===Ue)de=Bn(de);at(de,T.ADD_ATTR,Ut)}}if(yn(T,"ADD_URI_SAFE_ATTR")&&li(T.ADD_URI_SAFE_ATTR))at(on,T.ADD_URI_SAFE_ATTR,Ut);if(yn(T,"FORBID_CONTENTS")&&li(T.FORBID_CONTENTS)){if(Le===Rt)Le=Bn(Le);at(Le,T.FORBID_CONTENTS,Ut)}if(yn(T,"ADD_FORBID_CONTENTS")&&li(T.ADD_FORBID_CONTENTS)){if(Le===Rt)Le=Bn(Le);at(Le,T.ADD_FORBID_CONTENTS,Ut)}if(le)ae["#text"]=!0;if(it)at(ae,["html","head","body"]);if(ae.table)at(ae,["tbody"]),delete qe.tbody;if(T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!=="function")throw Xi('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!=="function")throw Xi('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let ce=I;I=T.TRUSTED_TYPES_POLICY;try{w=B("")}catch(ze){throw I=ce,ze}}else if(T.TRUSTED_TYPES_POLICY===null)I=void 0,w="";else{if(I===void 0)I=X();if(I&&typeof w==="string")w=B("")}if(Cn)Cn(T);hs=T},Hg=at({},[...Jm,...Ym,...mN]),Ug=at({},[...Qm,...hN]),WI=function(T,Z,ce){if(Z.namespaceURI===fn)return T==="svg";if(Z.namespaceURI===Pn)return T==="svg"&&(ce==="annotation-xml"||ot[ce]);return Boolean(Hg[T])},qI=function(T,Z,ce){if(Z.namespaceURI===fn)return T==="math";if(Z.namespaceURI===xn)return T==="math"&&Hn[ce];return Boolean(Ug[T])},GI=function(T,Z,ce){if(Z.namespaceURI===xn&&!Hn[ce])return!1;if(Z.namespaceURI===Pn&&!ot[ce])return!1;return!Ug[T]&&(Lr[T]||!Hg[T])},KI=function(T){let Z=b(T);if(!Z||!Z.tagName)Z={namespaceURI:cr,tagName:"template"};let ce=Tl(T.tagName),ze=Tl(Z.tagName);if(!ft[T.namespaceURI])return!1;if(T.namespaceURI===xn)return WI(ce,Z,ze);if(T.namespaceURI===Pn)return qI(ce,Z,ze);if(T.namespaceURI===fn)return GI(ce,Z,ze);if(ur==="application/xhtml+xml"&&ft[T.namespaceURI])return!0;return!1},Or=function(T){Ks(t.removed,{element:T});try{b(T).removeChild(T)}catch(Z){if(h(T),!b(T))throw Xi("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},dc=function(T){Ea(T);let Z=v(T);if(Z){let ze=[];Gs(Z,(Be)=>{Ks(ze,Be)}),Gs(ze,(Be)=>{try{h(Be)}catch(Qe){}})}let ce=C(T);if(ce)for(let ze=ce.length-1;ze>=0;--ze){let Be=ce[ze],Qe=Be&&Be.name;if(typeof Qe==="string")try{T.removeAttribute(Qe)}catch(St){}}},Si=function(T,Z){try{Ks(t.removed,{attribute:Z.getAttributeNode(T),from:Z})}catch(ce){Ks(t.removed,{attribute:null,from:Z})}if(Z.removeAttribute(T),T==="is")if(Ie||S)try{Or(Z)}catch(ce){}else try{Z.setAttribute(T,"")}catch(ce){}},VI=function(T){let Z=C(T);if(!Z)return;for(let ce=Z.length-1;ce>=0;--ce){let ze=Z[ce],Be=ze&&ze.name;if(typeof Be!=="string"||de[Ut(Be)])continue;try{T.removeAttribute(Be)}catch(Qe){}}},Ea=function(T){let Z=[T];while(Z.length>0){let ce=Z.pop();if((y?y(ce):ce.nodeType)===po.element)VI(ce);let Be=v(ce);if(Be)for(let Qe=Be.length-1;Qe>=0;--Qe)Z.push(Be[Qe])}},XI=function(T){if(!fe)return;let Z=[T];while(Z.length>0){let ce=Z.pop(),ze=y?y(ce):ce.nodeType;if(ze===po.processingInstruction||ze===po.comment&&gn(j0,ce.data)){try{h(ce)}catch(Qe){}continue}if(ze===po.element){let Qe=ce,St=Ut(k?k(ce):ce.nodeName);try{if(Qe.hasAttribute&&Qe.hasAttribute("patchsrc"))Qe.removeAttribute("patchsrc");if(Qe.hasAttribute&&Qe.hasAttribute("for")&&St!=="label"&&St!=="output")Qe.removeAttribute("for")}catch(jt){}}let Be=v(ce);if(Be)for(let Qe=Be.length-1;Qe>=0;--Qe)Z.push(Be[Qe])}},jg=function(T){let Z=null,ce=null;if(F)T="<remove></remove>"+T;else{let Qe=M0(T,/^[\r\n\t ]+/);ce=Qe&&Qe[0]}if(ur==="application/xhtml+xml"&&cr===fn)T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>";let ze=I?B(T):T;if(cr===fn)try{Z=new d().parseFromString(ze,ur)}catch(Qe){}if(!Z||!Z.documentElement){Z=ee.createDocument(cr,"template",null);try{Z.documentElement.innerHTML=ms?w:ze}catch(Qe){}}let Be=Z.body||Z.documentElement;if(T&&ce)Be.insertBefore(n.createTextNode(ce),Be.childNodes[0]||null);if(cr===fn)return te.call(Z,it?"html":"body")[0];return it?Z.documentElement:Be},Zg=function(T){let Z=_?_(T):T.ownerDocument;return he.call(Z||T,T,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},pc=function(T){return T=_l(T,Pe," "),T=_l(T,Fe," "),T=_l(T,De," "),T},xp=function(T){var Z;T.normalize();let ce=_?_(T):T.ownerDocument,ze=he.call(ce||T,T,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),Be=ze.nextNode();while(Be)Be.data=pc(Be.data),Be=ze.nextNode();let Qe=(Z=T.querySelectorAll)===null||Z===void 0?void 0:Z.call(T,"template");if(Qe)Gs(Qe,(St)=>{if(gs(St.content))xp(St.content)})},fc=function(T){let Z=k?k(T):null;if(typeof Z!=="string")return!1;if(Ut(Z)!=="form")return!1;return typeof T.nodeName!=="string"||typeof T.textContent!=="string"||typeof T.removeChild!=="function"||T.attributes!==C(T)||typeof T.removeAttribute!=="function"||typeof T.setAttribute!=="function"||typeof T.namespaceURI!=="string"||typeof T.insertBefore!=="function"||typeof T.hasChildNodes!=="function"||T.nodeType!==y(T)||T.childNodes!==v(T)},gs=function(T){if(!y||typeof T!=="object"||T===null)return!1;try{return y(T)===po.documentFragment}catch(Z){return!1}},Aa=function(T){if(!y||typeof T!=="object"||T===null)return!1;try{return typeof y(T)==="number"}catch(Z){return!1}};function Uo(me,T,Z){if(me.length===0)return;Gs(me,(ce)=>{ce.call(t,T,Z,hs)})}let JI=function(T,Z){if(fe&&T.hasChildNodes()&&!Aa(T.firstElementChild)&&gn(U0,T.textContent)&&gn(U0,T.innerHTML))return!0;if(fe&&T.namespaceURI===fn&&Z==="style"&&Aa(T.firstElementChild))return!0;if(T.nodeType===po.processingInstruction)return!0;if(fe&&T.nodeType===po.comment&&gn(j0,T.data))return!0;return!1},YI=function(T,Z,ce){if(!qe[Z]&&Kg(Z)){if(xe.tagNameCheck instanceof RegExp&&gn(xe.tagNameCheck,Z))return!1;if(xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Z))return!1}if(le&&!Le[Z]){let ze=b(T),Be=v(T);if(Be&&ze){let Qe=Be.length;for(let St=Qe-1;St>=0;--St){let jt=T===ce?m(Be[St],!0):Be[St];ze.insertBefore(jt,g(T))}}}return Or(T),!0},Wg=function(T,Z,ce,ze){if(T.length===0)return Z;return Z===ce||Z===ze?Bn(Z):Z},qg=function(T,Z){if(Uo(O.beforeSanitizeElements,T,null),T!==Z&&b(T)===null){if(we)Ea(T);return!0}if(fc(T))return Or(T),!0;let ce=Ut(k?k(T):T.nodeName);if(ae=Wg(O.uponSanitizeElement,ae,Se,Ye),Uo(O.uponSanitizeElement,T,{tagName:ce,allowedTags:ae}),T!==Z&&b(T)===null){if(we)Ea(T);return!0}if(JI(T,ce))return Or(T),!0;if(qe[ce]||!(ye.tagCheck instanceof Function&&ye.tagCheck(ce))&&!ae[ce]){let Be=YI(T,ce,Z);if(Be===!1)Uo(O.afterSanitizeElements,T,null);return Be}if((y?y(T):T.nodeType)===po.element&&!KI(T))return Or(T),!0;if((ce==="noscript"||ce==="noembed"||ce==="noframes")&&gn(CN,T.innerHTML))return Or(T),!0;if(Te&&T.nodeType===po.text){let Be=pc(T.textContent);if(T.textContent!==Be)Ks(t.removed,{element:T.cloneNode()}),T.textContent=Be}return Uo(O.afterSanitizeElements,T,null),!1},Gg=function(T,Z,ce){if(W[Z])return!1;if(fe&&Z==="patchsrc")return!1;if(fe&&Z==="for"&&T!=="label"&&T!=="output")return!1;if(ue&&(Z==="id"||Z==="name")&&((ce in n)||(ce in ZI)))return!1;let ze=de[Z]||ye.attributeCheck instanceof Function&&ye.attributeCheck(Z,T);if(R&&gn(Ae,Z));else if(He&&gn(ve,Z));else if(!ze)if(Kg(T)&&(xe.tagNameCheck instanceof RegExp&&gn(xe.tagNameCheck,T)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(T))&&(xe.attributeNameCheck instanceof RegExp&&gn(xe.attributeNameCheck,Z)||xe.attributeNameCheck instanceof Function&&xe.attributeNameCheck(Z,T))||Z==="is"&&xe.allowCustomizedBuiltInElements&&(xe.tagNameCheck instanceof RegExp&&gn(xe.tagNameCheck,ce)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(ce)));else return!1;else if(on[Z]);else if(gn(ke,_l(ce,re,"")));else if((Z==="src"||Z==="xlink:href"||Z==="href")&&T!=="script"&&z0(ce,"data:")===0&&pt[T]);else if(ne&&!gn(z,_l(ce,re,"")));else if(ce)return!1;return!0},QI=at({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Kg=function(T){return!QI[Tl(T)]&&gn(Ne,T)},eE=function(T,Z,ce,ze){if(I&&typeof p==="object"&&typeof p.getAttributeType==="function"&&!ce)switch(p.getAttributeType(T,Z)){case"TrustedHTML":return B(ze);case"TrustedScriptURL":return J(ze)}return ze},tE=function(T,Z,ce,ze){try{if(ce)T.setAttributeNS(ce,Z,ze);else T.setAttribute(Z,ze);if(fc(T))Or(T);else N0(t.removed)}catch(Be){Si(Z,T)}},Vg=function(T){Uo(O.beforeSanitizeAttributes,T,null);let Z=T.attributes;if(!Z||fc(T))return;de=Wg(O.uponSanitizeAttribute,de,Ue,Lt);let ce={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:de,forceKeepAttr:void 0},ze=Z.length,Be=Ut(T.nodeName);while(ze--){let Qe=Z[ze],{name:St,namespaceURI:jt,value:Kn}=Qe,Vn=Ut(St),kp=Kn,Un=St==="value"?kp:aN(kp);if(ce.attrName=Vn,ce.attrValue=Un,ce.keepAttr=!0,ce.forceKeepAttr=void 0,Uo(O.uponSanitizeAttribute,T,ce),Un=ce.attrValue,$e&&(Vn==="id"||Vn==="name")&&z0(Un,je)!==0)Si(St,T),Un=je+Un;if(fe&&gn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Un)){Si(St,T);continue}if(Vn==="attributename"&&M0(Un,"href")){Si(St,T);continue}if(ce.forceKeepAttr)continue;if(!ce.keepAttr){Si(St,T);continue}if(!Ce&&gn(TN,Un)){Si(St,T);continue}if(Te)Un=pc(Un);if(!Gg(Be,Vn,Un)){Si(St,T);continue}if(Un=eE(Be,Vn,jt,Un),Un!==kp)tE(T,St,jt,Un)}Uo(O.afterSanitizeAttributes,T,null)},mc=function(T){let Z=null,ce=Zg(T);Uo(O.beforeSanitizeShadowDOM,T,null);while(Z=ce.nextNode()){if(Uo(O.uponSanitizeShadowNode,Z,null),qg(Z,T),Vg(Z),gs(Z.content))mc(Z.content);if((y?y(Z):Z.nodeType)===po.element){let Be=x(Z);if(gs(Be))wp(Be),mc(Be)}}Uo(O.afterSanitizeShadowDOM,T,null)},wp=function(T){let Z=[{node:T,shadow:null}];while(Z.length>0){let ce=Z.pop();if(ce.shadow){mc(ce.shadow);continue}let ze=ce.node,Qe=(y?y(ze):ze.nodeType)===po.element,St=v(ze);if(St)for(let jt=St.length-1;jt>=0;--jt)Z.push({node:St[jt],shadow:null});if(Qe){let jt=k?k(ze):null;if(typeof jt==="string"&&Ut(jt)==="template"){let Kn=ze.content;if(gs(Kn))Z.push({node:Kn,shadow:null})}}if(Qe){let jt=x(ze);if(gs(jt))Z.push({node:null,shadow:jt},{node:jt,shadow:null})}}};return t.sanitize=function(me){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,ce=null,ze=null,Be=null;if(ms=!me,ms)me="<!-->";if(typeof me!=="string"&&!Aa(me)){if(me=pN(me),typeof me!=="string")throw Xi("dirty is not a string, aborting")}if(!t.isSupported)return me;if(Ht)ae=Ye,de=Lt;else bp(T);if(O.uponSanitizeElement.length>0||O.uponSanitizeAttribute.length>0)ae=Bn(ae);if(O.uponSanitizeAttribute.length>0)de=Bn(de);t.removed=[];let Qe=we&&typeof me!=="string"&&Aa(me);if(Qe){XI(me);let Kn=k?k(me):me.nodeName;if(typeof Kn==="string"){let Vn=Ut(Kn);if(!ae[Vn]||qe[Vn])throw dc(me),Xi("root node is forbidden and cannot be sanitized in-place")}if(fc(me))throw dc(me),Xi("root node is clobbered and cannot be sanitized in-place");try{wp(me)}catch(Vn){throw dc(me),Vn}}else if(Aa(me)){if(Z=jg("<!---->"),ce=Z.ownerDocument.importNode(me,!0),ce.nodeType===po.element&&ce.nodeName==="BODY")Z=ce;else if(ce.nodeName==="HTML")Z=ce;else Z.appendChild(ce);wp(ce)}else{if(!Ie&&!Te&&!it&&me.indexOf("<")===-1)return I&&K?B(me):me;if(Z=jg(me),!Z)return Ie?null:K?w:""}if(Z&&F)Or(Z.firstChild);let St=Qe?me:Z;try{let Kn=Zg(St);while(ze=Kn.nextNode())if(qg(ze,St),Vg(ze),gs(ze.content))mc(ze.content)}catch(Kn){if(Qe)dc(me),Gs(t.removed,(Vn)=>{if(Vn.element)Ea(Vn.element)});throw Kn}if(Qe){if(Gs(t.removed,(Kn)=>{if(Kn.element)Ea(Kn.element)}),Te)xp(me);return me}if(Ie){if(Te)xp(Z);if(S){Be=A.call(Z.ownerDocument);while(Z.firstChild)Be.appendChild(Z.firstChild)}else Be=Z;if(de.shadowroot||de.shadowrootmode)Be=M.call(o,Be,!0);return Be}let jt=it?Z.outerHTML:Z.innerHTML;if(it&&ae["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&gn(SN,Z.ownerDocument.doctype.name))jt="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
222
+ `+jt;if(Te)jt=pc(jt);return I&&K?B(jt):jt},t.setConfig=function(){let me=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};bp(me),Ht=!0,Ye=ae,Lt=de},t.clearConfig=function(){hs=null,Ht=!1,Ye=null,Lt=null,I=P,w=""},t.isValidAttribute=function(me,T,Z){if(!hs)bp({});let ce=Ut(me),ze=Ut(T);return Gg(ce,ze,Z)},t.addHook=function(me,T){if(typeof T!=="function")return;if(!yn(O,me))return;Ks(O[me],T)},t.removeHook=function(me,T){if(!yn(O,me))return;if(T!==void 0){let Z=iN(O[me],T);return Z===-1?void 0:sN(O[me],Z,1)[0]}return N0(O[me])},t.removeHooks=function(me){if(!yn(O,me))return;O[me]=[]},t.removeAllHooks=function(){O=Z0()},t}var K0=G0();function er(e){return K0.sanitize(e,{FORBID_TAGS:["form","svg","math"]})}var oh=null;function AN(){if(oh)return oh;let e=new Sl({headingStyle:"atx",codeBlockStyle:"fenced",emDelimiter:"*",bulletListMarker:"-"});return e.use(V0.gfm),e.addRule("wikiLink",{filter:(t)=>t.nodeName==="A"&&t.hasAttribute("data-wiki-markdown"),replacement:(t,n)=>{let o=n.textContent??"";return o===n.getAttribute("data-wiki-label")?n.getAttribute("data-wiki-markdown"):`[[${n.getAttribute("data-wiki-ref")}|${o}]]`}}),oh=e,e}function X0({markdown:e,initialHtml:t,className:n,onChange:o,onSave:i}){let s=D(null),a=D(!1),l=D(!1),c=D(e),u=D(e);Me(()=>{let v=s.current;if(!v)return;let b=er(t),x=u.current!==e;if(u.current=e,!a.current||x&&c.current!==e){a.current=!0,c.current=e,l.current=!1,v.innerHTML=b;for(let k of v.querySelectorAll('input[type="checkbox"][disabled]'))k.removeAttribute("disabled");return}let C=document.createElement("div");C.innerHTML=b;let y=new Map([...C.querySelectorAll("a[data-wiki-ref]")].map((k)=>[k.getAttribute("data-wiki-ref"),k]));for(let k of v.querySelectorAll("a[data-wiki-ref]")){let _=y.get(k.getAttribute("data-wiki-ref"));if(!_)continue;for(let I of["data-wiki-board","data-wiki-card","data-wiki-missing"]){let w=_.getAttribute(I);if(w===null)k.removeAttribute(I);else k.setAttribute(I,w)}k.classList.toggle("is-unresolved",_.classList.contains("is-unresolved"))}},[t,e]);let d=oe(()=>{let v=s.current;if(!v)return"";return AN().turndown(v.innerHTML)},[]),p=oe(()=>{l.current=!0;let v=d();c.current=v,o(v)},[o,d]),f=oe(()=>{let v=s.current;if(!v||!v.isConnected||v.innerHTML==="")return;i?.(l.current?d():e)},[e,i,d]),m=oe((v)=>{if(!(v.metaKey||v.ctrlKey))return;if(v.key==="s"){v.preventDefault(),f();return}if(v.key==="b"){v.preventDefault(),document.execCommand("bold"),p();return}if(v.key==="i"){v.preventDefault(),document.execCommand("italic"),p();return}if(v.key==="k")v.preventDefault(),Xu(),p()},[p,f]),h=oe((v)=>{let b=v.target;if(b instanceof HTMLInputElement&&b.type==="checkbox")b.toggleAttribute("checked",b.checked),p()},[p]),g=oe((v)=>{let b=v.clipboardData?.getData("text/plain");if(b==null)return;v.preventDefault(),document.execCommand("insertText",!1,b),p()},[p]);return r(be,{children:[r("div",{ref:s,class:n,contentEditable:!0,spellcheck:!1,onInput:p,onKeyDown:m,onPaste:g,onClick:h,onBlur:f},void 0,!1,void 0,this),r(A0,{hostRef:s,onChange:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Y0(e,t){let n=e.target.closest("a.wiki-link");if(!n)return!1;if(e.preventDefault(),e.stopPropagation(),n.dataset.wikiBoard)zt({boardId:n.dataset.wikiBoard,...n.dataset.wikiCard?{cardId:n.dataset.wikiCard}:{}});else{let o=n.dataset.wikiRef??"",i=o.split("#")[0];if(n.dataset.wikiMissing||o.includes("#")||Ge.value.some((s)=>s.name.toLocaleLowerCase()===i.toLocaleLowerCase()||s.id===i))hn("remove","Link unavailable","The target is missing or ambiguous. Use a board/card ID in the wiki link to choose it explicitly.");else window.dispatchEvent(new CustomEvent("pmx-open-board-link",{detail:{sourceNodeId:t,wikiRef:i}}))}return!0}function rh({html:e,className:t,style:n,onTaskToggle:o,nodeId:i}){let s=D(null),a=D(o);return a.current=o,q(()=>{let c=s.current;if(!c)return;if(c.replaceChildren(),!e)return;let u=document.createElement("template");if(u.innerHTML=er(e),c.append(u.content.cloneNode(!0)),a.current)for(let d of c.querySelectorAll('input[type="checkbox"][data-pmx-task][disabled]'))d.removeAttribute("disabled")},[e]),r("div",{ref:s,class:t,style:n,onClick:(c)=>{if(Y0(c,i))return;let u=c.target,d=a.current;if(!s.current||!d)return;let f=null;if(u instanceof HTMLInputElement&&u.matches('input[type="checkbox"][data-pmx-task]'))f=u;else{let h=u.closest("li")?.querySelector(":scope > input[data-pmx-task], :scope > p > input[data-pmx-task]");if(h&&c.clientX<=h.getBoundingClientRect().right+6)f=h}if(!f)return;c.preventDefault(),c.stopPropagation(),d(Number(f.dataset.pmxTask))}},void 0,!1,void 0,this)}var J0=new Lm({gfm:!0,breaks:!0});function RN(e,t){let n=(d)=>{let p=[];return J0.walkTokens(J0.lexer(d),(f)=>{if(f.type==="list_item"&&f.task)p.push(!!f.checked)}),p},o=n(e);if(!Number.isInteger(t)||t<0||t>=o.length)return e;let i=[...e.matchAll(/(?:[-*+]|\d{1,9}[.)])[ \t]+\[[ xX]\](?=[ \t]|$)/gm)].map((d)=>d.index+d[0].lastIndexOf("[")+1),s=(d,p)=>{let f=e;for(let m=p;m>=d;m--){let h=i[m];f=f.slice(0,h)+(f[h]===" "?"x":" ")+f.slice(h+1)}return f},a=0,l=i.length-1;while(a<l){let d=Math.floor((a+l)/2);if(n(s(a,d))[t]!==o[t])l=d;else a=d+1}let c=s(a,a),u=n(c);return u.length===o.length&&u.every((d,p)=>d===(p===t?!o[p]:o[p]))?c:e}var Ar=new Map;function ih(e,t){let n=Ar.get(JSON.stringify([e,t]));return!!n&&(n.dirty.value||n.pending.value>0)}async function sh(e,t){let n=Ik(),o=wt,i=Ar.get(JSON.stringify([e,t]));return await i?.saveQueue.current,n()&&o===wt&&se.value===e&&!i?.dirty.value}function Qu({node:e,expanded:t=!1}){let n=Yn(),o=se.value,i=JSON.stringify([o,e.id]),s=Ke(()=>{let A=Ar.get(i);if(A)return A;let te={latestMdRef:{current:typeof e.data.content==="string"?e.data.content:""},renderedMdRef:{current:null},dirty:ie(!1),editBase:{current:{boardId:o,revision:e.contentRevision??0}},saveQueue:{current:Promise.resolve()},nativeSaveAttempts:new Set,pending:ie(0),owners:0};return Ar.set(i,te),te},[i]),{latestMdRef:a,renderedMdRef:l,editBase:c,saveQueue:u}=s,d=e.data.path,[p,f]=E(""),[m,h]=E(""),[g,v]=E(!1),[b,x]=E(!1),[C,y]=E(!1),k=s.dirty.value,_=D(null),I=Ke(()=>({current:null}),[s]),w=Ke(()=>({current:null}),[s]),P=e.data.reviewActive,L=JSON.stringify(e.data.wikiLinks??[]);Me(()=>{s.owners++,Ar.set(i,s),f(a.current);let A=l.current,te=A?.markdown===a.current;return h(te?A.html:""),v(te),()=>{if(s.owners--,!s.owners&&!s.pending.value&&!s.dirty.value&&Ar.get(i)===s)Ar.delete(i)}},[s]),q(()=>{let A=s.dirty.value||s.pending.value>0;if(!A)c.current={boardId:o,revision:e.contentRevision??0};let te=!1;return(async()=>{let M;if(A)M=a.current;else if(d){let Pe=await ol(d);if(te)return;M=Pe.content}else if(typeof e.data.content==="string")M=e.data.content;else{v(!0);return}let O=await Vo(M,e.id,o);if(O===null||te||se.value!==o||(A||s.dirty.value?a.current!==M:!d&&H.value.get(e.id)?.data.content!==M))return;if(l.current={markdown:M,html:O},h(O),v(!0),!A&&!s.dirty.value)a.current=M,f(M),Xe(e.id,{content:M,rendered:O});else if(H.value.get(e.id)?.data.content===M)Xe(e.id,{rendered:O})})(),()=>{te=!0}},[o,d,e.id,e.data.content,L,e.linksRevision]);let N=oe(async(A)=>{let te=A.target.value;s.dirty.value=!0,a.current=te,f(te);let M=await Vo(te,e.id,o);if(M===null||se.value!==o||a.current!==te)return;l.current={markdown:te,html:M},h(M)},[o,s,e.id]),Y=oe(async(A)=>{let te=wt,M={revision:H.value.get(e.id)?.contentRevision??0};s.nativeSaveAttempts.add(M),s.pending.value++,u.current=u.current.then(async()=>{if(te!==wt||se.value!==o||a.current!==A)return;if(tt()){y(!0);let Ae=await ln(e.id,{content:A,expectedBoardId:c.current.boardId,expectedContentRevision:c.current.revision});if(y(!1),!Ae.ok||te!==wt)return;c.current.revision=Ae.contentRevision??c.current.revision;let ve=await Vo(A,e.id,o);if(te!==wt||se.value!==o||a.current!==A)return;let z=H.value.get(e.id);if(!z||(z.contentRevision??0)>c.current.revision)return;if(H.value=new Map(H.value).set(e.id,{...z,contentRevision:c.current.revision,lastEditedBy:Ae.lastEditedBy,data:{...z.data,content:A,...ve!==null?{rendered:ve}:{}}}),s.dirty.value=!1,ve!==null)l.current={markdown:A,html:ve},h(ve);return}let O=await Vo(A,e.id,o);if(O===null||te!==wt||se.value!==o||a.current!==A)return;if(se.value===o&&a.current===A&&l.current?.markdown!==A)l.current={markdown:A,html:O},h(O);let Pe=M.revision,Fe=await ln(e.id,{content:A,data:{rendered:O},expectedBoardId:o,expectedContentRevision:Pe,...d?{persistFile:!0}:{}});if(te!==wt)return;if(Fe.ok&&Fe.contentRevision!==void 0){for(let Ae of s.nativeSaveAttempts)if(Ae.revision===Pe)Ae.revision=Fe.contentRevision}let De=H.value.get(e.id);if(Fe.ok&&Fe.contentRevision!==void 0&&De&&se.value===o&&(De.contentRevision??0)<=Fe.contentRevision){let Ae=l.current,ve=Ae?.markdown!==A;if(H.value=new Map(H.value).set(e.id,{...De,contentRevision:Fe.contentRevision,lastEditedBy:Fe.lastEditedBy,data:{...De.data,content:A,rendered:Ae?.markdown===A?Ae.html:O}}),a.current===A){if(ve)l.current={markdown:A,html:O},h(O);s.dirty.value=!1,f(A)}}});try{await u.current}finally{if(s.nativeSaveAttempts.delete(M),s.pending.value--,!s.owners&&!s.pending.value&&!s.dirty.value&&Ar.get(i)===s)Ar.delete(i)}},[o,d,e.id,s]),B=oe(async()=>{if(!k)return;await Y(p)},[k,p,Y]),J=oe(async()=>{if(l.current?.markdown!==p){let te=await Vo(p,e.id,o);if(te===null||se.value!==o||a.current!==p)return;if(l.current?.markdown!==p)l.current={markdown:p,html:te}}if(se.value!==o||a.current!==p)return;let A=l.current;if(A?.markdown!==p)return;h(A.html),v(!0),x(!1)},[o,p,e.id]),X=oe((A)=>{if((A.metaKey||A.ctrlKey)&&A.key==="s"){A.preventDefault(),B();return}let te=_.current;if(te&&JS(A,te))return;if(te&&A.key==="Tab")A.preventDefault(),XS(te,A.shiftKey)},[B]);w.current=Y;let V=oe((A)=>{if(s.dirty.value=!0,f(A),a.current=A,I.current!==null)window.clearTimeout(I.current);I.current=window.setTimeout(()=>{I.current=null,Y(A)},800)},[Y,s]),ee=oe((A)=>{if(!s.dirty.value&&A===a.current)return;if(s.dirty.value=!0,f(A),a.current=A,I.current!==null)window.clearTimeout(I.current),I.current=null;Y(A)},[Y,s]);q(()=>()=>{if(I.current===null)return;window.clearTimeout(I.current),I.current=null;let A=w.current;if(A)A(a.current)},[s]);let he=P?r("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(b&&t)return r("div",{class:"md-editor-expanded",onKeyDown:X,children:[r("div",{class:"md-editor-toolbar",children:[r("button",{type:"button",class:"md-toolbar-btn",onClick:J,children:[r(uS,{size:14},void 0,!1,void 0,this)," Back to document"]},void 0,!0,void 0,this),r("div",{style:{display:"flex",gap:"6px",alignItems:"center"},children:[d&&r("span",{class:"md-toolbar-path",children:d.split("/").pop()},void 0,!1,void 0,this),r("button",{type:"button",class:`md-toolbar-btn${k?" md-toolbar-btn-primary":""}`,onClick:B,disabled:!k||C,children:C?"Saving…":k?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"md-editor-split",children:[r("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[r("textarea",{ref:_,value:p,onInput:N,spellcheck:!1},void 0,!1,void 0,this),r(Om,{textareaRef:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(rh,{nodeId:e.id,html:m,className:"md-preview"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(b)return r("div",{class:"md-editor-split",style:{height:"100%"},onKeyDown:X,children:[r("div",{style:{flex:1,position:"relative",display:"flex",flexDirection:"column"},children:[r("textarea",{ref:_,value:p,onInput:N,spellcheck:!1},void 0,!1,void 0,this),r(Om,{textareaRef:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(rh,{nodeId:e.id,html:m,className:"md-preview"},void 0,!1,void 0,this),r("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[r("button",{type:"button",onClick:J,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),r("button",{type:"button",onClick:B,disabled:!k||C,style:{padding:"4px 10px",fontSize:"11px",background:k?"color-mix(in srgb, var(--c-accent) 25%, transparent)":"var(--c-input-bg)",border:`1px solid ${k?"var(--c-accent)":"var(--c-line)"}`,borderRadius:"6px",color:k?"var(--c-text)":"var(--c-dim)",cursor:k?"pointer":"default"},children:C?"Saving…":k?"Save":"Saved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(t)return r("div",{class:"md-expanded-document",style:{height:"100%",position:"relative"},onClick:async(A)=>{if(!A.target.closest("a.wiki-link"))return;A.preventDefault(),A.stopPropagation();let te=document.activeElement;if(te instanceof HTMLElement&&A.currentTarget.contains(te))te.blur();if(!await sh(o,e.id))return;Y0(A,e.id)},children:[he,r("div",{class:"md-reader",children:g?r(X0,{markdown:p,initialHtml:m||"<p><br></p>",className:"md-reader-content md-reader-editable",onChange:V,onSave:ee},e.id,!1,void 0,this):r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"24px"},children:"Loading…"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",class:"md-edit-fab",onClick:()=>x(!0),children:"</> Source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{class:"md-card-preview",children:[r("div",{class:"md-card-content",children:[he,r(rh,{nodeId:e.id,html:m,style:{padding:m?"0":"12px",color:m?void 0:"var(--c-dim)"},onTaskToggle:(A)=>{let te=l.current;if(te?.html!==m||te.markdown!==a.current)return;let M=RN(te.markdown,A);if(M!==p)ee(M)}},void 0,!1,void 0,this),!g&&r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"Loading…"},void 0,!1,void 0,this),g&&!m&&r("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&&r("div",{class:"md-import-source",children:["Source material ·"," ",r("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),r("div",{class:"md-card-actions",children:[n&&r("button",{type:"button",class:"md-readme-btn","aria-pressed":n.readmeNodeId===e.id,onClick:()=>void Pk(n.id,n.readmeNodeId===e.id?null:e.id),children:n.readmeNodeId===e.id?"README":"Set as README"},void 0,!1,void 0,this),r("button",{type:"button",class:"md-card-edit",onClick:()=>xo(e.id),children:"Edit"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var ed="pmx-canvas-ax",td="pmx-canvas-ax-ack",Qn="pmx-canvas-html-node",ah="pmx-canvas-json-state",nd="pmx-canvas-ext-app-alive",lh="pmx-canvas-ext-app-paint-probe";function Q0(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 ch="allow-scripts allow-popups allow-popups-to-escape-sandbox";function Xs(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 Il(e,t={}){let n=new URLSearchParams;if(n.set("theme",t.theme??Qt.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 od(e){return Q0(e.type,e.data)}async function rd(e){if(tt()){hn("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=Il(e.id);if(!(await vk(e.id,t)).opened)window.open(t,"_blank","noopener")}var PN={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 e_(e){return PN[e]}function t_(e,t,n,o,i){return e.x<o.position.x+o.size.width+i&&e.x+t+i>o.position.x&&e.y<o.position.y+o.size.height+i&&e.y+n+i>o.position.y}function NN(e,t,n,o,i){return o.some((s)=>t_(e,t,n,s,i))}function id(e,t,n,o,i){return o.find((s)=>t_(e,t,n,s,i))}function sd(e,t,n,o=24){if(e.length===0)return{x:40,y:80};let i=e[e.length-1],s={x:i.position.x+i.size.width+o,y:i.position.y};if(!NN(s,t,n,e,o))return s;let a=40,l=80,c=3000,u=l;for(let p=0;p<20;p++){let f=a;while(f+t<c){let g=id({x:f,y:u},t,n,e,o);if(!g)return{x:f,y:u};f=g.position.x+g.size.width+o}u=e.filter((g)=>g.position.y<=u+n+o&&g.position.y+g.size.height+o>u).reduce((g,v)=>Math.max(g,v.position.y+v.size.height),u)+o}let d=e.reduce((p,f)=>Math.max(p,f.position.y+f.size.height),0);return{x:a,y:d+o}}var Js=37,MN=600,zN=1400,$N=24;function LN(e){return e.type==="html"||e.type==="mermaid"||e.type==="json-render"||e.type==="graph"||e.type==="mcp-app"||e.type==="webpage"}function ON(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 n_(e){return e.collapsed===!0||e.data.strictSize===!0||e.data.userResized===!0||e.type==="group"}function uh(e){return!n_(e)&&!LN(e)}function o_(e,t){if(!uh(e)||t<=0)return null;let n=Math.min(t+Js,MN),o=e_(e.type);return o?Math.max(n,o.height):n}function dh(e){return ON(e)&&!n_(e)}function r_(e,t){if(!dh(e)||!Number.isFinite(t)||t<=0)return null;let n=Math.min(t+Js+$N,zN);return n>e.size.height+8?n:null}function i_(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"),i={...e.position},s=id(i,e.size.width,t,o,24);while(s)i.y=s.position.y+s.size.height+24,s=id(i,e.size.width,t,o,24);return i}function Ys(e,t,n){q(()=>{if(!n)return;let o=null,i=null,s=()=>Wo.value===e.id||Ya.value.some((d)=>d.grabbingNodeId===e.id);function a(){if(o=null,s()||i===null)return;let d=i;i=null;let p=H.value.get(e.id);if(!p)return;let f=r_(p,d);if(f===null)return;let m=i_(p,f,Array.from(H.value.values())),h=m.x!==p.position.x||m.y!==p.position.y,g={size:{width:p.size.width,height:f},...h?{position:m}:{}};un(p.id,g),gu([{id:p.id,...g}],{recordHistory:h})}function l(){if(o!==null)clearTimeout(o);o=i!==null&&!s()?setTimeout(a,300):null}let c=sn(()=>{s(),l()});function u(d){if(d.source!==t.current?.contentWindow)return;let p=d.data;if(!p||p.source!=="pmx-canvas-frame"||p.type!=="content-height"||p.token!==n)return;if(typeof p.height!=="number"||!Number.isFinite(p.height)||p.height<=0)return;i=p.height,l()}return window.addEventListener("message",u),()=>{if(window.removeEventListener("message",u),c(),o!==null)clearTimeout(o)}},[e.id,n])}function DN(e){if(tt())return e.startsWith("/")&&!e.startsWith("//");try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}function Qs(e){let t=_n.value,[n,o]=E(null),i=Boolean(e)&&DN(e),s=t==="srcdoc"&&i;if(q(()=>{if(!s)return;let a=!1;return Gt(`${e}${e.includes("?")?"&":"?"}inline-assets=1`,{credentials:"same-origin"}).then((l)=>l.ok?l.text():Promise.reject(Error(`HTTP ${l.status}`))).then((l)=>{if(!a)o({url:e,html:l})}).catch((l)=>{if(console.error("[surface-frame] srcdoc fetch failed, falling back to src:",e,l),!a)o({url:e,html:""})}),()=>{a=!0}},[s,e]),!e)return{};if(!s)return t===null&&i?{}:{src:e};if(n)return n.html?{srcdoc:n.html}:{src:n.url};return{}}function ad({node:e,expanded:t=!1}){let n=D(null),o=Qt.value,i=Ke(()=>`theme-${crypto.randomUUID()}`,[]),s=Ke(()=>`frame-${crypto.randomUUID()}`,[]),a=typeof e.data.content==="string"?e.data.content:"",l=e.data.fit==="none"?"none":"contain",c=Ke(()=>Xs(`${l}:${a}`),[a,l]),u=Ke(()=>a?Il(e.id,{theme:o,themeToken:i,v:c,frameToken:s}):"",[a,i,c,e.id,s]),d=Qs(u);Ys(e,n,t?"":s);let p=()=>{n.current?.contentWindow?.postMessage({source:Qn,type:"theme-update",token:i,theme:o},"*")};if(q(p,[o,i]),!a)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No diagram source set"},void 0,!1,void 0,this);return r("iframe",{ref:n,class:"html-node-frame",title:typeof e.data.title==="string"?e.data.title:"Mermaid diagram",sandbox:"allow-scripts",...d,onLoad:p,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 ph=["harbor","daylight","high-contrast","midnight","sepia","arctic","ember","forest","volt"];function El(e){return typeof e==="string"&&ph.includes(e)}function fh(e,t="harbor"){return El(e)?e:t}var ea={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 ta(e){return ea[fh(e)].scheme}var ci="io.modelcontextprotocol/related-task",cd="2.0",In=Tw((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),s_=rt([U(),Ze().int()]),a_=U(),o4=Zn({ttl:rt([Ze(),_f()]).optional(),pollInterval:Ze().optional()}),BN=G({ttl:Ze().optional()}),FN=G({taskId:U()}),mh=Zn({progressToken:s_.optional(),[ci]:FN.optional()}),fo=G({_meta:mh.optional()}),Al=fo.extend({task:BN.optional()}),l_=(e)=>Al.safeParse(e).success,En=G({method:U(),params:fo.loose().optional()}),wo=G({_meta:mh.optional()}),ko=G({method:U(),params:wo.loose().optional()}),An=Zn({_meta:mh.optional()}),oa=rt([U(),Ze().int()]),c_=G({jsonrpc:j(cd),id:oa,...En.shape}).strict(),hh=(e)=>c_.safeParse(e).success,u_=G({jsonrpc:j(cd),...ko.shape}).strict(),d_=(e)=>u_.safeParse(e).success,gh=G({jsonrpc:j(cd),id:oa,result:An}).strict(),Rl=(e)=>gh.safeParse(e).success;var vt;(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"})(vt||(vt={}));var yh=G({jsonrpc:j(cd),id:oa.optional(),error:G({code:Ze().int(),message:U(),data:_t().optional()})}).strict();var p_=(e)=>yh.safeParse(e).success;var f_=rt([c_,u_,gh,yh]),r4=rt([gh,yh]),vh=An.strict(),HN=wo.extend({requestId:oa.optional(),reason:U().optional()}),ud=ko.extend({method:j("notifications/cancelled"),params:HN}),UN=G({src:U(),mimeType:U().optional(),sizes:We(U()).optional(),theme:mn(["light","dark"]).optional()}),Pl=G({icons:We(UN).optional()}),na=G({name:U(),title:U().optional()}),Nl=na.extend({...na.shape,...Pl.shape,version:U(),websiteUrl:U().optional(),description:U().optional()}),jN=Vc(G({applyDefaults:ht().optional()}),bt(U(),_t())),ZN=If((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Vc(G({form:jN.optional(),url:In.optional()}),bt(U(),_t()).optional())),WN=Zn({list:In.optional(),cancel:In.optional(),requests:Zn({sampling:Zn({createMessage:In.optional()}).optional(),elicitation:Zn({create:In.optional()}).optional()}).optional()}),qN=Zn({list:In.optional(),cancel:In.optional(),requests:Zn({tools:Zn({call:In.optional()}).optional()}).optional()}),GN=G({experimental:bt(U(),In).optional(),sampling:G({context:In.optional(),tools:In.optional()}).optional(),elicitation:ZN.optional(),roots:G({listChanged:ht().optional()}).optional(),tasks:WN.optional()}),KN=fo.extend({protocolVersion:U(),capabilities:GN,clientInfo:Nl}),VN=En.extend({method:j("initialize"),params:KN});var XN=G({experimental:bt(U(),In).optional(),logging:In.optional(),completions:In.optional(),prompts:G({listChanged:ht().optional()}).optional(),resources:G({subscribe:ht().optional(),listChanged:ht().optional()}).optional(),tools:G({listChanged:ht().optional()}).optional(),tasks:qN.optional()}),JN=An.extend({protocolVersion:U(),capabilities:XN,serverInfo:Nl,instructions:U().optional()}),YN=ko.extend({method:j("notifications/initialized"),params:wo.optional()});var Ji=En.extend({method:j("ping"),params:fo.optional()}),QN=G({progress:Ze(),total:Wt(Ze()),message:Wt(U())}),eM=G({...wo.shape,...QN.shape,progressToken:s_}),dd=ko.extend({method:j("notifications/progress"),params:eM}),tM=fo.extend({cursor:a_.optional()}),Ml=En.extend({params:tM.optional()}),zl=An.extend({nextCursor:a_.optional()}),nM=mn(["working","input_required","completed","failed","cancelled"]),$l=G({taskId:U(),status:nM,ttl:rt([Ze(),_f()]),createdAt:U(),lastUpdatedAt:U(),pollInterval:Wt(Ze()),statusMessage:Wt(U())}),pd=An.extend({task:$l}),oM=wo.merge($l),Ll=ko.extend({method:j("notifications/tasks/status"),params:oM}),fd=En.extend({method:j("tasks/get"),params:fo.extend({taskId:U()})}),md=An.merge($l),hd=En.extend({method:j("tasks/result"),params:fo.extend({taskId:U()})}),i4=An.loose(),gd=Ml.extend({method:j("tasks/list")}),yd=zl.extend({tasks:We($l)}),vd=En.extend({method:j("tasks/cancel"),params:fo.extend({taskId:U()})}),m_=An.merge($l),h_=G({uri:U(),mimeType:Wt(U()),_meta:bt(U(),_t()).optional()}),g_=h_.extend({text:U()}),bh=U().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),y_=h_.extend({blob:bh}),Ol=mn(["user","assistant"]),ra=G({audience:We(Ol).optional(),priority:Ze().min(0).max(1).optional(),lastModified:bf({offset:!0}).optional()}),v_=G({...na.shape,...Pl.shape,uri:U(),description:Wt(U()),mimeType:Wt(U()),annotations:ra.optional(),_meta:Wt(Zn({}))}),rM=G({...na.shape,...Pl.shape,uriTemplate:U(),description:Wt(U()),mimeType:Wt(U()),annotations:ra.optional(),_meta:Wt(Zn({}))}),xh=Ml.extend({method:j("resources/list")}),bd=zl.extend({resources:We(v_)}),wh=Ml.extend({method:j("resources/templates/list")}),kh=zl.extend({resourceTemplates:We(rM)}),Sh=fo.extend({uri:U()}),iM=Sh,_h=En.extend({method:j("resources/read"),params:iM}),xd=An.extend({contents:We(rt([g_,y_]))}),Ch=ko.extend({method:j("notifications/resources/list_changed"),params:wo.optional()}),sM=Sh,aM=En.extend({method:j("resources/subscribe"),params:sM}),lM=Sh,cM=En.extend({method:j("resources/unsubscribe"),params:lM}),uM=wo.extend({uri:U()}),dM=ko.extend({method:j("notifications/resources/updated"),params:uM}),pM=G({name:U(),description:Wt(U()),required:Wt(ht())}),fM=G({...na.shape,...Pl.shape,description:Wt(U()),arguments:Wt(We(pM)),_meta:Wt(Zn({}))}),Th=Ml.extend({method:j("prompts/list")}),Ih=zl.extend({prompts:We(fM)}),mM=fo.extend({name:U(),arguments:bt(U(),U()).optional()}),hM=En.extend({method:j("prompts/get"),params:mM}),Eh=G({type:j("text"),text:U(),annotations:ra.optional(),_meta:bt(U(),_t()).optional()}),Ah=G({type:j("image"),data:bh,mimeType:U(),annotations:ra.optional(),_meta:bt(U(),_t()).optional()}),Rh=G({type:j("audio"),data:bh,mimeType:U(),annotations:ra.optional(),_meta:bt(U(),_t()).optional()}),gM=G({type:j("tool_use"),name:U(),id:U(),input:bt(U(),_t()),_meta:bt(U(),_t()).optional()}),Ph=G({type:j("resource"),resource:rt([g_,y_]),annotations:ra.optional(),_meta:bt(U(),_t()).optional()}),Nh=v_.extend({type:j("resource_link")}),ia=rt([Eh,Ah,Rh,Nh,Ph]),yM=G({role:Ol,content:ia}),vM=An.extend({description:U().optional(),messages:We(yM)}),Mh=ko.extend({method:j("notifications/prompts/list_changed"),params:wo.optional()}),bM=G({title:U().optional(),readOnlyHint:ht().optional(),destructiveHint:ht().optional(),idempotentHint:ht().optional(),openWorldHint:ht().optional()}),xM=G({taskSupport:mn(["required","optional","forbidden"]).optional()}),wd=G({...na.shape,...Pl.shape,description:U().optional(),inputSchema:G({type:j("object"),properties:bt(U(),In).optional(),required:We(U()).optional()}).catchall(_t()),outputSchema:G({type:j("object"),properties:bt(U(),In).optional(),required:We(U()).optional()}).catchall(_t()).optional(),annotations:bM.optional(),execution:xM.optional(),_meta:bt(U(),_t()).optional()}),kd=Ml.extend({method:j("tools/list")}),wM=zl.extend({tools:We(wd)}),Yi=An.extend({content:We(ia).default([]),structuredContent:bt(U(),_t()).optional(),isError:ht().optional()}),s4=Yi.or(An.extend({toolResult:_t()})),kM=Al.extend({name:U(),arguments:bt(U(),_t()).optional()}),Sd=En.extend({method:j("tools/call"),params:kM}),zh=ko.extend({method:j("notifications/tools/list_changed"),params:wo.optional()}),a4=G({autoRefresh:ht().default(!0),debounceMs:Ze().int().nonnegative().default(300)}),b_=mn(["debug","info","notice","warning","error","critical","alert","emergency"]),SM=fo.extend({level:b_}),_M=En.extend({method:j("logging/setLevel"),params:SM}),CM=wo.extend({level:b_,logger:U().optional(),data:_t()}),$h=ko.extend({method:j("notifications/message"),params:CM}),TM=G({name:U().optional()}),IM=G({hints:We(TM).optional(),costPriority:Ze().min(0).max(1).optional(),speedPriority:Ze().min(0).max(1).optional(),intelligencePriority:Ze().min(0).max(1).optional()}),EM=G({mode:mn(["auto","required","none"]).optional()}),AM=G({type:j("tool_result"),toolUseId:U().describe("The unique identifier for the corresponding tool call."),content:We(ia).default([]),structuredContent:G({}).loose().optional(),isError:ht().optional(),_meta:bt(U(),_t()).optional()}),RM=Tf("type",[Eh,Ah,Rh]),ld=Tf("type",[Eh,Ah,Rh,gM,AM]),PM=G({role:Ol,content:rt([ld,We(ld)]),_meta:bt(U(),_t()).optional()}),NM=Al.extend({messages:We(PM),modelPreferences:IM.optional(),systemPrompt:U().optional(),includeContext:mn(["none","thisServer","allServers"]).optional(),temperature:Ze().optional(),maxTokens:Ze().int(),stopSequences:We(U()).optional(),metadata:In.optional(),tools:We(wd).optional(),toolChoice:EM.optional()}),MM=En.extend({method:j("sampling/createMessage"),params:NM}),zM=An.extend({model:U(),stopReason:Wt(mn(["endTurn","stopSequence","maxTokens"]).or(U())),role:Ol,content:RM}),$M=An.extend({model:U(),stopReason:Wt(mn(["endTurn","stopSequence","maxTokens","toolUse"]).or(U())),role:Ol,content:rt([ld,We(ld)])}),LM=G({type:j("boolean"),title:U().optional(),description:U().optional(),default:ht().optional()}),OM=G({type:j("string"),title:U().optional(),description:U().optional(),minLength:Ze().optional(),maxLength:Ze().optional(),format:mn(["email","uri","date","date-time"]).optional(),default:U().optional()}),DM=G({type:mn(["number","integer"]),title:U().optional(),description:U().optional(),minimum:Ze().optional(),maximum:Ze().optional(),default:Ze().optional()}),BM=G({type:j("string"),title:U().optional(),description:U().optional(),enum:We(U()),default:U().optional()}),FM=G({type:j("string"),title:U().optional(),description:U().optional(),oneOf:We(G({const:U(),title:U()})),default:U().optional()}),HM=G({type:j("string"),title:U().optional(),description:U().optional(),enum:We(U()),enumNames:We(U()).optional(),default:U().optional()}),UM=rt([BM,FM]),jM=G({type:j("array"),title:U().optional(),description:U().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:G({type:j("string"),enum:We(U())}),default:We(U()).optional()}),ZM=G({type:j("array"),title:U().optional(),description:U().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:G({anyOf:We(G({const:U(),title:U()}))}),default:We(U()).optional()}),WM=rt([jM,ZM]),qM=rt([HM,UM,WM]),GM=rt([qM,LM,OM,DM]),KM=Al.extend({mode:j("form").optional(),message:U(),requestedSchema:G({type:j("object"),properties:bt(U(),GM),required:We(U()).optional()})}),VM=Al.extend({mode:j("url"),message:U(),elicitationId:U(),url:U().url()}),XM=rt([KM,VM]),JM=En.extend({method:j("elicitation/create"),params:XM}),YM=wo.extend({elicitationId:U()}),QM=ko.extend({method:j("notifications/elicitation/complete"),params:YM}),ez=An.extend({action:mn(["accept","decline","cancel"]),content:If((e)=>e===null?void 0:e,bt(U(),rt([U(),Ze(),ht(),We(U())])).optional())}),tz=G({type:j("ref/resource"),uri:U()});var nz=G({type:j("ref/prompt"),name:U()}),oz=fo.extend({ref:rt([nz,tz]),argument:G({name:U(),value:U()}),context:G({arguments:bt(U(),U()).optional()}).optional()}),rz=En.extend({method:j("completion/complete"),params:oz});var iz=An.extend({completion:Zn({values:We(U()).max(100),total:Wt(Ze().int()),hasMore:Wt(ht())})}),sz=G({uri:U().startsWith("file://"),name:U().optional(),_meta:bt(U(),_t()).optional()}),az=En.extend({method:j("roots/list"),params:fo.optional()}),lz=An.extend({roots:We(sz)}),cz=ko.extend({method:j("notifications/roots/list_changed"),params:wo.optional()}),l4=rt([Ji,VN,rz,_M,hM,Th,xh,wh,_h,aM,cM,Sd,kd,fd,hd,gd,vd]),c4=rt([ud,dd,YN,cz,Ll]),u4=rt([vh,zM,$M,ez,lz,md,yd,pd]),d4=rt([Ji,MM,JM,az,fd,hd,gd,vd]),p4=rt([ud,dd,$h,dM,Ch,zh,Mh,Ll,QM]),f4=rt([vh,JN,iz,vM,Ih,bd,kh,xd,Yi,wM,md,yd,pd]);class lt 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===vt.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new x_(o.elicitations,t)}return new lt(e,t,n)}}class x_ extends lt{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(vt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function _d(e){return!!e._zod}function Cd(e,t){if(_d(e))return Da(e,t);return e.safeParse(t)}function w_(e){if(!e)return;let t;if(_d(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 k_(e){if(_d(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 ui(e){return e==="completed"||e==="failed"||e==="cancelled"}var uz=Symbol("Let zodToJsonSchema decide on which parser to use");var i5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Lh(e){let n=w_(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=k_(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");return o}function Oh(e,t){let n=Cd(e,t);if(!n.success)throw n.error;return n.data}var gz=60000;class Td{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(ud,(t)=>{this._oncancel(t)}),this.setNotificationHandler(dd,(t)=>{this._onprogress(t)}),this.setRequestHandler(Ji,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(fd,async(t,n)=>{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new lt(vt.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(hd,async(t,n)=>{let o=async()=>{let i=t.params.taskId;if(this._taskMessageQueue){let a;while(a=await this._taskMessageQueue.dequeue(i,n.sessionId)){if(a.type==="response"||a.type==="error"){let l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{let d=l,p=new lt(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new lt(vt.InvalidParams,`Task not found: ${i}`);if(!ui(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(ui(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[ci]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(gd,async(t,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new lt(vt.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(vd,async(t,n)=>{try{let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new lt(vt.InvalidParams,`Task not found: ${t.params.taskId}`);if(ui(o.status))throw new lt(vt.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 i=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!i)throw new lt(vt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...i}}catch(o){if(o instanceof lt)throw o;throw new lt(vt.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,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),lt.fromError(vt.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=(i)=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{if(o?.(i,s),Rl(i)||p_(i))this._onresponse(i);else if(hh(i))this._onrequest(i,s);else if(d_(i))this._onnotification(i);else this._onerror(Error(`Unknown message type: ${JSON.stringify(i)}`))},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=lt.fromError(vt.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,i=e.params?._meta?.[ci]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:vt.MethodNotFound,message:"Method not found"}};if(i&&this._taskMessageQueue)this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch((d)=>this._onerror(Error(`Failed to enqueue error response: ${d}`)));else o?.send(u).catch((d)=>this._onerror(Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=l_(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,c={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async(u)=>{if(s.signal.aborted)return;let d={relatedRequestId:e.id};if(i)d.relatedTask={taskId:i};await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(s.signal.aborted)throw new lt(vt.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};if(i&&!f.relatedTask)f.relatedTask={taskId:i};let m=f.relatedTask?.taskId??i;if(m&&l)await l.updateTaskStatus(m,"input_required");return await this.request(u,d,f)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(a)this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async(u)=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};if(i&&this._taskMessageQueue)await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)},async(u)=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:vt.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};if(i&&this._taskMessageQueue)await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId);else await o?.send(d)}).catch((u)=>this._onerror(Error(`Failed to send response: ${u}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===s)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),i=this._progressHandlers.get(o);if(!i){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(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(l);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),Rl(e))n(e);else{let s=new lt(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 i=!1;if(Rl(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")i=!0,this._taskProgressTokens.set(a.taskId,t)}}if(!i)this._progressHandlers.delete(t);if(Rl(e))o(e);else{let s=lt.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 lt?s:new lt(vt.InternalError,String(s))}}return}let i;try{let s=await this.request(e,pd,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new lt(vt.InternalError,"Task creation did not return a task");while(!0){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},ui(a.status)){if(a.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:i},t,n)};else if(a.status==="failed")yield{type:"error",error:new lt(vt.InternalError,`Task ${i} failed`)};else if(a.status==="cancelled")yield{type:"error",error:new lt(vt.InternalError,`Task ${i} was cancelled`)};return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},t,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof lt?s:new lt(vt.InternalError,String(s))}}}request(e,t,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{let d=(b)=>{u(b)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),a)this.assertTaskCapability(e.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};if(n?.onprogress)this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(a)f.params={...f.params,task:a};if(l)f.params={...f.params,_meta:{...f.params?._meta||{},[ci]:l}};let m=(b)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch((C)=>this._onerror(Error(`Failed to send cancellation: ${C}`)));let x=b instanceof lt?b:new lt(vt.RequestTimeout,String(b));u(x)};this._responseHandlers.set(p,(b)=>{if(n?.signal?.aborted)return;if(b instanceof Error)return u(b);try{let x=Cd(t,b.result);if(!x.success)u(x.error);else c(x.data)}catch(x){u(x)}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??gz,g=()=>m(lt.fromError(vt.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=l?.taskId;if(v){let b=(x)=>{let C=this._responseHandlers.get(p);if(C)C(x);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch((x)=>{this._cleanupTimeout(p),u(x)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch((b)=>{this._cleanupTimeout(p),u(b)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},md,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},yd,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},m_,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||{},[ci]: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||{},[ci]:t.relatedTask}}};this._transport?.send(a,t).catch((l)=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ci]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let n=Lh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=Oh(e,o);return Promise.resolve(t(s,i))})}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=Lh(e);this._notificationHandlers.set(n,(o)=>{let i=Oh(e,o);return Promise.resolve(t(i))})}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"&&hh(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);if(s)s(new lt(vt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i);else this._onerror(Error(`Resolver missing for request ${i} 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,i)=>{if(t.aborted){i(new lt(vt.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new lt(vt.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 i=await n.getTask(o,t);if(!i)throw new lt(vt.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,t);let a=await n.getTask(o,t);if(a){let l=Ll.parse({method:"notifications/tasks/status",params:a});if(await this.notification(l),ui(a.status))this._cleanupTaskProgressHandler(o)}},getTaskResult:(o)=>n.getTaskResult(o,t),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,t);if(!a)throw new lt(vt.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ui(a.status))throw new lt(vt.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,t);let l=await n.getTask(o,t);if(l){let c=Ll.parse({method:"notifications/tasks/status",params:l});if(await this.notification(c),ui(l.status))this._cleanupTaskProgressHandler(o)}},listTasks:(o)=>n.listTasks(o,t)}}}var C_="2026-01-26";var yz="ui/notifications/tool-input-partial";var vz=rt([j("light"),j("dark")]).describe("Color theme preference for the host environment."),Bl=rt([j("inline"),j("fullscreen"),j("pip")]).describe("Display mode for UI presentation."),bz=rt([j("--color-background-primary"),j("--color-background-secondary"),j("--color-background-tertiary"),j("--color-background-inverse"),j("--color-background-ghost"),j("--color-background-info"),j("--color-background-danger"),j("--color-background-success"),j("--color-background-warning"),j("--color-background-disabled"),j("--color-text-primary"),j("--color-text-secondary"),j("--color-text-tertiary"),j("--color-text-inverse"),j("--color-text-ghost"),j("--color-text-info"),j("--color-text-danger"),j("--color-text-success"),j("--color-text-warning"),j("--color-text-disabled"),j("--color-border-primary"),j("--color-border-secondary"),j("--color-border-tertiary"),j("--color-border-inverse"),j("--color-border-ghost"),j("--color-border-info"),j("--color-border-danger"),j("--color-border-success"),j("--color-border-warning"),j("--color-border-disabled"),j("--color-ring-primary"),j("--color-ring-secondary"),j("--color-ring-inverse"),j("--color-ring-info"),j("--color-ring-danger"),j("--color-ring-success"),j("--color-ring-warning"),j("--font-sans"),j("--font-mono"),j("--font-weight-normal"),j("--font-weight-medium"),j("--font-weight-semibold"),j("--font-weight-bold"),j("--font-text-xs-size"),j("--font-text-sm-size"),j("--font-text-md-size"),j("--font-text-lg-size"),j("--font-heading-xs-size"),j("--font-heading-sm-size"),j("--font-heading-md-size"),j("--font-heading-lg-size"),j("--font-heading-xl-size"),j("--font-heading-2xl-size"),j("--font-heading-3xl-size"),j("--font-text-xs-line-height"),j("--font-text-sm-line-height"),j("--font-text-md-line-height"),j("--font-text-lg-line-height"),j("--font-heading-xs-line-height"),j("--font-heading-sm-line-height"),j("--font-heading-md-line-height"),j("--font-heading-lg-line-height"),j("--font-heading-xl-line-height"),j("--font-heading-2xl-line-height"),j("--font-heading-3xl-line-height"),j("--border-radius-xs"),j("--border-radius-sm"),j("--border-radius-md"),j("--border-radius-lg"),j("--border-radius-xl"),j("--border-radius-full"),j("--border-width-regular"),j("--shadow-hairline"),j("--shadow-sm"),j("--shadow-md"),j("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),xz=bt(bz.describe(`Style variables for theming MCP apps.
223
223
 
224
224
  Individual style keys are optional - hosts may provide any subset of these values.
225
225
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
226
226
 
227
227
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
228
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),rt([U(),kf()]).describe(`Style variables for theming MCP apps.
228
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),rt([U(),Sf()]).describe(`Style variables for theming MCP apps.
229
229
 
230
230
  Individual style keys are optional - hosts may provide any subset of these values.
231
231
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
@@ -237,10 +237,10 @@ Individual style keys are optional - hosts may provide any subset of these value
237
237
  Values are strings containing CSS values (colors, sizes, font stacks, etc.).
238
238
 
239
239
  Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
240
- for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),wz=G({method:j("ui/open-link"),params:G({url:U().describe("URL to open in the host's browser")})}),a3=G({isError:ht().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),l3=G({isError:ht().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),c3=G({isError:ht().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),kz=G({method:j("ui/notifications/sandbox-proxy-ready"),params:G({})}),$h=G({connectDomains:We(U()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
240
+ for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),wz=G({method:j("ui/open-link"),params:G({url:U().describe("URL to open in the host's browser")})}),a3=G({isError:ht().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),l3=G({isError:ht().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),c3=G({isError:ht().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),kz=G({method:j("ui/notifications/sandbox-proxy-ready"),params:G({})}),Dh=G({connectDomains:We(U()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
241
241
 
242
242
  - Maps to CSP \`connect-src\` directive
243
- - Empty or omitted → no network connections (secure default)`),resourceDomains:We(U()).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:We(U()).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:We(U()).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'`)")}),Lh=G({camera:G({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:G({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:G({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:G({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Sz=G({method:j("ui/notifications/size-changed"),params:G({width:Ze().optional().describe("New width in pixels."),height:Ze().optional().describe("New height in pixels.")})}),u3=G({method:j("ui/notifications/tool-input"),params:G({arguments:bt(U(),_t().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),d3=G({method:j("ui/notifications/tool-input-partial"),params:G({arguments:bt(U(),_t().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),p3=G({method:j("ui/notifications/tool-cancelled"),params:G({reason:U().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),_z=G({fonts:U().optional()}),Cz=G({variables:xz.optional().describe("CSS variables for theming the app."),css:_z.optional().describe("CSS blocks that apps can inject.")}),f3=G({method:j("ui/resource-teardown"),params:G({})}),Tz=bt(U(),_t()),__=G({text:G({}).optional().describe("Host supports text content blocks."),image:G({}).optional().describe("Host supports image content blocks."),audio:G({}).optional().describe("Host supports audio content blocks."),resource:G({}).optional().describe("Host supports resource content blocks."),resourceLink:G({}).optional().describe("Host supports resource link content blocks."),structuredContent:G({}).optional().describe("Host supports structured content.")}),Iz=G({method:j("ui/notifications/request-teardown"),params:G({}).optional()}),Ez=G({experimental:G({}).optional().describe("Experimental features (structure TBD)."),openLinks:G({}).optional().describe("Host supports opening external URLs."),downloadFile:G({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:G({listChanged:ht().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:G({listChanged:ht().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:G({}).optional().describe("Host accepts log messages."),sandbox:G({permissions:Lh.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:$h.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:__.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:__.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),Az=G({experimental:G({}).optional().describe("Experimental features (structure TBD)."),tools:G({listChanged:ht().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:We(Bl).optional().describe("Display modes the app supports.")}),Rz=G({method:j("ui/notifications/initialized"),params:G({}).optional()}),m3=G({csp:$h.optional().describe("Content Security Policy configuration for UI resources."),permissions:Lh.optional().describe("Sandbox permissions requested by the UI resource."),domain:U().optional().describe(`Dedicated origin for view sandbox.
243
+ - Empty or omitted → no network connections (secure default)`),resourceDomains:We(U()).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:We(U()).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:We(U()).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'`)")}),Bh=G({camera:G({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:G({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:G({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:G({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),Sz=G({method:j("ui/notifications/size-changed"),params:G({width:Ze().optional().describe("New width in pixels."),height:Ze().optional().describe("New height in pixels.")})}),u3=G({method:j("ui/notifications/tool-input"),params:G({arguments:bt(U(),_t().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),d3=G({method:j("ui/notifications/tool-input-partial"),params:G({arguments:bt(U(),_t().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),p3=G({method:j("ui/notifications/tool-cancelled"),params:G({reason:U().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),_z=G({fonts:U().optional()}),Cz=G({variables:xz.optional().describe("CSS variables for theming the app."),css:_z.optional().describe("CSS blocks that apps can inject.")}),f3=G({method:j("ui/resource-teardown"),params:G({})}),Tz=bt(U(),_t()),S_=G({text:G({}).optional().describe("Host supports text content blocks."),image:G({}).optional().describe("Host supports image content blocks."),audio:G({}).optional().describe("Host supports audio content blocks."),resource:G({}).optional().describe("Host supports resource content blocks."),resourceLink:G({}).optional().describe("Host supports resource link content blocks."),structuredContent:G({}).optional().describe("Host supports structured content.")}),Iz=G({method:j("ui/notifications/request-teardown"),params:G({}).optional()}),Ez=G({experimental:G({}).optional().describe("Experimental features (structure TBD)."),openLinks:G({}).optional().describe("Host supports opening external URLs."),downloadFile:G({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:G({listChanged:ht().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:G({listChanged:ht().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:G({}).optional().describe("Host accepts log messages."),sandbox:G({permissions:Bh.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Dh.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:S_.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:S_.optional().describe("Host supports receiving content messages (ui/message) from the view.")}),Az=G({experimental:G({}).optional().describe("Experimental features (structure TBD)."),tools:G({listChanged:ht().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:We(Bl).optional().describe("Display modes the app supports.")}),Rz=G({method:j("ui/notifications/initialized"),params:G({}).optional()}),m3=G({csp:Dh.optional().describe("Content Security Policy configuration for UI resources."),permissions:Bh.optional().describe("Sandbox permissions requested by the UI resource."),domain:U().optional().describe(`Dedicated origin for view sandbox.
244
244
 
245
245
  Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
246
246
 
@@ -254,10 +254,10 @@ Boolean requesting whether a visible border and background is provided by the ho
254
254
 
255
255
  - \`true\`: request visible border + background
256
256
  - \`false\`: request no visible border + background
257
- - omitted: host decides border`)}),C_=G({method:j("ui/request-display-mode"),params:G({mode:Bl.describe("The display mode being requested.")})}),h3=G({mode:Bl.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),Pz=rt([j("model"),j("app")]).describe("Tool visibility scope - who can access the tool."),g3=G({resourceUri:U().optional(),visibility:We(Pz).optional().describe(`Who can access this tool. Default: ["model", "app"]
257
+ - omitted: host decides border`)}),__=G({method:j("ui/request-display-mode"),params:G({mode:Bl.describe("The display mode being requested.")})}),h3=G({mode:Bl.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),Pz=rt([j("model"),j("app")]).describe("Tool visibility scope - who can access the tool."),g3=G({resourceUri:U().optional(),visibility:We(Pz).optional().describe(`Who can access this tool. Default: ["model", "app"]
258
258
  - "model": Tool visible to and callable by the agent
259
- - "app": Tool callable by the app from this server only`)}),y3=G({mimeTypes:We(U()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),Nz=G({method:j("ui/download-file"),params:G({contents:We(rt([Eh,Ah])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Mz=G({method:j("ui/message"),params:G({role:j("user").describe('Message role, currently only "user" is supported.'),content:We(ra).describe("Message content blocks (text, image, etc.).")})}),v3=G({method:j("ui/notifications/sandbox-resource-ready"),params:G({html:U().describe("HTML content to load into the inner iframe."),sandbox:U().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:$h.optional().describe("CSP configuration from resource metadata."),permissions:Lh.optional().describe("Sandbox permissions from resource metadata.")})}),b3=G({method:j("ui/notifications/tool-result"),params:Yi.describe("Standard MCP tool execution result.")}),I_=G({toolInfo:G({id:na.optional().describe("JSON-RPC id of the tools/call request."),tool:xd.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:vz.optional().describe("Current color theme preference."),styles:Cz.optional().describe("Style configuration for theming the app."),displayMode:Bl.optional().describe("How the UI is currently displayed."),availableDisplayModes:We(Bl).optional().describe("Display modes the host supports."),containerDimensions:rt([G({height:Ze().describe("Fixed container height in pixels.")}),G({maxHeight:rt([Ze(),kf()]).optional().describe("Maximum container height in pixels.")})]).and(rt([G({width:Ze().describe("Fixed container width in pixels.")}),G({maxWidth:rt([Ze(),kf()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
260
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:U().optional().describe("User's language and region preference in BCP 47 format."),timeZone:U().optional().describe("User's timezone in IANA format."),userAgent:U().optional().describe("Host application identifier."),platform:rt([j("web"),j("desktop"),j("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:G({touch:ht().optional().describe("Whether the device supports touch input."),hover:ht().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:G({top:Ze().describe("Top safe area inset in pixels."),right:Ze().describe("Right safe area inset in pixels."),bottom:Ze().describe("Bottom safe area inset in pixels."),left:Ze().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),x3=G({method:j("ui/notifications/host-context-changed"),params:I_.describe("Partial context update containing only changed fields.")}),zz=G({method:j("ui/update-model-context"),params:G({content:We(ra).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:bt(U(),_t().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),$z=G({method:j("ui/initialize"),params:G({appInfo:Nl.describe("App identification (name and version)."),appCapabilities:Az.describe("Features and capabilities this app provides."),protocolVersion:U().describe("Protocol version this app supports.")})}),w3=G({protocolVersion:U().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Nl.describe("Host application identification and version."),hostCapabilities:Ez.describe("Features and capabilities provided by the host."),hostContext:I_.describe("Rich context about the host environment.")}).passthrough();class Oh{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=m_.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!==yz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}function E_(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 Lz=[T_];class Dh extends Cd{_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($z,(i)=>this._oninitialize(i)),this.setRequestHandler(Ji,(i,s)=>(this.onping?.(i.params,s),{})),this.setRequestHandler(C_,(i)=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;set onsizechange(e){this.setNotificationHandler(Sz,(t)=>e(t.params))}set onsandboxready(e){this.setNotificationHandler(kz,(t)=>e(t.params))}set oninitialized(e){this.setNotificationHandler(Rz,(t)=>e(t.params))}set onmessage(e){this.setRequestHandler(Mz,async(t,n)=>e(t.params,n))}set onopenlink(e){this.setRequestHandler(wz,async(t,n)=>e(t.params,n))}set ondownloadfile(e){this.setRequestHandler(Nz,async(t,n)=>e(t.params,n))}set onrequestteardown(e){this.setNotificationHandler(Iz,(t)=>e(t.params))}set onrequestdisplaymode(e){this.setRequestHandler(C_,async(t,n)=>e(t.params,n))}set onloggingmessage(e){this.setNotificationHandler(Nh,async(t)=>{e(t.params)})}set onupdatemodelcontext(e){this.setRequestHandler(zz,async(t,n)=>e(t.params,n))}set oncalltool(e){this.setRequestHandler(kd,async(t,n)=>e(t.params,n))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}set onlistresources(e){this.setRequestHandler(yh,async(t,n)=>e(t.params,n))}set onlistresourcetemplates(e){this.setRequestHandler(vh,async(t,n)=>e(t.params,n))}set onreadresource(e){this.setRequestHandler(wh,async(t,n)=>e(t.params,n))}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}set onlistprompts(e){this.setRequestHandler(Sh,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:Lz.includes(t)?t:T_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let o of Object.keys(e)){let i=this._hostContext[o],s=e[o];if(Oz(i,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},Tz,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},Yi,{signal:o.signal}),t.tools.listChanged)this._client.setNotificationHandler(Ph,(n)=>this.sendToolListChanged(n.params))}if(t.resources){if(this.onlistresources=async(n,o)=>this._client.request({method:"resources/list",params:n},vd,{signal:o.signal}),this.onlistresourcetemplates=async(n,o)=>this._client.request({method:"resources/templates/list",params:n},bh,{signal:o.signal}),this.onreadresource=async(n,o)=>this._client.request({method:"resources/read",params:n},bd,{signal:o.signal}),t.resources.listChanged)this._client.setNotificationHandler(kh,(n)=>this.sendResourceListChanged(n.params))}if(t.prompts){if(this.onlistprompts=async(n,o)=>this._client.request({method:"prompts/list",params:n},_h,{signal:o.signal}),t.prompts.listChanged)this._client.setNotificationHandler(Rh,(n)=>this.sendPromptListChanged(n.params))}}return super.connect(e)}}function Oz(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Bh(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Dz(e){return Bh(e)&&Array.isArray(e.content)&&e.content.every((t)=>Bh(t)&&typeof t.type==="string")}function Bz(...e){for(let t of e)if(typeof t==="string"){if(t.trim().length>0)return t}return}function Fz(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 Fh(e){let t=e.success===!1;if(Dz(e.result))return{...e.result,isError:e.result.isError===!0||t};let n=Bh(e.result)?e.result:null,o=Bz(e.detailedContent,e.content,n?.detailedContent,n?.content,n?.textResultForLlm,n?.text,n?.message,typeof e.result==="string"?e.result:void 0,e.error)??Fz(e.result);return{content:o?[{type:"text",text:o}]:[],isError:t}}function A_(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 R_(e){return Boolean(e)&&typeof e==="object"&&e!==null&&!Array.isArray(e)&&"ok"in e&&typeof e.ok==="boolean"}async function Hz(e,t){let n=await Gt("/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||!R_(o)||!o.ok||typeof o.url!=="string"){let i=R_(o)&&o.error?o.error:`Frame document request failed with HTTP ${n.status}`;throw Error(i)}return o.url}function P_(e,t){let n=_n.value,[o,i]=E(null),[s,a]=E(0),l=D(0);q(()=>{if(i(null),!e||n!=="src")return;let u=!1;return l.current=Zi.value,Hz(e,t).then((d)=>{if(!u)i(d)}).catch((d)=>{console.error("[iframe-document] failed to create frame document:",d)}),()=>{u=!0}},[e,t,n,s]);let c=Zi.value;return q(()=>{if(n!=="src"||c===l.current)return;if(!o){a((d)=>d+1);return}let u=!1;return Gt(o,{method:"HEAD"}).then((d)=>{if(u)return;if(d.ok){l.current=c;return}a((p)=>p+1)}).catch(()=>{}),()=>{u=!0}},[c,o,n]),Ke(()=>{if(n==="srcdoc"&&e)return{attributes:{srcdoc:e},ready:!0,key:`srcdoc-${Vs(e)}`};return{attributes:o?{src:o}:{},ready:Boolean(o),key:o??""}},[o,n,e])}function ia(e){let{enabled:t,token:n,nodeId:o,sourceSurface:i,iframeRef:s}=e;Me(()=>{if(!t||!n)return;function a(l){if(l.source!==s.current?.contentWindow)return;let c=l.data;if(!c||c.source!==Qu||c.token!==n||c.nodeId!==o)return;let u=c.interaction;if(!u||typeof u.type!=="string")return;let d=u.type;vu({type:d,sourceNodeId:o,sourceSurface:i,...u.payload&&typeof u.payload==="object"?{payload:u.payload}:{}}).then((p)=>{if(p.ok)hn("context","AX interaction",d,[o]);s.current?.contentWindow?.postMessage({source:ed,token:n,...c.correlationId?{correlationId:c.correlationId}:{},interaction:{type:d},result:p},"*")})}return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[t,n,o,i])}async function Qi(e,t){let o=await(await Gt(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 es(e){return/AppleWebKit/.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/.test(e)}function Uz(e){let{userAgent:t,visibilityState:n,rect:o,viewport:i,alreadyRearmed:s}=e;if(s)return!1;if(!es(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<i.height&&o.left<i.width}var B_=1000,N_=7000;function vn(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});jz({t:Date.now(),nodeId:e,event:t})}var M_=[],Hh=null;function jz(e){if(M_.push({...e,...typeof document<"u"?{visibility:document.visibilityState}:{}}),Hh)return;Hh=setTimeout(()=>{Hh=null;let t=M_.splice(0);if(t.length===0)return;Gt("/api/canvas/debug/ext-app-recovery",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:t})}).catch(()=>{})},1500)}var z_=Promise.resolve();function $_(e){z_=z_.then(async()=>{if(!e.remount())return;await e.awaitBoot(),await new Promise((t)=>setTimeout(t,B_))}).catch(()=>{})}function Zz(e,t){let n=typeof e.data.html==="string"?e.data.html:"",o=typeof e.data.serverName==="string"?e.data.serverName:"",i=typeof e.data.appSessionId==="string"?e.data.appSessionId:"",s=typeof e.data.sessionStatus==="string"?e.data.sessionStatus:"";return`${e.id}:${t}:${o}:${i}:${s}:${n}`}function Wz(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 L_(e,t,n){if(await e.sendToolInput({arguments:t}),n)await e.sendToolResult(n)}function qz(e){return typeof e==="string"&&e.trim().length>0?e.trim():sh}function Gz(e,t){return`<script data-pmx-canvas-ax-bridge>
259
+ - "app": Tool callable by the app from this server only`)}),y3=G({mimeTypes:We(U()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),Nz=G({method:j("ui/download-file"),params:G({contents:We(rt([Ph,Nh])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Mz=G({method:j("ui/message"),params:G({role:j("user").describe('Message role, currently only "user" is supported.'),content:We(ia).describe("Message content blocks (text, image, etc.).")})}),v3=G({method:j("ui/notifications/sandbox-resource-ready"),params:G({html:U().describe("HTML content to load into the inner iframe."),sandbox:U().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Dh.optional().describe("CSP configuration from resource metadata."),permissions:Bh.optional().describe("Sandbox permissions from resource metadata.")})}),b3=G({method:j("ui/notifications/tool-result"),params:Yi.describe("Standard MCP tool execution result.")}),T_=G({toolInfo:G({id:oa.optional().describe("JSON-RPC id of the tools/call request."),tool:wd.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:vz.optional().describe("Current color theme preference."),styles:Cz.optional().describe("Style configuration for theming the app."),displayMode:Bl.optional().describe("How the UI is currently displayed."),availableDisplayModes:We(Bl).optional().describe("Display modes the host supports."),containerDimensions:rt([G({height:Ze().describe("Fixed container height in pixels.")}),G({maxHeight:rt([Ze(),Sf()]).optional().describe("Maximum container height in pixels.")})]).and(rt([G({width:Ze().describe("Fixed container width in pixels.")}),G({maxWidth:rt([Ze(),Sf()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
260
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:U().optional().describe("User's language and region preference in BCP 47 format."),timeZone:U().optional().describe("User's timezone in IANA format."),userAgent:U().optional().describe("Host application identifier."),platform:rt([j("web"),j("desktop"),j("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:G({touch:ht().optional().describe("Whether the device supports touch input."),hover:ht().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:G({top:Ze().describe("Top safe area inset in pixels."),right:Ze().describe("Right safe area inset in pixels."),bottom:Ze().describe("Bottom safe area inset in pixels."),left:Ze().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),x3=G({method:j("ui/notifications/host-context-changed"),params:T_.describe("Partial context update containing only changed fields.")}),zz=G({method:j("ui/update-model-context"),params:G({content:We(ia).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:bt(U(),_t().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),$z=G({method:j("ui/initialize"),params:G({appInfo:Nl.describe("App identification (name and version)."),appCapabilities:Az.describe("Features and capabilities this app provides."),protocolVersion:U().describe("Protocol version this app supports.")})}),w3=G({protocolVersion:U().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Nl.describe("Host application identification and version."),hostCapabilities:Ez.describe("Features and capabilities provided by the host."),hostContext:T_.describe("Rich context about the host environment.")}).passthrough();class Fh{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=f_.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!==yz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}function I_(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 Lz=[C_];class Hh extends Td{_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($z,(i)=>this._oninitialize(i)),this.setRequestHandler(Ji,(i,s)=>(this.onping?.(i.params,s),{})),this.setRequestHandler(__,(i)=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;set onsizechange(e){this.setNotificationHandler(Sz,(t)=>e(t.params))}set onsandboxready(e){this.setNotificationHandler(kz,(t)=>e(t.params))}set oninitialized(e){this.setNotificationHandler(Rz,(t)=>e(t.params))}set onmessage(e){this.setRequestHandler(Mz,async(t,n)=>e(t.params,n))}set onopenlink(e){this.setRequestHandler(wz,async(t,n)=>e(t.params,n))}set ondownloadfile(e){this.setRequestHandler(Nz,async(t,n)=>e(t.params,n))}set onrequestteardown(e){this.setNotificationHandler(Iz,(t)=>e(t.params))}set onrequestdisplaymode(e){this.setRequestHandler(__,async(t,n)=>e(t.params,n))}set onloggingmessage(e){this.setNotificationHandler($h,async(t)=>{e(t.params)})}set onupdatemodelcontext(e){this.setRequestHandler(zz,async(t,n)=>e(t.params,n))}set oncalltool(e){this.setRequestHandler(Sd,async(t,n)=>e(t.params,n))}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}set onlistresources(e){this.setRequestHandler(xh,async(t,n)=>e(t.params,n))}set onlistresourcetemplates(e){this.setRequestHandler(wh,async(t,n)=>e(t.params,n))}set onreadresource(e){this.setRequestHandler(_h,async(t,n)=>e(t.params,n))}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}set onlistprompts(e){this.setRequestHandler(Th,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:Lz.includes(t)?t:C_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let o of Object.keys(e)){let i=this._hostContext[o],s=e[o];if(Oz(i,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},Tz,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},Yi,{signal:o.signal}),t.tools.listChanged)this._client.setNotificationHandler(zh,(n)=>this.sendToolListChanged(n.params))}if(t.resources){if(this.onlistresources=async(n,o)=>this._client.request({method:"resources/list",params:n},bd,{signal:o.signal}),this.onlistresourcetemplates=async(n,o)=>this._client.request({method:"resources/templates/list",params:n},kh,{signal:o.signal}),this.onreadresource=async(n,o)=>this._client.request({method:"resources/read",params:n},xd,{signal:o.signal}),t.resources.listChanged)this._client.setNotificationHandler(Ch,(n)=>this.sendResourceListChanged(n.params))}if(t.prompts){if(this.onlistprompts=async(n,o)=>this._client.request({method:"prompts/list",params:n},Ih,{signal:o.signal}),t.prompts.listChanged)this._client.setNotificationHandler(Mh,(n)=>this.sendPromptListChanged(n.params))}}return super.connect(e)}}function Oz(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Uh(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Dz(e){return Uh(e)&&Array.isArray(e.content)&&e.content.every((t)=>Uh(t)&&typeof t.type==="string")}function Bz(...e){for(let t of e)if(typeof t==="string"){if(t.trim().length>0)return t}return}function Fz(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 jh(e){let t=e.success===!1;if(Dz(e.result))return{...e.result,isError:e.result.isError===!0||t};let n=Uh(e.result)?e.result:null,o=Bz(e.detailedContent,e.content,n?.detailedContent,n?.content,n?.textResultForLlm,n?.text,n?.message,typeof e.result==="string"?e.result:void 0,e.error)??Fz(e.result);return{content:o?[{type:"text",text:o}]:[],isError:t}}function E_(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 A_(e){return Boolean(e)&&typeof e==="object"&&e!==null&&!Array.isArray(e)&&"ok"in e&&typeof e.ok==="boolean"}async function Hz(e,t){let n=await Gt("/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||!A_(o)||!o.ok||typeof o.url!=="string"){let i=A_(o)&&o.error?o.error:`Frame document request failed with HTTP ${n.status}`;throw Error(i)}return o.url}function R_(e,t){let n=_n.value,[o,i]=E(null),[s,a]=E(0),l=D(0);q(()=>{if(i(null),!e||n!=="src")return;let u=!1;return l.current=Zi.value,Hz(e,t).then((d)=>{if(!u)i(d)}).catch((d)=>{console.error("[iframe-document] failed to create frame document:",d)}),()=>{u=!0}},[e,t,n,s]);let c=Zi.value;return q(()=>{if(n!=="src"||c===l.current)return;if(!o){a((d)=>d+1);return}let u=!1;return Gt(o,{method:"HEAD"}).then((d)=>{if(u)return;if(d.ok){l.current=c;return}a((p)=>p+1)}).catch(()=>{}),()=>{u=!0}},[c,o,n]),Ke(()=>{if(n==="srcdoc"&&e)return{attributes:{srcdoc:e},ready:!0,key:`srcdoc-${Xs(e)}`};return{attributes:o?{src:o}:{},ready:Boolean(o),key:o??""}},[o,n,e])}function sa(e){let{enabled:t,token:n,nodeId:o,sourceSurface:i,iframeRef:s}=e;Me(()=>{if(!t||!n)return;function a(l){if(l.source!==s.current?.contentWindow)return;let c=l.data;if(!c||c.source!==ed||c.token!==n||c.nodeId!==o)return;let u=c.interaction;if(!u||typeof u.type!=="string")return;let d=u.type;vu({type:d,sourceNodeId:o,sourceSurface:i,...u.payload&&typeof u.payload==="object"?{payload:u.payload}:{}}).then((p)=>{if(p.ok)hn("context","AX interaction",d,[o]);s.current?.contentWindow?.postMessage({source:td,token:n,...c.correlationId?{correlationId:c.correlationId}:{},interaction:{type:d},result:p},"*")})}return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[t,n,o,i])}async function Qi(e,t){let o=await(await Gt(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 es(e){return/AppleWebKit/.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/.test(e)}function Uz(e){let{userAgent:t,visibilityState:n,rect:o,viewport:i,alreadyRearmed:s}=e;if(s)return!1;if(!es(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<i.height&&o.left<i.width}var D_=1000,P_=7000;function vn(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});jz({t:Date.now(),nodeId:e,event:t})}var N_=[],Zh=null;function jz(e){if(N_.push({...e,...typeof document<"u"?{visibility:document.visibilityState}:{}}),Zh)return;Zh=setTimeout(()=>{Zh=null;let t=N_.splice(0);if(t.length===0)return;Gt("/api/canvas/debug/ext-app-recovery",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:t})}).catch(()=>{})},1500)}var M_=Promise.resolve();function z_(e){M_=M_.then(async()=>{if(!e.remount())return;await e.awaitBoot(),await new Promise((t)=>setTimeout(t,D_))}).catch(()=>{})}function Zz(e,t){let n=typeof e.data.html==="string"?e.data.html:"",o=typeof e.data.serverName==="string"?e.data.serverName:"",i=typeof e.data.appSessionId==="string"?e.data.appSessionId:"",s=typeof e.data.sessionStatus==="string"?e.data.sessionStatus:"";return`${e.id}:${t}:${o}:${i}:${s}:${n}`}function Wz(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 $_(e,t,n){if(await e.sendToolInput({arguments:t}),n)await e.sendToolResult(n)}function qz(e){return typeof e==="string"&&e.trim().length>0?e.trim():ch}function Gz(e,t){return`<script data-pmx-canvas-ax-bridge>
261
261
  (function () {
262
262
  const PMX_AX_TOKEN = ${JSON.stringify(e)};
263
263
  const PMX_AX_NODE_ID = ${JSON.stringify(t)};
@@ -275,7 +275,7 @@ container holding the app. Specify either width or maxWidth, and either height o
275
275
  }, 10000);
276
276
  pending.set(correlationId, function (result) { clearTimeout(timer); resolve(result); });
277
277
  window.parent.postMessage({
278
- source: '${Qu}',
278
+ source: '${ed}',
279
279
  token: PMX_AX_TOKEN,
280
280
  nodeId: PMX_AX_NODE_ID,
281
281
  correlationId: correlationId,
@@ -288,7 +288,7 @@ container holding the app. Specify either width or maxWidth, and either height o
288
288
  };
289
289
  window.addEventListener('message', function (event) {
290
290
  const m = event.data;
291
- if (!m || m.source !== '${ed}' || m.token !== PMX_AX_TOKEN) return;
291
+ if (!m || m.source !== '${td}' || m.token !== PMX_AX_TOKEN) return;
292
292
  const result = m.result || { ok: false };
293
293
  const resolver = m.correlationId ? pending.get(m.correlationId) : undefined;
294
294
  if (resolver) { pending.delete(m.correlationId); resolver(result); }
@@ -302,7 +302,7 @@ container holding the app. Specify either width or maxWidth, and either height o
302
302
  (function () {
303
303
  var TOKEN = ${JSON.stringify(e)};
304
304
  var NODE_ID = ${JSON.stringify(t)};
305
- window.parent.postMessage({ source: '${td}', token: TOKEN, nodeId: NODE_ID }, '*');
305
+ window.parent.postMessage({ source: '${nd}', token: TOKEN, nodeId: NODE_ID }, '*');
306
306
  // Paint-tick answers (Finding N): a double rAF only fires when this frame's
307
307
  // rendering pipeline is actually running — a frame whose layer WebKit never
308
308
  // composites stays silent, and that silence drives the parent's recovery
@@ -372,23 +372,23 @@ container holding the app. Specify either width or maxWidth, and either height o
372
372
  requestAnimationFrame(function () {
373
373
  requestAnimationFrame(function () {
374
374
  var v = contentVerdict();
375
- window.parent.postMessage({ source: '${td}', token: TOKEN, nodeId: NODE_ID, kind: 'paint-tick', content: v.content, detail: v.detail }, '*');
375
+ window.parent.postMessage({ source: '${nd}', token: TOKEN, nodeId: NODE_ID, kind: 'paint-tick', content: v.content, detail: v.detail }, '*');
376
376
  });
377
377
  });
378
378
  }
379
379
  window.addEventListener('message', function (event) {
380
380
  var m = event.data;
381
- if (m && m.source === '${ih}' && m.token === TOKEN) sendPaintTick();
381
+ if (m && m.source === '${lh}' && m.token === TOKEN) sendPaintTick();
382
382
  });
383
383
  sendPaintTick();
384
384
  })();
385
- </script>`}function O_(){return"<style data-pmx-canvas-ext-app-base>html, body { background: transparent !important; }</style>"}function D_(e,t){if(!t)return e;let n=/<head\b[^>]*>/i.exec(e);if(n?.index!==void 0){let i=n.index+n[0].length;return`${e.slice(0,i)}${t}${e.slice(i)}`}let o=/<body\b[^>]*>/i.exec(e);if(o?.index!==void 0){let i=o.index+o[0].length;return`${e.slice(0,i)}${t}${e.slice(i)}`}return`${t}${e}`}function sa(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 Uh(e,t){let n=e?.getBoundingClientRect();return{width:sa(e?.clientWidth??0,sa(n?.width??0,t.width)),height:sa(e?.clientHeight??0,sa(n?.height??0,t.height))}}function Vz(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0&&!t}function Xz(e,t){return Math.max(sa(e,1),sa(t,1))}function F_({node:e,expanded:t=!1}){let n=D(null),o=D(null),i=D(null),s=D(null),a=D({}),l=D(void 0),c=D(!1),u=D(void 0),d=D(null),p=D(!1),f=D(null),m=D(0),h=D([]),g=D(""),v=D(!1),b=D(!1),x=D([]),C=D(!1),y=D(!1),k=D(!1),_=D(!1),[I,w]=E("loading"),[P,L]=E(null),[N,Y]=E(0),[B,J]=E(!1),[X,V]=E(!1),[ee,he]=E(()=>t||typeof navigator>"u"||typeof window>"u"||!es(navigator.userAgent)),A=e.data.html,te=e.data.serverName,M=e.data.appSessionId,O=e.data.toolInput??{},Pe=e.data.toolResult,Fe=e.data.toolName??"ext-app",De=e.data.toolDefinition,Ae=e.data.toolCallId,ve=typeof Ae==="string"||typeof Ae==="number"?Ae:void 0,z=e.data.resourceMeta,re=e.data.sessionStatus,Ne=e.data.sessionError,ke=e.size.height,ae=e.id,Se=Zz(e,N),pe=qz(null),xe=e.data.axCapabilities?.enabled===!0&&typeof A==="string"&&A.length>0,qe=Ke(()=>`ax-${crypto.randomUUID()}`,[]),W=xe?Gz(qe,ae):"",ye=typeof A==="string"&&A.length>0?Kz(qe,ae):"",He=P_(D_(A??"",O_()+ye+W),pe);q(()=>{function le(we){if(we.source!==n.current?.contentWindow)return;let ge=we.data;if(!ge||ge.source!==td||ge.token!==qe||ge.nodeId!==ae)return;if(b.current=!0,ge.kind==="paint-tick"){let Le=ge,Rt={content:Le.content===!0,detail:typeof Le.detail==="string"?Le.detail:""};for(let pt of h.current.splice(0))pt(Rt)}}return window.addEventListener("message",le),()=>window.removeEventListener("message",le)},[qe,ae]),q(()=>{if(ee)return;$_({remount:()=>{if(_.current)return!1;return vn(ae,"mount-slot"),he(!0),!0},awaitBoot:()=>new Promise((le)=>{let we=window.setTimeout(ge,N_);function ge(){window.clearTimeout(we),le()}x.current.push(ge)})})},[]),ia({enabled:xe,token:qe,nodeId:ae,sourceSurface:"mcp-app",iframeRef:n});let R=3,ne=(le)=>{if(m.current>=R)return vn(ae,`remount-cap-hit (${le})`),!1;if(C.current)return!0;return m.current+=1,C.current=!0,vn(ae,`remount-queued #${m.current} (${le})`),$_({remount:()=>{if(C.current=!1,_.current||!t&&Bt.value===ae)return vn(ae,"remount-skipped"),J(!1),!1;return y.current=typeof document<"u"&&document.visibilityState==="hidden",vn(ae,`remount-run #${m.current}`),w("loading"),Y((we)=>we+1),!0},awaitBoot:()=>new Promise((we)=>{let ge=window.setTimeout(Le,N_);function Le(){window.clearTimeout(ge),we()}x.current.push(Le)})}),!0},Ce=1500,Ie=()=>new Promise((le)=>{let we=n.current?.contentWindow;if(!we||_.current){le("timeout");return}let ge=!1,Le=window.setTimeout(()=>{if(ge)return;ge=!0,le("timeout")},Ce);h.current.push((Rt)=>{if(ge)return;ge=!0,window.clearTimeout(Le),g.current=Rt.detail,le(Rt.content?"content-verified":"tick-no-content")}),we.postMessage({source:ih,token:qe},"*")}),fe=async(le)=>{let we=Date.now()+le;while(Date.now()<we&&!_.current){if(await Ie()==="content-verified")return!0;await new Promise((ge)=>window.setTimeout(ge,400))}return!1},it=()=>new Promise((le)=>{let we=n.current;if(!we){le();return}let ge=we.style.width,Le=we.style.height;we.style.width="140%",we.style.height="140%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{we.style.width=ge,we.style.height=Le,vn(ae,"soft-expand-cycle"),le()})})}),Ht=600,Ye=()=>{if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;let le=n.current;if(!le||_.current)return;if(!Uz({userAgent:navigator.userAgent,visibilityState:document.visibilityState,rect:le.getBoundingClientRect(),viewport:{width:window.innerWidth,height:window.innerHeight},alreadyRearmed:k.current}))return;k.current=!0,window.setTimeout(()=>{if(_.current||document.visibilityState==="visible")return;m.current=0,V(!1),y.current=!1,vn(ae,"assume-visible-rearm"),ne("assume-visible")},Ht)},Lt=(le="")=>{let we=g.current?` [${g.current}]`:"";return typeof document<"u"&&document.visibilityState==="hidden"?`paint-ok (content-verified)${we}${le} (host hidden)`:`paint-ok (content-verified)${we}${le}`},F=async()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!es(navigator.userAgent))return;J(!0);let le=await Ie();if(le==="content-verified"){vn(ae,Lt()),J(!1),Ye();return}if(vn(ae,le==="tick-no-content"?`paint-fail (tick without content: ${g.current||"unknown"})`:"paint-fail (no tick)"),await it(),le=await Ie(),le==="content-verified"){vn(ae,Lt(" (after soft-expand)")),J(!1),Ye();return}if(_.current)return;if(le==="tick-no-content"&&await fe(3000)){vn(ae,Lt(" (after content wait)")),J(!1),Ye();return}if(_.current)return;if(!ne("paint-fail"))vn(ae,"recovery-exhausted"),J(!1),V(!0),Ye()};q(()=>{if(t)return;if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;if(!es(navigator.userAgent))return;function le(){if(document.visibilityState!=="visible")return;if(!y.current||_.current)return;y.current=!1,m.current=0,V(!1),vn(ae,"visible-again-rearm"),ne("visible-after-hidden-boot")}return document.addEventListener("visibilitychange",le),()=>document.removeEventListener("visibilitychange",le)},[t,ae]);let Ee=6000;q(()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!es(navigator.userAgent))return;if(!He.ready||!ee)return;let le=window.setTimeout(()=>{if(v.current||b.current||_.current)return;ne("boot-watchdog")},Ee);return()=>window.clearTimeout(le)},[Se,He.ready,t,ee]),q(()=>()=>{_.current=!0;for(let le of x.current.splice(0))le();for(let le of h.current.splice(0))le({content:!1,detail:"unmounted"})},[]);let S=(le)=>ea(le),K=t||Bt.value===ae;a.current=O,l.current=Pe;let ue=re==="error"&&typeof A==="string"&&A.length>0,$e=re==="error"?ue?`Live session unavailable — showing saved content. Reopen the app to restore interactivity.${Ne?` (${Ne})`:""}`:Ne??"Saved app session is unavailable. Reopen the app to restore interactivity.":"Reconnecting saved app session...",je=(le)=>{let we=l.current;if(!le||!p.current||!we)return null;if(u.current===we)return null;if(u.current&&A_(u.current,we))return u.current=we,null;if(d.current)return d.current;let ge=le.sendToolResult(we).then(()=>{u.current=we,c.current=!0,w("done")}).catch((Le)=>{let Rt=Le instanceof Error?Le.message:String(Le);throw L(`Tool result delivery failed: ${Rt}`),Le}).finally(()=>{d.current=null});return d.current=ge,ge};if(q(()=>{if(!A||!He.ready||!ee)return;let le=n.current;if(!le)return;let we=!1,ge=null,Le=null,Rt=null,pt=null,pn=null;c.current=!1,u.current=void 0,d.current=null,p.current=!1,v.current=!1,b.current=!1;let on=()=>{if(!ge)return;clearTimeout(ge),ge=null};return(async()=>{if(!A)return;let Pn=le.contentWindow;if(!Pn)throw Error("Ext-app iframe window is unavailable");let xn=(ot=Bt.value===ae?"fullscreen":"inline")=>({theme:S(Qt.value),platform:"web",containerDimensions:Uh(le,{width:e.size.width,height:ke}),displayMode:ot,locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,...De?{toolInfo:{id:ve,tool:De}}:{}}),fn=()=>{if(pt!==null)return;pt=requestAnimationFrame(()=>{if(pt=null,we||!p.current)return;ft.setHostContext?.(xn())})},cr=()=>{if(pn!==null)return;pn=requestAnimationFrame(()=>{pn=requestAnimationFrame(()=>{if(pn=null,we||!p.current)return;ft.sendHostContextChange?.(xn())})})},ms=()=>{if(!es(navigator.userAgent))return;if(Le)clearTimeout(Le);Le=setTimeout(()=>{if(Le=null,we)return;F()},B_+200)},ft=new Dh(null,{name:"PMX Canvas",version:"1.0.0"},{openLinks:{},serverTools:{listChanged:!1},serverResources:{listChanged:!1},logging:{},updateModelContext:{text:{},structuredContent:{}}},{hostContext:xn(K?"fullscreen":"inline")});ft.onsizechange=async({height:ot})=>{let Ot=H.value.get(ae);if(!Ot||Ot.data.userResized===!0)return{};if(Vz(ot,Bt.value===ae)){let Hn=Uh(le.parentElement??le,{width:e.size.width,height:ke}),Lr=Xz(ot,Hn.height);le.style.height=`${Lr}px`;let ur=Ot.size,cc=Math.max(ur.height,Lr+Xs);if(Math.abs(cc-ur.height)>8){if(Cu(ae,{width:ur.width,height:cc}),s.current!==null)window.clearTimeout(s.current);s.current=window.setTimeout(()=>{s.current=null;let uc=H.value.get(ae);if(uc&&uc.data.userResized!==!0)dn({recordHistory:!1})},0)}}return{}},ft.onopenlink=async({url:ot})=>(window.open(ot,"_blank","noopener"),{}),ft.onsandboxready=async()=>{await ft.sendSandboxResourceReady({html:D_(A,O_()),sandbox:sh,...z?.csp?{csp:z.csp}:{},...z?.permissions?{permissions:z.permissions}:{}})},ft.onrequestdisplaymode=async({mode:ot})=>{let{nextMode:Ot,shouldExpand:Hn,shouldCollapse:Lr}=Wz(ot,K);if(Hn)xo(ae);else if(Lr)Cr();return{mode:Ot}},ft.oncalltool=async(ot)=>{if(!M)throw Error($e);try{let Ot=await Qi("/api/ext-app/call-tool",{sessionId:M,nodeId:ae,serverName:te,toolName:ot.name,arguments:ot.arguments??{}});return L(null),Ot}catch(Ot){let Hn=Ot instanceof Error?Ot.message:String(Ot);throw L(`Tool call failed: ${Hn}`),Ot}},ft.setRequestHandler(wd,async()=>{if(!M)return{tools:[]};return Qi("/api/ext-app/list-tools",{sessionId:M})}),ft.onlistresources=async()=>M?Qi("/api/ext-app/list-resources",{sessionId:M}):{resources:[]},ft.onlistresourcetemplates=async()=>M?Qi("/api/ext-app/list-resource-templates",{sessionId:M}):{resourceTemplates:[]},ft.onreadresource=async(ot)=>{if(!M)throw Error($e);return Qi("/api/ext-app/read-resource",{sessionId:M,uri:ot.uri})},ft.onlistprompts=async()=>M?Qi("/api/ext-app/list-prompts",{sessionId:M}):{prompts:[]},ft.onupdatemodelcontext=async(ot)=>{if(!M)return{};return await Qi("/api/ext-app/model-context",{nodeId:ae,...Array.isArray(ot.content)?{content:ot.content}:{},...ot.structuredContent&&typeof ot.structuredContent==="object"?{structuredContent:ot.structuredContent}:{}}),{}};let Ca=new Oh(Pn,Pn);if(ft.oninitialized=()=>{if(we)return;on(),p.current=!0,v.current=!0,vn(ae,"initialized"),w("ready"),L(null),Promise.resolve(ft.sendHostContextChange(xn(K?"fullscreen":"inline"))).then(()=>L_(ft,a.current,void 0)).then(()=>je(ft)).then(()=>{let ot=()=>{for(let Ot of x.current.splice(0))Ot()};if(typeof navigator<"u"&&es(navigator.userAgent))fe(4000).then((Ot)=>{vn(ae,Ot?"settled (content-verified)":`settled (content-timeout${g.current?`: ${g.current}`:""})`),ot()});else vn(ae,"settled"),ot();cr(),ms()}).catch((ot)=>{let Ot=ot instanceof Error?ot.message:String(ot);L(`Bridge bootstrap failed: ${Ot}`)})},ge=setTimeout(()=>{if(we||p.current)return;let ot=l.current,Ot=xn(K?"fullscreen":"inline");p.current=!0,ft.setHostContext?.(Ot),Promise.resolve(ft.sendHostContextChange(Ot)).then(()=>L_(ft,a.current,ot)).then(()=>{if(c.current=Boolean(ot),ot)u.current=ot;if(w(ot?"done":"ready"),L(null),cr(),ms(),b.current){vn(ae,"settled (fallback)");for(let Hn of x.current.splice(0))Hn()}}).catch((Hn)=>{let Lr=Hn instanceof Error?Hn.message:String(Hn);L(`Bridge bootstrap fallback failed: ${Lr}`)})},1200),await ft.connect(Ca),we){on(),await Ca.close();return}if(o.current=ft,i.current=Ca,Rt=new ResizeObserver(fn),Rt.observe(le),le.parentElement)Rt.observe(le.parentElement);let Ta=!0;f.current=Qt.subscribe((ot)=>{if(Ta){Ta=!1;return}if(we)return;ft.setHostContext?.({...xn(),theme:S(ot)}),ft.sendHostContextChange?.(xn())}),je(ft)})().catch((Pn)=>{on(),console.error("[ext-app] Bridge init failed:",Pn),L(Pn?.message??"Bridge initialization failed")}),()=>{if(we=!0,on(),Le)clearTimeout(Le),Le=null;if(Rt?.disconnect(),Rt=null,pt!==null)cancelAnimationFrame(pt),pt=null;if(pn!==null)cancelAnimationFrame(pn),pn=null;if(p.current=!1,d.current=null,f.current?.(),f.current=null,s.current!==null)window.clearTimeout(s.current),s.current=null;if(o.current=null,i.current)i.current.close().catch((Pn)=>{console.error("[ext-app] transport close failed:",Pn)}),i.current=null}},[Se,He.key,ee]),q(()=>{if(Pe&&o.current&&(I==="ready"||I==="done"))je(o.current)},[Pe,I]),q(()=>{let le=o.current;if(n.current)n.current.style.height="100%";if(!le||!p.current)return;let we=null,ge=null;return we=requestAnimationFrame(()=>{we=null,ge=requestAnimationFrame(()=>{if(ge=null,!p.current)return;let Le={theme:S(Qt.value),platform:"web",containerDimensions:Uh(n.current,{width:e.size.width,height:ke}),displayMode:K?"fullscreen":"inline",locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone};le.setHostContext?.(Le),le.sendHostContextChange?.(Le)})}),()=>{if(we!==null)cancelAnimationFrame(we);if(ge!==null)cancelAnimationFrame(ge)}},[K,ke]),!A)return r("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--c-muted)",fontSize:"13px",flexDirection:"column",gap:"8px"},children:[r("div",{style:{opacity:0.6},children:["Loading ",Fe," viewer..."]},void 0,!0,void 0,this),r("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),r("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{style:{flex:1,width:"100%",height:"100%",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[re&&re!=="ready"&&r("div",{style:{padding:"6px 10px",fontSize:"11px",background:re==="error"&&!ue?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 10%, transparent)",color:re==="error"&&!ue?"var(--c-danger)":"var(--c-warn)",borderBottom:`1px solid ${re==="error"&&!ue?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 15%, transparent)"}`},children:$e},void 0,!1,void 0,this),P&&r("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:[r("span",{children:"⚠"},void 0,!1,void 0,this),r("span",{style:{flex:1},children:P},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>{L(null),w("loading"),Y((le)=>le+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),r("button",{type:"button",onClick:()=>L(null),"aria-label":"Dismiss error",style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{style:{flex:1,position:"relative",display:"flex",minHeight:0,height:"100%"},children:[ee&&r("iframe",{ref:n,...He.attributes,sandbox:pe,allow:E_(z?.permissions),style:{flex:1,width:"100%",height:"100%",minHeight:0,border:"none",background:"var(--c-panel)",pointerEvents:K?"auto":"none"},title:`Ext App: ${Fe}`},Se,!1,void 0,this),X&&!P&&r("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:[r("div",{children:"App surface failed to paint."},void 0,!1,void 0,this),r("button",{type:"button",onClick:(le)=>{le.stopPropagation(),vn(ae,"manual-retry"),m.current=0,V(!1),w("loading"),Y((we)=>we+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),(I==="loading"||B)&&!P&&!X&&r("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:[r("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),r("div",{children:I==="loading"?`Connecting to ${Fe}...`:"Finishing paint..."},void 0,!1,void 0,this),r("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!K&&!(X&&!P)&&r("button",{type:"button",onClick:(le)=>{le.stopPropagation(),xo(ae)},class:"ext-app-preview-catcher",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 Fl=new Map,H_=!1;function U_(e,t,n,o){if(!H_)H_=!0,sn(()=>{let l=H.value,c=Po.value;for(let[u,d]of Fl){let p=l.get(u);if(!p||d.epoch!==c||d.version!==p.data.specVersion||d.documentUrl!==p.data.url){for(let f of d.owners)f.cancel();Fl.delete(u)}}}),window.addEventListener("message",(l)=>{let c=l.data;if(!c||c.source!==rh||typeof c.nodeId!=="string")return;let u=Fl.get(c.nodeId),d=u?.owners.findIndex((h)=>h.token===c.token&&h.source===l.source)??-1;if(!u||d<0)return;if(c.type==="mounted"){u.owners[d].mounted();return}if(c.type==="ready"){u.owners[d].ready();return}if(c.type!=="snapshot")return;if(!c.state||typeof c.state!=="object"||Array.isArray(c.state))return;let{ax:p,...f}=c.state;u.state=f;let m=u.owners.slice(0,d);u.owners=u.owners.slice(d);for(let h of m)h.cancel()});let i=H.value.get(e);if(!i||o?.aborted)return Promise.resolve("cancelled");let s=Fl.get(e)??{epoch:Po.value,version:i.data.specVersion,documentUrl:i.data.url,state:null,owners:[]};Fl.set(e,s);let a=new Promise((l)=>{let c=(p)=>{if(clearTimeout(d),o?.removeEventListener("abort",u.cancel),p!==!0)s.owners=s.owners.filter((f)=>f!==u);l(p)},u={token:t,source:n,mounted:()=>clearTimeout(d),ready:()=>c(!0),cancel:()=>c("cancelled")},d=setTimeout(()=>c(!1),1e4);for(let p of s.owners.filter((f)=>f.source===n))p.cancel();while(s.owners.length>1)s.owners[0].cancel();s.owners.push(u),o?.addEventListener("abort",u.cancel,{once:!0})});return n.postMessage({source:rh,type:"restore",token:t,state:s.state},"*"),a}function Jz(e,t,n,o,i,s,a,l){if(!e)return e;try{let c=tt()&&e.startsWith("/"),u=new URL(e,c?"https://pmx.invalid":window.location.origin);if(u.searchParams.set("theme",ea(Qt.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(i)u.searchParams.set("axNodeId",i);if(s)u.searchParams.set("frameToken",s);if(a)u.searchParams.set("fit","content");if(l)u.searchParams.set("stateToken",l);return c?`${u.pathname}${u.search}`:u.toString()}catch{return e}}function Yz(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 jh({source:e,iframeRef:t,onLoad:n,onDocumentLoad:o,title:i,className:s="mcp-app-frame",sandbox:a="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",allow:l="clipboard-read; clipboard-write",tabIndex:c}){let u=e.src??e.srcdoc??"",[d,p]=E({key:u,source:e,attempt:0}),[f,m]=E(null),h=D(0),g=D(new Set);Me(()=>{h.current+=1;for(let b of g.current)b.abort();if(g.current.clear(),!u||u===d.key){m(null);return}if(!d.key){p({key:u,source:e,attempt:0});return}m({key:u,source:e,attempt:0})},[u,d.key]),q(()=>()=>{h.current+=1;for(let b of g.current)b.abort();g.current.clear()},[]);let v=(b,x)=>r("iframe",{ref:x?void 0:t,...b.source,class:s,sandbox:a,allow:l,tabIndex:c,inert:x,"aria-hidden":x?!0:void 0,loading:_n.value==="srcdoc"?void 0:"lazy",onLoad:async(C)=>{let y=x?++h.current:h.current,k=C.currentTarget,_=new AbortController;g.current.add(_);let I=o?.(k,_.signal),w=I?await I:void 0;if(g.current.delete(_),h.current!==y||w==="cancelled")return;if(w===!1){if(b.attempt===0){let P={...b,attempt:1};if(x)m(P);else p(P)}else{if(x)m(null);hn("remove","Viewer could not load",`${x?"Keeping the last view. ":""}Reload to retry.`)}return}if(!x){n();return}requestAnimationFrame(()=>requestAnimationFrame(()=>{if(h.current!==y)return;t.current=k,p(b),m(null),n()}))},style:{position:"absolute",inset:0,width:"100%",height:"100%",visibility:"visible",zIndex:x?0:1,background:"var(--c-panel-soft)"},title:i},`${b.key}:${b.attempt}`,!1,void 0,this);return r("div",{class:"mcp-app-frame-stack",children:[v(d,!1),f&&v(f,!0)]},void 0,!0,void 0,this)}function di({node:e,expanded:t=!1}){if(e.data.mode==="ext-app")return r(F_,{node:e,expanded:t},void 0,!1,void 0,this);return r(Qz,{node:e,expanded:t},void 0,!1,void 0,this)}function Qz({node:e,expanded:t}){let n=D(null),o=e.type==="mcp-app"&&e.data.viewerType==="web-artifact",i=e.type==="json-render"||e.type==="graph",s=e.data.axCapabilities?.enabled,l=(i||o)&&(o?s===!0:s!==!1),c=o?"mcp-app":"json-render",u=Ke(()=>l?`ax-${crypto.randomUUID()}`:"",[l]),d=lh(e)&&!t,p=Ke(()=>d?`frame-${crypto.randomUUID()}`:"",[d]);Js(e,n,p),ia({enabled:l&&Boolean(u),token:u,nodeId:e.id,sourceSurface:c,iframeRef:n});let f=Oo.value,m=()=>{if(!l||!u||f==null)return;n.current?.contentWindow?.postMessage({source:Qn,type:"ax-update",token:u,state:f},"*")};q(m,[l,u,f]);let h=typeof e.data.specVersion==="number"?e.data.specVersion:void 0,g=Ke(()=>i?`ui-${crypto.randomUUID()}`:"",[i,h,e.data.url]),v=Jz(e.data.url||"",t,h,u||void 0,l?e.id:void 0,p||void 0,d,g||void 0),b=Ys(v),x=e.data.sourceServer||"",C=e.data.hostMode||"hosted",y=e.data.fallbackReason,k=e.data.trustedDomain===!0||Yz(v);if(C==="fallback")return r("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[r("div",{style:{color:"var(--c-warn)",display:"flex",alignItems:"center",gap:"6px"},children:[r("span",{children:"⚠"},void 0,!1,void 0,this),r("span",{children:"Cannot embed — opened externally"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y&&r("div",{style:{color:"var(--c-muted)",fontSize:"11px"},children:["Reason: ",y]},void 0,!0,void 0,this),r("a",{href:v,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all"},children:v},void 0,!1,void 0,this),x&&r("div",{style:{color:"var(--c-dim)",fontSize:"10px"},children:["Source: ",x]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return r("div",{style:{height:"100%",display:"flex",flexDirection:"column",...t?{flex:1,minHeight:0,width:"100%"}:{}},children:[!k&&r("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),r(jh,{source:b,iframeRef:n,onDocumentLoad:(_,I)=>{if(g&&_.contentWindow)return U_(e.id,g,_.contentWindow,I)},onLoad:m,title:`MCP App: ${x}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var e$=null;function aa(){e$=null}var j_={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 t$(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 Td({node:e}){let t=t$(e),n=e.data.detail||"",o=e.data.message||"",i=e.data.level||"ok",s=e.data.activeTool,a=e.data.subagent,l=j_[t]??"var(--c-muted)",c=t!=="idle";return r("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[r("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:l,boxShadow:c?`0 0 8px ${l}`:"none",animation:c?"pulse 1.5s infinite":"none",flexShrink:0}},void 0,!1,void 0,this),r("span",{style:{fontWeight:600,color:l,textTransform:"uppercase",letterSpacing:"0.05em"},children:t},void 0,!1,void 0,this),n&&r("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&&r("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-agent)"},children:[r("span",{style:{fontSize:"10px"},children:"⚙"},void 0,!1,void 0,this),r("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"&&r("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-subagent)"},children:[r("span",{style:{fontSize:"10px"},children:"⠉"},void 0,!1,void 0,this),r("span",{children:a.name},void 0,!1,void 0,this),r("span",{style:{color:"var(--c-muted)",fontSize:"10px"},children:["(",a.state,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o&&r("div",{style:{color:i==="warn"?"var(--c-warn)":i==="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 la(e){return typeof e==="string"&&e.trim().length>0?e.trim():null}function Z_(e){if(typeof e==="string"){let i=la(e);return i?{title:"Evidence warning",detail:i}:null}if(!e||typeof e!=="object")return null;let t=e,n=la(t.title)??"Evidence warning",o=la(t.detail);return o?{title:n,detail:o}:null}function n$(e){let t=[],n=Z_(e.data.warning);if(n)t.push(n);let o=e.data.warnings;if(Array.isArray(o))for(let s of o){let a=Z_(s);if(a)t.push(a)}let i=la(e.data.validationStatus)?.toLowerCase();if(i==="failed"||i==="invalid")t.push({title:"Image failed validation",detail:la(e.data.validationMessage)??"Review this image before using it as evidence."});return t}function o$(e){let t=[e.data.title,e.data.caption,e.data.alt,e.data.src,e.data.path].map((n)=>la(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 W_(e){let t=n$(e);if(t.length>0)return t;if(o$(e))return[{title:"Captured login page",detail:"This image looks like an auth screen. Treat it as environment context, not product evidence."}];return[]}function Id({node:e,expanded:t=!1}){let n=e.data.src||"",o=e.data.alt||e.data.title||"Image",i=e.data.caption||"",s=W_(e),a=Ws(n.startsWith("data:")||n.startsWith("http://")||n.startsWith("https://")?n:`/api/canvas/image/${e.id}`),[l,c]=E(!1),[u,d]=E(!1),[p,f]=E(1),[m,h]=E({x:0,y:0}),[g,v]=E({w:0,h:0}),b=D(null),x=D(!1),C=D({x:0,y:0}),y=oe((B)=>{let J=B.target;v({w:J.naturalWidth,h:J.naturalHeight}),c(!0),d(!1)},[]),k=oe(()=>{d(!0),c(!1)},[]);q(()=>{f(1),h({x:0,y:0})},[n]);let _=oe((B)=>{B.preventDefault(),B.stopPropagation();let J=B.deltaY>0?0.9:1.1;f((X)=>Math.max(0.25,Math.min(10,X*J)))},[]),I=oe((B)=>{if(p<=1)return;B.stopPropagation(),x.current=!0,C.current={x:B.clientX,y:B.clientY},B.target.setPointerCapture(B.pointerId)},[p]),w=oe((B)=>{if(!x.current)return;let J=B.clientX-C.current.x,X=B.clientY-C.current.y;C.current={x:B.clientX,y:B.clientY},h((V)=>({x:V.x+J,y:V.y+X}))},[]),P=oe(()=>{x.current=!1},[]),L=oe(()=>{f(1),h({x:0,y:0})},[]);if(!n)return r("div",{class:"image-node-empty",children:[r("div",{class:"image-node-empty-icon",children:"\uD83D\uDDBC"},void 0,!1,void 0,this),r("div",{class:"image-node-empty-text",children:"No image source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let N=g.w>0?`${g.w}×${g.h}`:"",Y=Math.round(p*100);return r("div",{class:`image-node ${t?"image-node-expanded":""}`,ref:b,children:[s.length>0&&r("div",{class:"image-node-warning-stack",children:s.map((B)=>r("div",{class:"image-node-warning",children:[r("span",{class:"image-node-warning-title",children:B.title},void 0,!1,void 0,this),r("span",{class:"image-node-warning-detail",children:B.detail},void 0,!1,void 0,this)]},`${B.title}-${B.detail}`,!0,void 0,this))},void 0,!1,void 0,this),r("div",{class:"image-node-viewport",onWheel:_,onPointerDown:I,onPointerMove:w,onPointerUp:P,style:{cursor:p>1?"grab":"default"},children:[!l&&!u&&r("div",{class:"image-node-loading",children:"Loading…"},void 0,!1,void 0,this),u&&r("div",{class:"image-node-error",children:[r("div",{class:"image-node-error-icon",children:"⚠"},void 0,!1,void 0,this),r("div",{children:"Failed to load image"},void 0,!1,void 0,this),r("div",{class:"image-node-error-path",children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("img",{src:a,alt:o,onLoad:y,onError:k,draggable:!1,style:{transform:`translate(${m.x}px, ${m.y}px) scale(${p})`,opacity:l?1:0,display:u?"none":"block"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(i||N||p!==1)&&r("div",{class:"image-node-footer",children:[i&&r("span",{class:"image-node-caption",children:i},void 0,!1,void 0,this),r("span",{class:"image-node-meta",children:[N&&r("span",{children:N},void 0,!1,void 0,this),p!==1&&r("button",{type:"button",class:"image-node-zoom-reset",onClick:L,"aria-label":"Reset zoom",children:[Y,"% ",r(Ru,{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 q_({node:e}){if((e.data.children??[]).filter((o)=>H.value.has(o)).length>0)return null;return r("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 r$(e){try{return new URL(e).host}catch{return e}}function i$(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ed({node:e,expanded:t=!1}){let n=typeof e.data.url==="string"?e.data.url:"",o=typeof e.data.pageTitle==="string"?e.data.pageTitle:"",i=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",l=typeof e.data.error==="string"?e.data.error:"",c=i$(typeof e.data.fetchedAt==="string"?e.data.fetchedAt:void 0),u=typeof e.data.statusCode==="number"?e.data.statusCode:null,d=typeof e.data.imageUrl==="string"?e.data.imageUrl:"",p=e.data.frameBlocked===!0,f=typeof e.data.frameBlockedReason==="string"?e.data.frameBlockedReason:"",[m,h]=E(!1),[g,v]=E(t);q(()=>{if(t)v(!0)},[t]);let b=oe(async()=>{if(!n||m)return;h(!0);try{await yu(e.id)}finally{h(!1)}},[e.id,m,n]);if(!n)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No webpage URL set"},void 0,!1,void 0,this);let x=a==="ready"?"var(--c-ok)":a==="error"?"var(--c-danger)":"var(--c-muted)";return r("div",{style:{display:"flex",flexDirection:"column",gap:"12px",height:"100%"},children:[r("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[r("div",{style:{minWidth:0,flex:1},children:[r("div",{style:{fontSize:"12px",color:"var(--c-muted)"},children:r$(n)},void 0,!1,void 0,this),r("div",{style:{fontSize:t?"18px":"15px",fontWeight:700,color:"var(--c-text)"},children:o||e.data.title||n},void 0,!1,void 0,this),r("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),r("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 8px",borderRadius:"999px",background:"rgba(255,255,255,0.04)",color:x,fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.04em",flexShrink:0},children:[r("span",{style:{width:"7px",height:"7px",borderRadius:"999px",background:x}},void 0,!1,void 0,this),a]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(i||d)&&r("div",{style:{display:"grid",gridTemplateColumns:d&&t?"160px 1fr":"1fr",gap:"12px",alignItems:"start"},children:[d&&t&&r("img",{src:d,alt:o||"Webpage preview image",style:{width:"160px",height:"96px",objectFit:"cover",borderRadius:"10px",border:"1px solid var(--c-line)",background:"var(--c-panel-soft)"}},void 0,!1,void 0,this),i&&r("p",{style:{margin:0,color:"var(--c-text-soft)",lineHeight:1.5,fontSize:t?"14px":"12px"},children:i},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:[r("button",{type:"button",onClick:b,disabled:m,style:{border:"1px solid var(--c-line)",background:"var(--c-panel-soft)",color:"var(--c-text)",borderRadius:"8px",padding:"6px 10px",cursor:m?"progress":"pointer",fontSize:"12px"},children:m||a==="fetching"?"Refreshing…":"Refresh"},void 0,!1,void 0,this),t&&!p&&r("button",{type:"button",onClick:()=>v((C)=>!C),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:g?"Hide live preview":"Show live preview"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>window.open(n,"_blank","noopener"),style:{border:"1px solid var(--c-line)",background:"transparent",color:"var(--c-accent)",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px"},children:"Open in browser"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&p&&r("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[r("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),r("div",{style:{padding:"20px",color:"var(--c-text-soft)",lineHeight:1.6,fontSize:"13px"},children:f||"The remote site blocks iframe embedding."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&g&&!p&&r("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[r("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),r("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),(c||u!==null)&&r("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",color:"var(--c-muted)",fontSize:"11px"},children:[c&&r("span",{children:["Fetched ",c]},void 0,!0,void 0,this),u!==null&&r("span",{children:["HTTP ",u]},void 0,!0,void 0,this),p&&r("span",{children:"Preview blocked by site"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),l&&r("div",{style:{color:"var(--c-danger)",fontSize:"12px",lineHeight:1.5},children:l},void 0,!1,void 0,this),r("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?r("div",{style:{whiteSpace:"pre-wrap",lineHeight:1.55,color:"var(--c-text)",fontSize:t?"14px":"12px"},children:s},void 0,!1,void 0,this):r("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 G_(e){return e.type==="html"&&e.data.presentation===!0}function s$(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 Hl({node:e,expanded:t=!1,presentation:n=!1,presentationExitToken:o,autoFocus:i=!1}){let s=D(null),a=Qt.value,l=s$(e.data.axCapabilities),c=Ke(()=>`theme-${crypto.randomUUID()}`,[]),u=Ke(()=>`ax-${crypto.randomUUID()}`,[l]),d=Ke(()=>`frame-${crypto.randomUUID()}`,[]),p=typeof e.data.html==="string"?e.data.html:typeof e.data.content==="string"?e.data.content:"",f=Ke(()=>Vs(p),[p]),m=Ke(()=>p?Il(e.id,{theme:a,themeToken:c,present:n,presentToken:o,v:f,axToken:u,frameToken:d}):"",[p,n,o,c,f,e.id,u,d]),h=Ys(m);Js(e,s,t?"":d),ia({enabled:!0,token:u,nodeId:e.id,sourceSurface:"html-node",iframeRef:s}),q(()=>{if(s.current?.contentWindow?.postMessage({source:Qn,type:"theme-update",token:c,theme:a},"*"),i)s.current?.focus()},[a,c]);let g=e.data.axCapabilities,v=g?.enabled===!0&&(!Array.isArray(g.allowed)||g.allowed.length>0),b=Oo.value;q(()=>{if(!v||b==null)return;s.current?.contentWindow?.postMessage({source:Qn,type:"ax-update",token:u,state:b},"*")},[v,b,u]),q(()=>{if(!i)return;let y=window.setTimeout(()=>s.current?.focus(),0);return()=>window.clearTimeout(y)},[i,m]);let x=(y,k)=>{if(k.aborted)return Promise.resolve(!1);return new Promise((_)=>{let I=(N)=>{clearTimeout(L),window.removeEventListener("message",P),k.removeEventListener("abort",w),_(N)},w=()=>I(!1),P=(N)=>{if(N.source!==y.contentWindow||N.data?.source!==Qn||N.data?.token!==c)return;if(N.data.type==="mounted")clearTimeout(L);if(N.data.type==="ready")I(!0)},L=setTimeout(w,1e4);window.addEventListener("message",P),k.addEventListener("abort",w,{once:!0}),y.contentWindow?.postMessage({source:Qn,type:"check-ready",token:c},"*")})},C=()=>{if(s.current?.contentWindow?.postMessage({source:Qn,type:"theme-update",token:c,theme:a},"*"),v&&Oo.value!=null)s.current?.contentWindow?.postMessage({source:Qn,type:"ax-update",token:u,state:Oo.value},"*");if(i)s.current?.focus()};if(!p)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No HTML content set"},void 0,!1,void 0,this);return r(jh,{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:i?0:void 0,onLoad:C,onDocumentLoad:x},void 0,!1,void 0,this)}var Zh=null;async function K_(){if(!Zh)Zh=await fk();return Zh}function V_(e,t){if(!e)return null;let n=e.toLowerCase(),o=t.find((s)=>s.name.toLowerCase()===n);if(o)return o.name;let i=t.filter((s)=>s.name.toLowerCase().startsWith(n));return i.length===1?i[0].name:null}function a$({html:e}){let t=D(null);return q(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=er(e),n.append(o.content.cloneNode(!0))},[e]),r("div",{ref:t},void 0,!1,void 0,this)}function l$(e,t){return`${e.role}:${e.status??"none"}:${t}:${e.text}`}function X_({count:e}){if(e===0)return null;return r("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 J_({message:e,onDismiss:t}){if(!e)return null;return r("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:[r("span",{style:{flex:1},children:e},void 0,!1,void 0,this),r("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:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Ad({node:e,expanded:t=!1}){let n=Array.isArray(e.data.turns)?e.data.turns:[],o=n.length===0,i=e.data.text||"",s=e.data.status||"draft",a=o?s:e.data.threadStatus||"draft",l=a==="draft",c=a==="pending"||a==="sending",u=a==="streaming",d=a==="answered",[p,f]=E(""),[m,h]=E(""),[g,v]=E(null),[b,x]=E(new Map),C=D(null),y=D(null),k=n[n.length-1],_=`${n.length}:${k?.role??""}:${k?.status??""}:${Math.floor((k?.text?.length??0)/200)}`;q(()=>{if(t&&l&&C.current)C.current.focus()},[t,l]),q(()=>{if(!_)return;if(y.current)y.current.scrollTo({top:y.current.scrollHeight,behavior:"smooth"})},[_]);let I=D(null),w=D(n);w.current=n,q(()=>{let J=n.some((V)=>V.role==="assistant"&&V.status==="streaming"),X=()=>{let V=!1,he=w.current.map((A,te)=>({turn:A,index:te})).filter(({turn:A})=>A.role==="assistant"&&A.text);if(he.length===0)return;return Promise.all(he.map(async({turn:A,index:te})=>{let M=await Vo(A.text);return{index:te,html:er(M??"")}})).then((A)=>{if(V)return;let te=new Map;for(let M of A)te.set(M.index,M.html);x(te)}),()=>{V=!0}};if(!J){if(I.current)clearTimeout(I.current),I.current=null;return X()}if(I.current)clearTimeout(I.current);return I.current=setTimeout(()=>{I.current=null,X()},400),()=>{if(I.current)clearTimeout(I.current),I.current=null}},[n]);let P=oe(async()=>{let J=p.trim();if(!J)return;let X=p;v(null),Xe(e.id,{turns:[{role:"user",text:J,status:"pending"}],threadStatus:"pending",text:J}),f("");let V=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds:void 0;if(!(await ol(J,e.position,e.id,V,e.id)).ok)Xe(e.id,{turns:[],threadStatus:"draft",text:"",status:"draft"}),f(X),v("Failed to send prompt. Your draft has been restored.")},[p,e.id,e.position,e.data.contextNodeIds]),L=oe(async()=>{let J=m.trim();if(!J)return;let X=m;v(null);let V=Array.isArray(e.data.turns)?[...e.data.turns]:[];if(V.push({role:"user",text:J,status:"pending"}),Xe(e.id,{turns:V,threadStatus:"pending"}),h(""),!(await mk(e.id,J)).ok)V.pop(),Xe(e.id,{turns:V,threadStatus:"answered"}),h(X),v("Failed to send reply. Your draft has been restored.")},[m,e.id,e.data.turns]),N=oe((J)=>{if(J.key==="Enter"&&(J.metaKey||J.ctrlKey)){J.preventDefault(),P();return}if(J.key==="Tab"&&p.startsWith("/")){J.preventDefault();let X=p.slice(1).split(/\s/)[0];if(X)K_().then((V)=>{let ee=V_(X,V);if(ee)f(`/${ee}`)})}},[P,p]),Y=oe((J)=>{if(J.key==="Enter"&&(J.metaKey||J.ctrlKey)){J.preventDefault(),L();return}if(J.key==="Tab"&&m.startsWith("/")){J.preventDefault();let X=m.slice(1).split(/\s/)[0];if(X)K_().then((V)=>{let ee=V_(X,V);if(ee)h(`/${ee}`)})}},[L,m]),B=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds.length:0;if(l&&n.length===0)return r("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%",gap:"8px"},children:[r(X_,{count:B},void 0,!1,void 0,this),r(J_,{message:g,onDismiss:()=>v(null)},void 0,!1,void 0,this),r("textarea",{ref:C,value:p,onInput:(J)=>f(J.target.value),onKeyDown:N,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),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter to send"]},void 0,!0,void 0,this),r("button",{type:"button",onClick:P,disabled:!p.trim(),style:{padding:"5px 14px",fontSize:"12px",fontWeight:600,background:p.trim()?"var(--c-accent)":"var(--c-line)",color:p.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:p.trim()?"pointer":"default"},children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(o)return r("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[r("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:i},void 0,!1,void 0,this),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px"},children:r("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:c?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:c?"Sending…":d?"Answered":s},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[r(X_,{count:B},void 0,!1,void 0,this),r(J_,{message:g,onDismiss:()=>v(null)},void 0,!1,void 0,this),r("div",{ref:y,style:{flex:1,overflow:"auto",minHeight:0},children:n.map((J,X)=>r("div",{children:[X>0&&r("div",{class:"thread-turn-divider"},void 0,!1,void 0,this),J.role==="user"?r("div",{class:"thread-turn-user",children:[r("div",{class:"thread-turn-role",children:[r("span",{class:"status-dot"},void 0,!1,void 0,this),"You"]},void 0,!0,void 0,this),r("div",{style:{fontSize:t?"15px":"13px",lineHeight:t?"1.7":"1.55",color:"var(--c-text)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:J.text},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("div",{class:"thread-turn-assistant",children:[r("div",{class:"thread-turn-role",children:[r("span",{class:`status-dot${J.status==="streaming"?" pulsing":""}`},void 0,!1,void 0,this),"PMX"]},void 0,!0,void 0,this),J.status==="streaming"&&!J.text&&r("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),r("div",{class:t?"md-reader-content":void 0,style:{fontSize:t?void 0:"13px",lineHeight:t?void 0:"1.55",opacity:J.text?1:0.4},children:b.get(X)?r(be,{children:[r(a$,{html:b.get(X)??""},void 0,!1,void 0,this),J.status==="streaming"&&r("span",{class:"streaming-cursor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("div",{style:{color:"var(--c-muted)",fontStyle:"italic"},children:J.status==="streaming"?"Waiting for response…":J.text||"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},l$(J,X),!0,void 0,this))},void 0,!1,void 0,this),r("div",{style:{flexShrink:0,borderTop:"1px solid var(--c-line)",marginTop:"4px",paddingTop:"6px"},children:[r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:d?"6px":0},children:[r("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:u?"var(--c-accent)":c?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:u?"Streaming…":c?"Sending…":d?"Answered":a},void 0,!1,void 0,this),r("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:[n.length," turn",n.length!==1?"s":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d&&r("div",{class:"thread-reply-area",children:[r("textarea",{value:m,onInput:(J)=>h(J.target.value),onKeyDown:Y,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),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"4px"},children:[r("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter"]},void 0,!0,void 0,this),r("button",{type:"button",onClick:L,disabled:!m.trim(),style:{padding:"3px 10px",fontSize:"11px",fontWeight:600,background:m.trim()?"var(--c-accent)":"var(--c-line)",color:m.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:m.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 c$({html:e}){let t=D(null);return q(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=er(e),n.append(o.content.cloneNode(!0))},[e]),r("div",{ref:t},void 0,!1,void 0,this)}function Rd({node:e,expanded:t=!1}){let n=e.data.content||"",o=e.data.status||"streaming",[i,s]=E(""),a=o==="streaming",l=o==="complete";q(()=>{if(!n){s("");return}let u=!1;return Vo(n).then((d)=>{if(!u)s(er(d??""))}),()=>{u=!0}},[n]);let c=oe(()=>{ol("",{x:e.position.x,y:e.position.y+e.size.height+24},e.id)},[e]);return r("div",{class:"response-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[a&&r("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),r("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:i?r("div",{class:t?"md-reader-content":void 0,children:r(c$,{html:i},void 0,!1,void 0,this)},void 0,!1,void 0,this):r("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),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px",flexShrink:0},children:[r("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:a?"var(--c-accent)":l?"var(--c-ok)":"var(--c-muted)"},children:a?"Streaming…":l?"Complete":o},void 0,!1,void 0,this),l&&r("button",{type:"button",onClick:c,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 Y_(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 Q_={mcp:"var(--c-muted)",file:"var(--c-muted)",subagent:"var(--c-subagent)",other:"var(--c-muted)"},u$={running:"⠋",success:"✓",failed:"✕"},d$={running:"var(--c-accent)",success:"var(--c-ok)",failed:"var(--c-danger)"};function Pd({node:e}){let{toolName:t,category:n,status:o,duration:i,resultSummary:s,error:a}=Y_(e.data),l=Q_[n]??Q_.other,c=u$[o]??"◌",u=d$[o]??"var(--c-muted)",d=o==="running",p=a?a.slice(0,30):s.length>30?`${s.slice(0,28)}…`:s;return r("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"0 12px",height:"100%",overflow:"hidden"},children:[r("span",{style:{fontSize:"14px",color:u,flexShrink:0,animation:d?"pulse 1.5s infinite":"none"},children:c},void 0,!1,void 0,this),r("div",{style:{flex:1,minWidth:0,overflow:"hidden"},children:[r("div",{style:{fontFamily:"var(--font-code)",fontSize:"11px",fontWeight:600,color:l,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t},void 0,!1,void 0,this),p&&r("div",{style:{fontSize:"10px",color:a?"var(--c-danger)":"var(--c-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1.3},children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i&&r("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:i},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var p$=new Set(["png","jpg","jpeg","gif","svg","webp","bmp","ico","avif"]),f$=new Set(["md","mdx","markdown"]);function m$(e){let t=e.split(".").pop()?.toLowerCase()??"";if(p$.has(t))return"image";if(f$.has(t))return"markdown";return"file"}async function ca(e,t,n){let o=se.value,i=400,s=300,a=20,l=Math.ceil(Math.sqrt(e.length));for(let c=0;c<e.length;c++){let u=e[c],d=c%l,p=Math.floor(c/l),f=t-l*420/2+d*420,m=n-150+p*320,h=m$(u.name),g=u.name;if(/\.(pdf|pptx?|xlsx?|docx?|od[pts])$/i.test(g)){if(!o||u.size===0||u.size>20971520){hn("remove","File not attached","Open a board and choose a nonempty file under 20 MiB.");continue}let v=new URLSearchParams({boardId:o,name:g,mime:u.type,x:String(f),y:String(m)});hn("context","Attaching document",g),await de("attachDocument",`/api/canvas/attachments?${v}`,null,{method:"POST",body:u});continue}if(se.value!==o)return;if(h==="image"){let v=new FileReader,b=await new Promise((x)=>{v.onload=()=>x(v.result),v.readAsDataURL(u)});if(se.value!==o)return;await No({type:"image",title:g,content:b,x:f,y:m,width:400,height:300,...o?{boardId:o}:{}})}else{let v=await u.text();if(se.value!==o)return;let b=h==="markdown"||h==="file";await No({type:h,title:g,content:v,x:f,y:m,width:b?720:400,height:b?500:300,...o?{boardId:o}:{}})}}}var eC={width:260,height:150},h$={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 qh(e){return!!e&&e in an}function Pr(e){if(!e)return null;let t=H.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 Wh(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Ul(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 tC(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 Gh({intent:e}){let t=qh(e.nodeType)?Bo(e.nodeType):null,n=e.label||e.kind,o=typeof e.confidence==="number"?`${Math.round(e.confidence*100)}%`:null;return r("div",{class:"intent-info",onMouseEnter:()=>Ts.value=e.id,onMouseLeave:()=>{if(Ts.value===e.id)Ts.value=null},children:[r("div",{class:"intent-chip",children:[typeof e.seq==="number"&&r("span",{class:"intent-seq",children:e.seq},void 0,!1,void 0,this),t&&r("span",{class:"intent-chip-icon","aria-hidden":"true",children:r(t,{size:12},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"intent-chip-label",children:n},void 0,!1,void 0,this),o&&r("span",{class:"intent-confidence",children:o},void 0,!1,void 0,this),e.phase==="forming"&&!e.auto&&r(_e,{label:"Veto this move",shortcut:"Esc",children:r("button",{type:"button",class:"intent-veto","aria-label":"Veto this move",onClick:(i)=>{i.stopPropagation(),Li(e)},children:r(Tt,{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),e.reason&&r("div",{class:"intent-reason",children:e.reason},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nC({intent:e,rect:t}){let n=qh(e.nodeType)?Bo(e.nodeType):null,o=qh(e.nodeType)?an[e.nodeType]:"Node";return r("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:Ul(e)},children:[r("div",{class:"intent-ghost-titlebar",children:[r("span",{class:"intent-ghost-icon","aria-hidden":"true",children:n?r(n,{size:13},void 0,!1,void 0,this):"◇"},void 0,!1,void 0,this),r("span",{class:"intent-ghost-badge",children:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(Gh,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oC({intent:e,rect:t,variant:n}){return r("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:Ul(e)},children:[n==="edit"&&r("div",{class:"intent-edit-bar"},void 0,!1,void 0,this),r(Gh,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function g$(e){let t=e.phase==="settling"?Pr(e.settledNodeId):null;switch(e.kind){case"create":{if(!e.position)return null;let n=e.nodeType&&h$[e.nodeType]||eC,o=t??{left:e.position.x,top:e.position.y,...n};return r(nC,{intent:e,rect:o},e.id,!1,void 0,this)}case"move":{if(!e.position)return null;let o=Pr(e.nodeId)??eC,i=t??{left:e.position.x,top:e.position.y,width:o.width,height:o.height};return r(nC,{intent:e,rect:i},e.id,!1,void 0,this)}case"remove":{let n=t??Pr(e.nodeId);if(!n)return null;return r(oC,{intent:e,rect:n,variant:"remove"},e.id,!1,void 0,this)}case"edit":{let n=t??Pr(e.nodeId);if(!n)return null;return r(oC,{intent:e,rect:n,variant:"edit"},e.id,!1,void 0,this)}case"connect":{if(!e.edge)return null;if("toBoardId"in e.edge&&e.edge.toBoardId&&e.edge.toBoardId!==se.value)return null;let n=Pr(e.edge.from),o=Pr(e.edge.to);if(!n||!o)return null;let i={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:i.x-110,top:i.y-18,width:220,height:36};return r("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:Ul(e)},children:r(Gh,{intent:e},void 0,!1,void 0,this)},e.id,!1,void 0,this)}default:return null}}function rC(){let e=Array.from(qt.value.values());if(q(()=>{function t(n){if(n.key!=="Escape")return;let o=Ts.value;if(!o)return;let i=qt.value.get(o);if(!i||i.phase!=="forming")return;n.stopImmediatePropagation(),n.preventDefault(),Li(i)}return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[]),e.length===0)return null;return r("div",{class:"intent-layer",onAnimationEnd:(t)=>{if(t.animationName!=="intent-settle"&&t.animationName!=="intent-dissolve")return;let n=t.target.dataset.intentId;if(n&&qt.value.get(n)?.phase!=="forming")zi(n)},children:[r("svg",{class:"intent-line-layer",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"},children:[r("defs",{children:r("marker",{id:"intent-arrow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"3",orient:"auto",children:r("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){if("toBoardId"in t.edge&&t.edge.toBoardId&&t.edge.toBoardId!==se.value)return null;let n=Pr(t.edge.from),o=Pr(t.edge.to);if(!n||!o)return null;return r("path",{d:tC(Wh(n),Wh(o)),class:`intent-edge type-${t.edge.type}`,style:{opacity:Ul(t)}},`line-${t.id}`,!1,void 0,this)}if(t.kind==="move"&&t.position){let n=Pr(t.nodeId);if(!n)return null;let o=n,i={x:t.position.x+o.width/2,y:t.position.y+o.height/2};return r("path",{d:tC(Wh(n),i),class:"intent-trail",markerEnd:"url(#intent-arrow)",style:{opacity:Ul(t)}},`line-${t.id}`,!1,void 0,this)}return null})]},void 0,!0,void 0,this),e.map(g$)]},void 0,!0,void 0,this)}var ua="Agent session";function iC(e){return e.some((t)=>t.attached)}function sC(e){return e.filter((t)=>!t.attached)}function pi(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 en=ie([]),fi=ie([]),ts=ie(!1),da=ie(!1),Kh=ie(null);function So(e){return en.value.find((n)=>n.sessionId===e)?.parentAgentId?"var(--c-subagent)":"var(--c-agent)"}function Nd(e){return(e.trim().replace(/^[^a-z0-9]+/i,"").charAt(0)||e.trim().charAt(0)||"?").toUpperCase()}function Md(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 _o=Ve(()=>iC(en.value)),tr=Ve(()=>xt.value&&_o.value),zd=Ve(()=>xt.value?sC(en.value):en.value),aC=Ve(()=>{let e=new Set;return[...en.value].filter((t)=>t.label!==ua).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))}),pa=Ve(()=>en.value.filter((e)=>e.attached)),mi=Ve(()=>en.value.find((e)=>e.attached)??null);function y$(e){let t=new Set;for(let n of e)if(n.nodeId&&n.kind!=="create")t.add(n.nodeId);return t}var $d=Ve(()=>y$(qt.value.values()));function Ld(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 Vh(e){if(!e)return;if(Array.isArray(e.presences))en.value=e.presences;if(Array.isArray(e.activity))fi.value=e.activity}function lC(){let e=D(new Map),t=Te.value.scale,n=H.value,o=1/Math.max(0.05,t),i=en.value.map((s)=>{let a=Ld(s,(c)=>n.get(c));if(a)e.current.set(s.sessionId,a);let l=a??e.current.get(s.sessionId)??null;return l?{presence:s,position:l}:null}).filter((s)=>s!==null);if(i.length===0)return null;return r("div",{class:"agent-presence-layer","aria-hidden":"true",children:i.map(({presence:s,position:a})=>r("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":So(s.sessionId)},children:r("div",{class:"agent-cursor-inner",style:{transform:`scale(${o})`},children:[r("svg",{class:"agent-cursor-glyph",width:"16",height:"18",viewBox:"0 0 16 18","aria-hidden":"true",children:r("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),r("span",{class:"agent-cursor-chip",children:[r("span",{class:"agent-cursor-dot"},void 0,!1,void 0,this),r("span",{class:"agent-cursor-label",children:pi(s)},void 0,!1,void 0,this),r("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 nr(e=1000){let[t,n]=E(()=>Date.now());return q(()=>{if(e<=0)return;n(Date.now());let o=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(o)},[e]),t}function cC(){let e=nr(Ja.value.length>0?5000:0),t=Ja.value.filter((o)=>o.cursor!==null&&(!o.lastSeenAt||e-Date.parse(o.lastSeenAt)<Bw+5000));if(t.length===0)return null;let n=1/Math.max(0.05,Te.value.scale);return r("div",{class:"human-presence-layer","aria-hidden":"true",children:t.map((o)=>r("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:r("div",{class:"human-cursor-inner",style:{transform:`scale(${n})`},children:[r("svg",{class:"human-cursor-glyph",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",children:r("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),r("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)}var uC=ie(new Map),hi=ie({}),Xh=ie({});function Jh(e){uC.value=new Map((e.nodes??[]).map((t)=>[t.nodeId,t])),Xh.value=e.links??{},hi.value=e.pins??{}}async function jl(){let e=await de("fetchContextStatus","/api/canvas/ax/context-status",{});if(e.ok&&e.boardId===se.value)Jh(e)}function Od(e,t){let n=uC.value.get(e),o=hi.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 dC(e){if(e.changedBy?.actor==="agent")return{agent:Nr(e.changedBy),notSeen:!1};let t=Xh.value;return{agent:null,notSeen:!!e.revision&&Object.keys(t).length>0&&e.revision>Math.max(t[e.from]??-1,e.toBoardId===void 0?t[e.to]??-1:-1)}}function Dd(e,t){let n=Xh.value[e];if(n===void 0||t<=n)return!1;let o=[...et.value.values()].filter((i)=>(i.from===e||i.toBoardId===void 0&&i.to===e)&&(i.revision??0)>n);if(o.some((i)=>i.changedBy?.actor!=="agent"))return!0;return!o.some((i)=>i.revision===t)}function Nr(e){return e.agentId?.trim()||e.source}var gi={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 pC(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function fC(e,t){if(!t)return null;let n=hi.value[e.id],o=n?.pinnedBy.actor==="agent"?` Pinned by ${Nr(n.pinnedBy)}${n.reason?`: ${n.reason}`:""}.`:"",i=Od(e.id,e.contentRevision??0);if(i.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(i.kind==="changed")return{tone:"warn",glyph:"warn",word:"changed",label:"The agent's copy is out of date",body:`Text changed after ${i.by} read it at ${pC(i.at)}${Dd(e.id,e.linksRevision??0)?" · links changed too":""}.${o}`};return{tone:"agent",glyph:"eye",word:"read",label:"Read by the agent",body:`${i.count>1?`Read ${i.count} times · last`:"Read"} ${pC(i.at)} by ${i.by}.${o}`}}function v$(e){if(e.lastEditedBy?.actor==="human")return null;if(e.createdBy?.actor==="agent")return`Written by ${Nr(e.createdBy)}`;if(e.lastEditedBy?.actor==="agent")return`Edited by ${Nr(e.lastEditedBy)}`;return null}function Yh(e,t){let n=fC(e,t);if(n)return{amber:n.tone==="warn",folded:n.label};let o=t?void 0:ro.value.get(e.id);if(o&&o.length>0)return{amber:!1,folded:o.length>1?`near ${o.length} pins`:"near a pin"};return null}function mC({node:e,pinned:t,fold:n="word"}){let o=fC(e,t),i=o?.tone==="warn"?"word":n;if(!o||i==="hidden")return null;return r(_e,{label:o.label,body:o.body,align:"end",fitWithin:".node-content",tapToOpen:!0,children:r("span",{class:`node-context-mark is-${o.tone}${i==="glyph"?" is-glyph":""}`,"data-mark":o.word,"aria-label":i==="glyph"?o.word:void 0,children:[r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:r("path",{d:gi[o.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),i==="word"&&o.word]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function hC({node:e,pinned:t,title:n,fold:o,children:i}){let s=v$(e),a=o==="hidden"?Yh(e,t):null,l=[s,a&&!a.amber?a.folded:"",an[e.type]].filter(Boolean).join(" · ");return r(_e,{label:n,body:l,align:"start",fitWithin:".node-content",tapToOpen:!0,children:r("span",{class:"node-type-icon","data-byline":s??void 0,children:i},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function gC(e){return hi.value[e]?.pinnedBy.actor==="agent"}function yC({node:e,pinned:t,fold:n="word"}){let o=t?void 0:ro.value.get(e.id),i=Bi.value?.nodeId===e.id?Bi.value:null,s=!o&&!t&&i?.kind==="out",a=o??(s?i.pins:void 0);if(!a||a.length===0||n==="hidden")return null;let l=a.length>1?`near ${a.length}`:"near",c=s?" is-fading":i?.kind==="in"?" is-pulse":Wo.value===e.id?" is-preview":"",u=(d)=>{if(!s)ik(e.id,d.currentTarget,Qh())};return r("button",{type:"button",class:`node-near-mark${n==="glyph"?" is-glyph":""}${c}`,"aria-label":n==="glyph"?l:void 0,"aria-expanded":Vr.value?.nodeId===e.id,"data-near":a.map((d)=>d.pinNodeId).join(" "),onPointerDown:(d)=>d.stopPropagation(),onPointerEnter:u,onPointerLeave:As,onFocus:u,onBlur:As,onClick:u,onKeyDown:(d)=>{if(d.key!=="Enter"&&d.key!=="ArrowDown")return;d.preventDefault(),u(d),requestAnimationFrame(()=>document.querySelector(".near-hint button")?.focus())},onAnimationEnd:()=>Wf(e.id),children:[r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[r("circle",{cx:"12",cy:"12",r:"8",class:"node-near-ring"},void 0,!1,void 0,this),r("circle",{cx:"12",cy:"12",r:"2.2",class:"node-near-dot"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n==="word"&&l]},void 0,!0,void 0,this)}function Qh(){let e=Te.value;return`${e.x},${e.y},${e.scale}`}var vC=600;function bC(e,t){let n={x:t.left+t.width/2,y:t.top+t.height/2},o=e.x-n.x,i=e.y-n.y,s=Math.min(o===0?Number.POSITIVE_INFINITY:t.width/2/Math.abs(o),i===0?Number.POSITIVE_INFINITY:t.height/2/Math.abs(i));return s>=1?n:{x:n.x+o*s,y:n.y+i*s}}function xC(){let e=nk.value;if(e.pinIds.length===0)return null;let t=Te.value,n=H.value,o=tk.value,i=(s,a)=>({x:s*t.scale+t.x,y:a*t.scale+t.y});return r("svg",{class:"near-pin-layer","aria-hidden":"true",children:e.pinIds.map((s)=>{let a=n.get(s);if(!a)return null;if(![...n.values()].some((f)=>f.id!==s&&hr(f,a)<=vC))return null;let l=i(a.position.x,a.position.y),c={left:l.x,top:l.y,width:a.size.width*t.scale,height:a.size.height*t.scale},u={x:c.left+c.width/2,y:c.top+c.height/2},d=vC*t.scale,p=e.ringOnly?[]:(o.get(s)??[]).map((f)=>n.get(f)).filter((f)=>f!==void 0).sort((f,m)=>hr(f,a)-hr(m,a));return r("g",{"data-pin-id":s,children:[r("rect",{class:"near-pin-radius",x:c.left-d,y:c.top-d,width:c.width+2*d,height:c.height+2*d,rx:d},void 0,!1,void 0,this),p.map((f,m)=>{let h=i(f.position.x,f.position.y),g={left:h.x,top:h.y,width:f.size.width*t.scale,height:f.size.height*t.scale},v=bC(u,g),b=bC({x:g.left+g.width/2,y:g.top+g.height/2},c);return r("g",{class:"near-pin-tether","data-near-node":f.id,children:[r("path",{d:`M ${b.x} ${b.y} L ${v.x} ${v.y}`},void 0,!1,void 0,this),r("circle",{class:"near-pin-number",cx:v.x,cy:v.y,r:10},void 0,!1,void 0,this),r("text",{class:"near-pin-number-label",x:v.x,y:v.y,children:m+1},void 0,!1,void 0,this)]},f.id,!0,void 0,this)})]},s,!0,void 0,this)})},void 0,!1,void 0,this)}function wC(){let e=Vr.value;if(!e||e.view!==Qh())return null;let t=H.value.get(e.nodeId),n=ro.value.get(e.nodeId);if(!t||!n)return null;let o=du.value===t.id,i=Math.max(8,Math.min(e.at.right-240,window.innerWidth-248)),s=e.at.bottom<window.innerHeight/2,a=s?window.innerHeight-e.at.bottom-16:e.at.top-16;return r("div",{class:"near-hint",role:"dialog","aria-label":n.length>1?`Near ${n.length} pins`:"Near a pin",style:{left:`${i}px`,maxHeight:`${Math.max(120,a)}px`,...s?{top:`${e.at.bottom+8}px`}:{bottom:`${window.innerHeight-e.at.top+8}px`}},onPointerEnter:qf,onPointerLeave:As,onFocusIn:qf,onFocusOut:As,onPointerDown:(l)=>l.stopPropagation(),onKeyDown:(l)=>{if(l.key!=="Escape")return;l.stopPropagation(),Vr.value=null,document.querySelector(`[data-node-id="${CSS.escape(t.id)}"] .node-near-mark`)?.focus()},children:[r("span",{class:"near-hint-label",children:n.length>1?`Near ${n.length} pins`:"Near a pin"},void 0,!1,void 0,this),n.map((l)=>{let c=H.value.get(l.pinNodeId);return r("span",{class:"near-hint-row",children:[r("span",{class:"near-hint-title",children:l.pinTitle},void 0,!1,void 0,this),c&&r("span",{class:"near-hint-distance",children:[Math.round(hr(t,c))," px"]},void 0,!0,void 0,this)]},l.pinNodeId,!0,void 0,this)}),r("span",{class:"near-hint-body",children:"Distance is measured between card edges. The agent gets its title and a short summary because a pin is nearby. Pin it to put it first."},void 0,!1,void 0,this),r("span",{class:"near-hint-actions",children:[r("button",{type:"button",class:"near-hint-pin",onClick:()=>{Vr.value=null,lo(t.id)},children:"Pin to put it first"},void 0,!1,void 0,this),r("button",{type:"button",class:"near-hint-show","aria-pressed":o,onClick:()=>{du.value=o?null:t.id},children:o?"Hide pins":"Show pins"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Bd(e,t){let{POSITIVE_INFINITY:n,POSITIVE_INFINITY:o,NEGATIVE_INFINITY:i,NEGATIVE_INFINITY:s}=Number,a=0;for(let l of e)a+=1,n=Math.min(n,l.position.x),o=Math.min(o,l.position.y),i=Math.max(i,l.position.x+l.size.width),s=Math.max(s,l.position.y+l.size.height);if(a===0)return null;return{x:n-t,y:o-t,width:i-n+t*2,height:s-o+t*2}}var eo=ie(!1);function tg(){let e=Oo.value;return e&&typeof e==="object"?e:{}}var SC=Ve(()=>tg().workItems??[]),ng=Ve(()=>tg().approvalGates??[]),Co=Ve(()=>ng.value.filter((e)=>e.status==="pending")),To=Ve(()=>{let e=tg().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 _C(e){return(await so("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 os=Ve(()=>ng.value.filter((e)=>e.status==="held")),og=Ve(()=>ng.value.filter((e)=>e.status==="approved"||e.status==="rejected")),CC=ie({events:[],evidence:[],steering:[]}),rs=ie("all");function b$(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 x$=new Set(["api","mcp","sdk","cli"]);function eg(e,t){if(e?.trim())return e.trim();let n=t?.trim();if(n&&!x$.has(n))return n;return null}var w$=/^(node|edge|group|annotation|jsonrender|graph|render)\.|^arrange$|^canvas\.clear$|^snapshot\.restore$/,TC=ie(null),Wl=ie(new Set),k$={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 S$(e,t=40,n=[],o=null,i="all"){let s=n.find((c)=>w$.test(c.op)),a=[...n.map((c)=>({id:`update-${c.id}`,kind:"update",label:"Update",body:c.summary,createdAt:c.at,who:c.sessionId??null,...!tt()&&o?.actor==="agent"&&s?.id===c.id?{undoable:!0}:{}})),...e.events.map((c)=>({id:`event-${c.id}`,kind:c.kind,label:k$[c.kind]??c.kind,body:c.detail?`${c.summary} — ${c.detail}`:c.summary,createdAt:c.createdAt,who:eg(c.agentId,c.source)})),...e.evidence.map((c)=>({id:`evidence-${c.id}`,kind:"evidence",label:"Evidence",body:c.body?`${c.title} — ${c.body}`:c.title,createdAt:c.createdAt,who:eg(c.agentId,c.source)})),...e.steering.map((c)=>{let u=c.agentId??(c.source&&c.source!=="browser"?c.source:null),d=c.target?`→ ${c.target} · `:u?"→ all · ":"",p=c.target&&c.delivered===!1?` — waiting for ${c.target} to pick it up`:"";return{id:`steer-${c.id}`,kind:"steer",label:"Steer",body:`${u?`${u} `:""}${d}${c.message}${p}`,createdAt:c.createdAt,who:eg(c.agentId,c.source)}})],l=i==="all"?a:a.filter((c)=>b$(c.kind)===i);return l.sort((c,u)=>c.createdAt<u.createdAt?1:c.createdAt>u.createdAt?-1:0),l.slice(0,t)}var IC=Ve(()=>S$(CC.value,40,fi.value,TC.value,rs.value));async function yi(){let[e,t]=await Promise.all([de("refreshTimeline","/api/canvas/ax/timeline?limit=40",null),de("refreshHistoryTop","/api/canvas/history",null)]);if(t)TC.value=t.top??null;if(!e)return;CC.value={events:Array.isArray(e.events)?e.events:[],evidence:Array.isArray(e.evidence)?e.evidence:[],steering:Array.isArray(e.steering)?e.steering:[]}}async function rg(e){if(!(await so("undoAgentEdit","/api/canvas/undo",{method:"POST"})).ok)return!1;return Wl.value=new Set([...Wl.value,e.id]),await oo("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"})}),yi(),!0}async function ig(e=!1){if(tt())return hn("remove","Undo / redo unavailable","Open the local PMX workbench to use shared history."),!1;let t=await so(e?"redo":"undo",e?"/api/canvas/redo":"/api/canvas/undo",{method:"POST"});if(t.ok)yi();return t.ok}async function EC(e,t){if(!(await so("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 oo("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 AC(e){return(await so("reopenGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/reopen`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser"})})).ok}async function fa(e,t){return(await so("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 vi(){if(!xt.value)return!1;return(await so("startSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser",label:ua,attached:!0,phase:"idle"})})).ok}async function ql(e){return(await so("endSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:e.source,agentId:e.agentId,attached:!1,endedBy:"human"})})).ok}var or=(e)=>JSON.stringify([e.boardId,e.id]);function Zl(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.boardId==="string"?{boardId:n.boardId}:{},...typeof n.reason==="string"?{reason:n.reason}:{},...typeof n.change==="string"?{change:n.change}:{},...typeof n.before==="string"?{before:n.before}:{},...typeof n.after==="string"?{after:n.after}:{}}]})}var Fn=ie(null),kC=(e)=>new Set(e.flat().map((t)=>typeof t==="string"?t:t.id)),sg=Ve(()=>{if(!xt.value)return null;let e=Fn.value;if(e?.kind==="live"){let n=en.value.find((o)=>o.attached&&o.sessionId===e.sessionId)?.session;return n?kC([n.read,n.pinned,n.created,n.edited]):null}let t=e?.kind==="receipt"?ns.value?.context:void 0;return t?kC([t.read,t.pinned,t.created,t.edited].map((n)=>n.filter((o)=>!o.boardId||o.boardId===se.value))):null}),RC=Ve(()=>new Set([...en.value.flatMap((e)=>e.attached?e.session?.edited??[]:[]),...ns.value?.context.edited.filter((e)=>!e.boardId||e.boardId===se.value).map((e)=>e.id)??[]]));function Gl(e,t){Fn.value=e?t?{kind:"live",...t}:{kind:"receipt"}:null}var ns=ie(null);function _$(e,t){let n=new Map(t.map((i)=>[or(i),i]));return[...e.map((i)=>{let s=n.get(or(i));if(!s)return i;return n.delete(or(i)),{...s,change:[i.change,s.change].filter(Boolean).join("; then "),before:i.before??s.before}}),...n.values()]}function Fd(e,t){let n=new Set(e.map(or));return[...e,...t.filter((o)=>!n.has(or(o)))]}function C$(e,t){return{labels:[...new Set([...e.labels,...t.labels])],sessions:e.sessions+1,startedAt:e.startedAt&&t.startedAt&&t.startedAt<e.startedAt?t.startedAt:e.startedAt,endedAt:t.endedAt,endedBy:e.endedBy===t.endedBy?t.endedBy:void 0,counts:t.counts,snapshot:null,context:{read:Fd(e.context.read,t.context.read),pinned:Fd(e.context.pinned,t.context.pinned),created:Fd(e.context.created,t.context.created),edited:_$(e.context.edited,t.context.edited),changedSinceRead:Fd(e.context.changedSinceRead,t.context.changedSinceRead)}}}function PC(e){let{counts:t,snapshot:n,context:o}=e;if(typeof e.label!=="string"||typeof e.endedAt!=="string")return;let i=Fn.value,s=i?.kind==="live"&&i.sessionId===e.writer;if(e.unchanged===!0||typeof e.parentAgentId==="string"){if(s)Fn.value=null;return}let a={labels:[e.label],sessions:1,startedAt:typeof e.startedAt==="string"?e.startedAt:null,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??""),boardId:typeof n.boardId==="string"?n.boardId:null}:null,context:{read:Zl(o?.read),pinned:Zl(o?.pinned),created:Zl(o?.created),edited:Zl(o?.edited),changedSinceRead:Zl(o?.changedSinceRead)}},l=ns.value;if(ns.value=l?C$(l,a):a,s)Fn.value={kind:"receipt"}}async function NC(e,t){let n=!0,o=[];for(let i of t){if(i.boardId&&i.boardId!==se.value)continue;let s=i.id,a=H.value.get(s);if(!a||a.lastEditedBy?.actor==="human")continue;let l=await de("undoSessionEdit",`/api/canvas/snapshots/${encodeURIComponent(e)}/restore-node`,{ok:!1,restored:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeId:s,preserveHumanEdits:!0})});if(n=n&&l.ok,l.ok&&l.restored)o.push(s)}return{ok:n,restored:o}}function Hd(){if(ns.value=null,Fn.value?.kind==="receipt")Fn.value=null}function MC(){if(!_o.value)return null;let e=To.value;if(!e)return null;let t=H.value,n=e.nodeIds.map((s)=>t.get(s)).filter((s)=>s!==void 0),o=Bd(n,e.padding);if(!o)return null;let i=1/Math.max(0.05,Te.value.scale);return r("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:[r("span",{class:"scope-fence-pill scope-fence-pill-top",style:{transform:`scale(${i})`},children:["Agent scope · ",n.length," node",n.length===1?"":"s"]},void 0,!0,void 0,this),r("span",{class:"scope-fence-pill scope-fence-pill-bottom",style:{transform:`scale(${i})`},children:"writes outside are blocked · reads allowed"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var T$=U().trim().min(1).max(80),CG=U().trim().max(4000),I$=Pi({kind:T$,ink:mn(["supports","contradicts","cites","derived","informs","related"]),directed:ht()}),E$=We(I$).max(64).refine((e)=>new Set(e.map((t)=>t.kind)).size===e.length,"Relation kinds must be unique."),TG=Pi({id:U().trim().min(1),name:U().trim().min(1).max(80),vocabulary:E$}),Kl=[{kind:"supports",ink:"supports",directed:!0},{kind:"contradicts",ink:"contradicts",directed:!0},{kind:"cites",ink:"cites",directed:!0},{kind:"derived-from",ink:"derived",directed:!0},{kind:"answers",ink:"informs",directed:!0},{kind:"depends-on",ink:"informs",directed:!0},{kind:"supersedes",ink:"informs",directed:!0},{kind:"flow",ink:"derived",directed:!0},{kind:"related",ink:"related",directed:!1}],A$={Research:Kl.filter((e)=>["supports","contradicts","cites","derived-from","related"].includes(e.kind)),Dependencies:Kl.filter((e)=>["depends-on","related"].includes(e.kind)),Decision:[{kind:"option",ink:"derived",directed:!0},{kind:"if",ink:"cites",directed:!0},{kind:"rejected",ink:"related",directed:!0},{kind:"supersedes",ink:"informs",directed:!0}],Flow:[{kind:"next",ink:"derived",directed:!0},{kind:"if-fails",ink:"contradicts",directed:!0},{kind:"loop",ink:"related",directed:!0}]};function zC(e=[]){return Object.entries(A$).find(([,t])=>t.length===e.length&&t.every((n)=>e.some((o)=>o.kind===n.kind&&o.ink===n.ink&&o.directed===n.directed)))?.[0]??null}function Gn(e){return e.kind??(e.type==="relation"?"related":e.type==="references"?"cites":e.type??"related")}function Ud(e){let t=Gn(e);if(t==="depends-on")return"to";if(["derived-from","contradicts","supersedes"].includes(t))return"from";return null}function mo(e,t=[]){let n=Gn(e);return t.find((o)=>o.kind===n)??Kl.find((o)=>o.kind===n)??{kind:n,ink:"related",directed:!0}}function ma(e){return`${e.kind??e.type??"related"}${e.label?` "${e.label}"`:""}${e.reason?` (why: ${e.reason})`:""}`}var Io=ie(null);sn(()=>{let e=Io.value;if(e?.boardId===se.value&&![...et.value.values()].some((t)=>Gn(t)===e.kind))Io.value=null});var ag=Ve(()=>gt.value),Vl=Ve(()=>{let e=zC(Yn()?.relationVocabulary),t=ag.value,n=Io.value?.boardId===se.value?Io.value.kind:null,o=[...et.value.values()].filter((c)=>!c.toBoardId||c.toBoardId===se.value),i=new Set(st.value);if(t)i.add(t);if(i.size===0&&!n)return null;for(let c of i){let u=H.value.get(c);if(u?.type==="group"&&Array.isArray(u.data.children)){for(let d of u.data.children)if(typeof d==="string")i.add(d)}}let s=new Set(i),a=new Set,l=(c)=>{a.add(c.id),s.add(c.from),s.add(c.to)};if(!n){for(let c of o)if(i.has(c.from)&&i.has(c.to))l(c)}if(n){for(let c of o)if(Gn(c)===n)l(c)}else if(e==="Dependencies"||e==="Decision"){let c=!0;while(c){c=!1;for(let u of o){if(a.has(u.id))continue;let d=Ud(u);if(e==="Dependencies"?d&&s.has(d==="from"?u.from:u.to):["option","if","chosen"].includes(Gn(u))&&s.has(u.to))l(u),c=!0}}}else if(e==="Flow"){let c=new Set;for(let u of H.value.values())if(["done","in-progress","blocked"].includes(String(u.data.axWorkStatus)))c.add(u.id),s.add(u.id);for(let u of o)if(["flow","next","if-fails","loop"].includes(Gn(u))&&c.has(u.from))l(u)}else for(let c of o)if((i.has(c.from)||i.has(c.to))&&(e!=="Research"||["supports","contradicts","cites","derived-from"].includes(Gn(c))))l(c);return{cards:s,links:a}});function $C(){let e=se.value,t=Ge.value,n=H.value,o=et.value,i=Oe.value;return q(()=>{let s=setTimeout(()=>void Kt(),100);return()=>clearTimeout(s)},[e,t,n,o,i]),q(()=>{let s=setInterval(()=>void Kt(),60000);return()=>clearInterval(s)},[]),null}function LC(){if(!Oe.value)return null;let e=[...H.value.keys()].map(Jn);return r(be,{children:[r("div",{class:"lifecycle-filters",role:"group","aria-label":"Lifecycle filter",children:[["All","To review","Retired"].map((t)=>r("button",{type:"button","aria-pressed":Ro.value===t,onClick:()=>{if(!Oe.value)return;Ro.value=t},children:[t,t==="All"?"":` · ${e.filter((n)=>t==="Retired"?n?.retired:!n?.retired&&(n?.due||n?.sources.length)).length}`]},t,!0,void 0,this)),Oi.value&&r("span",{role:"status",children:"Qualification unavailable"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(R$,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function R$(){let e=Is.value,[t,n]=E(!1);if(!Oe.value||!e||e.boardId!==se.value||e.incarnation!==wt||Ct.value||!Jn(e.nodeId)?.retired)return null;return r("div",{class:"retirement-toast",role:"status",children:[r("span",{children:"Retired from active context. History kept."},void 0,!1,void 0,this),r("button",{type:"button",disabled:t,onClick:async()=>{if(t||!Oe.value)return;if(n(!0),(await de("restore",`/api/canvas/node/${encodeURIComponent(e.nodeId)}/lifecycle/restore`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedBoardId:e.boardId,evidence:"Human undid retirement."})}))?.ok)Is.value=null,await Kt();n(!1)},children:"Undo retirement"},void 0,!1,void 0,this),r("button",{type:"button","aria-label":"Dismiss retirement notice",onClick:()=>{Is.value=null},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function jd({nodeId:e}){if(!Oe.value)return null;let t=Jn(e);if(!t||t.retired||!t.due&&t.sources.length===0)return null;let n=t.sources[0];return r("button",{type:"button",class:"node-lifecycle-warning",onClick:(o)=>{o.stopPropagation(),Es(e)},children:[r("span",{children:t.due?"⧗ review due":"⧗ source needs review"},void 0,!1,void 0,this),r("span",{children:t.due?t.reasons[0]:`${n.title} · ${n.reasons[0]}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Zd({node:e}){let t=[...et.value.values()].filter((i)=>i.toBoardId&&i.from===e.id),n=se.value,o=Ge.value.find((i)=>i.id===n);if(!t.length)return null;return r("div",{class:"node-memory-links",role:"region","aria-label":"Cross-board references",tabIndex:0,onWheel:(i)=>{if(!i.ctrlKey&&!i.metaKey)i.stopPropagation()},onKeyDown:(i)=>{if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"," "].includes(i.key))i.stopPropagation()},children:t.map((i)=>{let s=Ge.value.find((l)=>l.id===i.toBoardId),a=o?.links?.find((l)=>l.kind==="card"&&l.nodeId===e.id&&l.boardId===i.toBoardId&&l.cardId===i.to);return r("div",{class:"node-memory-link",children:r("button",{type:"button",disabled:!s||a?.missing===!0,onClick:async(l)=>{l.stopPropagation();let c=document.activeElement;if(c instanceof HTMLElement&&c.isContentEditable)c.blur();if(e.type==="markdown"&&!await oh(n,e.id))return;await zt({boardId:i.toBoardId,cardId:i.to})},children:["↗ ",i.label||i.type,": ",s?.name??"Missing board"," /"," ",a?.cardTitle??(a?.missing?"Missing card":"Loading card…")]},void 0,!0,void 0,this)},i.id,!1,void 0,this)})},void 0,!1,void 0,this)}function ho({board:e,inNodeHeader:t=!1}){let n=!!e.pin;return r("button",{type:"button",class:`ctx-pin-btn${t?"":" board-pin-btn"}${n?" ctx-pin-active":""}`,onClick:(i)=>{i.stopPropagation(),$s(e.id,!n)},"aria-label":n?"Unpin board from the agent's context":"Pin board to the agent's context","aria-pressed":n,"data-testid":"board-pin",children:r("span",{class:"ctx-pin-mark",children:[r(uo,{},void 0,!1,void 0,this),n&&e.pin?.pinnedBy.actor==="agent"&&r("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)}function P$(e){let t=typeof e==="number"&&Number.isFinite(e)?Math.floor(e):1;return Math.max(1,Math.min(20,t))}function Wd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xl(e){return typeof e==="string"&&e.length>0}function OC(e){let t=e.axStep;if(!Wd(t))return null;if(!Xl(t.flowId)||!Xl(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 DC(e){let t=e.axFlow;if(!Wd(t)||!Xl(t.flowId)||!Array.isArray(t.steps))return null;let n=[];for(let i of t.steps){if(!Wd(i)||!Xl(i.nodeId)||!Xl(i.workItemId))return null;if(typeof i.index!=="number")return null;n.push({index:i.index,nodeId:i.nodeId,workItemId:i.workItemId,title:typeof i.title==="string"?i.title:""})}if(n.length===0)return null;let o=Wd(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:P$(o.maxRuns)}}}var N$={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)"},FC={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},HC={fontSize:"10px",color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginRight:"auto"},UC={...Gi,background:"color-mix(in srgb, var(--c-accent) 25%, transparent)",color:"var(--c-text)"},M$=[{status:"in-progress",label:"Start",toast:"Step started"},{status:"done",label:"Done",toast:"Step done"},{status:"blocked",label:"Blocked",toast:"Step blocked"}];async function BC(e,t,n){let o={...t,loop:n};Xe(e.id,{axFlow:o}),await ln(e.id,{data:{axFlow:o}})}function jC(e){return typeof e?.axWorkStatus==="string"?e.axWorkStatus:"todo"}function z$({node:e,flow:t}){let[n,o]=E(""),{running:i,run:s,maxRuns:a}=t.loop,l=async()=>{await BC(e,t,{running:!0,run:s>=a?0:s,maxRuns:a});let u=t.steps.find((p)=>jC(H.value.get(p.nodeId)?.data)!=="done"),d=u??t.steps[t.steps.length-1];await ii(e,"ax.work.update",{id:d.workItemId,status:u?"in-progress":"done"},"Loop running")},c=async()=>{let u=n.trim();if(!u)return;await ii(e,"ax.steer",{message:u},"Steering sent"),o("")};return r("div",{class:"ax-flow-controls",style:{...FC,marginTop:"6px",rowGap:"4px"},children:[r("span",{class:"ax-flow-runs",style:HC,children:i?`Loop running · run ${s+1}/${a}`:`Loop idle · ${s}/${a} runs`},void 0,!1,void 0,this),i?r(_e,{label:"Stop the loop now",body:"The stop is persisted on this node, so it survives a refresh and no further step is opened.",side:"up",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action",style:UC,onClick:(u)=>{u.stopPropagation(),BC(e,t,{...t.loop,running:!1})},children:"Stop"},void 0,!1,void 0,this)},void 0,!1,void 0,this):r(_e,{label:"Run this flow as a loop",body:"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.",side:"up",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action",style:Gi,onClick:(u)=>{u.stopPropagation(),l()},children:"Run loop"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("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(),c()},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),r(_e,{label:"Send a steering message to the agent working this flow",side:"up",align:"end",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action",style:Gi,onClick:(u)=>{u.stopPropagation(),c()},children:"Steer"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function qd({node:e}){let t=OC(e.data);if(!t)return null;let n=DC(e.data),o=jC(e.data);return r("div",{class:"ax-step-dock",style:N$,children:[r("div",{class:"ax-step-controls",style:FC,children:[r("span",{class:"ax-step-position",style:HC,children:["Step ",t.index,"/",t.total]},void 0,!0,void 0,this),M$.map((i)=>r(_e,{label:`Set this step's work item to "${i.status}"`,side:"up",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action","aria-pressed":o===i.status,style:o===i.status?UC:Gi,onClick:(s)=>{s.stopPropagation(),ii(e,"ax.work.update",{id:t.workItemId,status:i.status},i.toast)},children:i.label},void 0,!1,void 0,this)},i.status,!1,void 0,this))]},void 0,!0,void 0,this),n&&r(z$,{node:e,flow:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ha=8,is=ie(null),ga=[],ya=[],qC=null;function ZC(e){let t=e?.data.parentGroup;return typeof t==="string"&&t.length>0?t:null}function WC(e){if(!e||!Array.isArray(e.data.children))return[];return e.data.children.filter((t)=>typeof t==="string")}function $$(e,t){let n=new Map(t.map((l)=>[l.id,l])),o=new Set([e]),i=n.get(e);if(!i)return o;let s=ZC(i);while(s&&!o.has(s))o.add(s),s=ZC(n.get(s));if(i.type!=="group")return o;let a=[...WC(i)];while(a.length>0){let l=a.pop();if(!l||o.has(l))continue;o.add(l);let c=n.get(l);if(c?.type==="group")a.push(...WC(c))}return o}function GC(e,t){ga=[],ya=[],qC=e;let n=Array.from(t),o=$$(e,n);for(let i of n){if(o.has(i.id))continue;let s=i.position.x,a=i.position.x+i.size.width,l=i.position.x+i.size.width/2,c=i.position.y,u=i.position.y+i.size.height,d=i.position.y+i.size.height/2;ga.push({val:s,minY:c,maxY:u}),ga.push({val:a,minY:c,maxY:u}),ga.push({val:l,minY:c,maxY:u}),ya.push({val:c,minX:s,maxX:a}),ya.push({val:u,minX:s,maxX:a}),ya.push({val:d,minX:s,maxX:a})}}function KC(){ga=[],ya=[],qC=null}function VC(e,t,n,o){let i=[e,e+n/2,e+n],s=[t,t+o/2,t+o],a=[0,n/2,n],l=[0,o/2,o],c=null,u=ha+1,d=null;for(let g=0;g<3;g++){let v=i[g];for(let b of ga){let x=Math.abs(v-b.val);if(x<u)u=x,c=b.val-a[g],d={axis:"x",pos:b.val,from:Math.min(b.minY,t),to:Math.max(b.maxY,t+o)}}}let p=null,f=ha+1,m=null;for(let g=0;g<3;g++){let v=s[g];for(let b of ya){let x=Math.abs(v-b.val);if(x<f)f=x,p=b.val-l[g],m={axis:"y",pos:b.val,from:Math.min(b.minX,e),to:Math.max(b.maxX,e+n)}}}let h=[];if(d&&u<=ha)h.push(d);if(m&&f<=ha)h.push(m);return{x:c!==null&&u<=ha?c:e,y:p!==null&&f<=ha?p:t,guides:h}}function XC({nodeId:e,viewport:t,onMove:n,onDragEnd:o,onClick:i}){let s=D(!1),a=D({x:0,y:0}),l=D({x:0,y:0});return oe((u,d,p)=>{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},l.current={x:d,y:p};let f=null,m=null,h=!1,g=()=>{if(m=null,!s.current||!f)return;let x=f;f=null;let C=t.value.scale,y=(x.x-a.current.x)/C,k=(x.y-a.current.y)/C;n(e,l.current.x+y,l.current.y+k)},v=(x)=>{if(!s.current)return;if(!h&&Math.hypot(x.clientX-u.clientX,x.clientY-u.clientY)<4)return;if(!h)document.documentElement.classList.add("is-node-moving");if(h=!0,f={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(g)},b=(x)=>{if(m!==null)window.cancelAnimationFrame(m),g();if(s.current=!1,document.documentElement.classList.remove("is-node-dragging","is-node-moving"),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",b),o(),!h&&x.type==="pointerup")i?.()};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",b)},[e,t,n,o,i])}var L$=200,O$=100;function JC({nodeId:e,viewport:t,onResize:n,onResizeEnd:o}){let i=D(!1),s=D({x:0,y:0}),a=D({w:0,h:0});return oe((c,u,d)=>{c.stopPropagation(),c.preventDefault(),i.current=!0,s.current={x:c.clientX,y:c.clientY},a.current={w:u,h:d},document.documentElement.classList.add("is-node-resizing");let p=null,f=null,m=()=>{if(f=null,!i.current||!p)return;let v=p;p=null;let b=t.value.scale,x=(v.x-s.current.x)/b,C=(v.y-s.current.y)/b;n(e,Math.max(L$,a.current.w+x),Math.max(O$,a.current.h+C))},h=(v)=>{if(!i.current)return;if(p={x:v.clientX,y:v.clientY},f!==null)return;f=window.requestAnimationFrame(m)},g=()=>{if(f!==null)window.cancelAnimationFrame(f),m();i.current=!1,document.documentElement.classList.remove("is-node-resizing"),document.removeEventListener("pointermove",h),document.removeEventListener("pointerup",g),document.removeEventListener("pointercancel",g),o()};document.addEventListener("pointermove",h),document.addEventListener("pointerup",g),document.addEventListener("pointercancel",g)},[e,t,n,o])}var D$={ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1}};function B$(e,t,n){let o=e.position.x+e.size.width/2,i=e.position.y+e.size.height/2,s=null,a=Number.POSITIVE_INFINITY;for(let l of n){if(l.id===e.id)continue;let c=l.position.x+l.size.width/2-o,u=l.position.y+l.size.height/2-i,d=c*t.dx+u*t.dy;if(d<=0)continue;let p=Math.abs(c*t.dy)+Math.abs(u*t.dx);if(p>d)continue;let f=d+p*2;if(f<a)a=f,s=l}return s}var F$=0.4,H$=0.55,U$=175;function j$(e,t,n=0){if(!Number.isFinite(e)||e>=1)return 1;let i=Math.min(2.2,1/Math.max(e,0.01));if(Number.isFinite(t)&&t>0)i=Math.min(i,t*F$/Xs);if(Number.isFinite(n)&&n>0)i=Math.min(i,n*H$/U$);return Math.max(1,i)}var Z$=140;function W$(e,t,n,o,i){let[s,a]=E("word"),l=`${n}\x00${t?t.amber?"amber":t.folded:""}\x00${o}\x00${i.toFixed(3)}`,c=D(l);return Me(()=>{if(c.current!==l){if(c.current=l,s!=="word"){a("word");return}}let u=e.current;if(!u||!t||t.amber||s==="hidden")return;let d=Math.min(u.scrollWidth,Z$*i);if(u.clientWidth+0.5<d)a(s==="word"?"glyph":"hidden")},[l,s]),t?s:"word"}function YC({node:e,children:t,onContextMenu:n}){let o=gt.value===e.id,i=st.value.has(e.id),s=kt.value.has(e.id),a=D(null),l=D(null),c=e.type==="board"&&typeof e.data.boardId==="string"?Ge.value.find((W)=>W.id===e.data.boardId)??null:null,u=tu.value.has(e.id),d=!o&&Bk.value.has(e.id),p=wr.value,f=p!==null&&p.has(e.id),m=p!==null&&!p.has(e.id),[h,g]=E(!1),v=D(null),b=oe((W,ye,He)=>{let R=VC(ye,He,e.size.width,e.size.height),ne=H.value.get(W);if(ne?.position.x===R.x&&ne.position.y===R.y){is.value=R.guides.length>0?R.guides:null;return}un(W,{position:{x:R.x,y:R.y}}),is.value=R.guides.length>0?R.guides:null,Zk(W)},[e.size.width,e.size.height]),x=D(null),C=oe(()=>{if(KC(),is.value=null,Uf(null),rk(e.id),x.current)document.removeEventListener("keydown",x.current),x.current=null;dn();let W=Xo.value;if(jk(),!W||W.nodeId!==e.id)return;if(W.mode==="add")em(W.groupId,[e.id]);else{let ye=H.value.get(W.groupId),He=Array.isArray(ye?.data.children)?ye.data.children.filter((R)=>typeof R==="string"&&R!==e.id):[];bu(W.groupId,He)}},[e.id]),y=XC({nodeId:e.id,viewport:Te,onMove:b,onDragEnd:C,onClick:()=>{st.value=new Set([e.id])}}),k=oe((W,ye,He)=>{let R=H.value.get(W);if(R?.size.width===ye&&R.size.height===He)return;un(W,{size:{width:ye,height:He}})},[]),_=oe(()=>{Xe(e.id,{userResized:!0}),ln(e.id,{data:{userResized:!0}}),dn()},[e.id]),I=JC({nodeId:e.id,viewport:Te,onResize:k,onResizeEnd:_}),w=oe((W)=>{W.stopPropagation(),W.preventDefault(),At.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]),P=oe((W)=>{if(W.button!==0)return;if(h)return;if(W.target instanceof Element&&W.target.closest("button, input")){W.stopPropagation();return}if(Wn.value==="connect"){w(W);return}if(W.shiftKey){W.stopPropagation(),im(e.id);return}if(Sr(e.id),Uf(e.id),ok(e.id),Xw(e.id,typeof e.data.title==="string"&&e.data.title?e.data.title:e.type),GC(e.id,H.value.values()),e.type!=="group"){let ye=(He)=>{if(He.key==="Escape")Uk()};x.current=ye,document.addEventListener("keydown",ye)}y(W,e.position.x,e.position.y)},[e.id,e.type,e.data.title,e.position.x,e.position.y,y,h,w]),L=oe((W)=>{if(W.button!==0)return;if(W.stopPropagation(),Wn.value==="connect"){w(W);return}if(W.shiftKey){im(e.id);return}Sr(e.id)},[e.id,w]),N=oe((W)=>{if((W.target instanceof Element?W.target:null)?.closest('button, input, textarea, select, a, [contenteditable="true"]'))return;if(n)n(W,e.id)},[n,e.id]),Y=oe((W)=>{let ye=W.target;if(ye&&ye!==W.currentTarget&&ye.closest('input, textarea, [contenteditable="true"]'))return;let He=D$[W.key];if(He){W.preventDefault();let R=B$(e,He,H.value.values());if(!R)return;Sr(R.id),requestAnimationFrame(()=>{document.querySelector(`.canvas-node[data-node-id="${CSS.escape(R.id)}"]`)?.focus()})}else if(W.key==="Enter"&&W.target===W.currentTarget&&qa.has(e.type))W.preventDefault(),xo(e.id)},[e]),B=e.data.title||(e.type==="file"?(e.data.path||e.data.content||"").split(/[\\/]/).pop()??"":"")||an[e.type],J=oe((W)=>{let ye=W.trim();if(ye&&ye!==B)Xe(e.id,{title:ye}),ln(e.id,{title:ye});g(!1)},[e.id,B]),X=D(null),V=D(!1),ee=D(null);q(()=>{if(V.current||!ah(e))return;let W=X.current;if(!W)return;let ye=new ResizeObserver(()=>{if(V.current){ye.disconnect();return}let He=W.scrollHeight,R=r_(e,He);if(R===null)return;if(Math.abs(R-e.size.height)>8){if(Cu(e.id,{width:e.size.width,height:R}),ee.current!==null)window.clearTimeout(ee.current);ee.current=window.setTimeout(()=>{dn({recordHistory:!1}),ee.current=null},0)}V.current=!0,ye.disconnect()});return ye.observe(W),()=>{if(ye.disconnect(),ee.current!==null)window.clearTimeout(ee.current),ee.current=null}},[e.id,e.type,e.data.mode,e.data.strictSize,e.collapsed,e.size.width,e.size.height]);let he=e.pinned,A=e.type==="trace",te=A&&e.data.status==="running",M=e.type==="group",O=e.data.strictSize===!0,Pe=Math.max(Te.value.scale,0.01),Fe=j$(Pe,e.collapsed?0:e.size.height,e.size.width),De=W$(a,Yh(e,s),B,e.size.width,Fe),Ae=M&&e.data.color?e.data.color:void 0,ve={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":Fe.toFixed(3),"--node-port-scale":(1/Pe).toFixed(3),...Ae?{"--group-color":Ae}:{}},z=tr.value&&$d.value.has(e.id),re=["canvas-node",o?"active":"",d?"neighbor":"",f?"search-match":"",m?"search-dimmed":"",i?"selected":"",s?"context-pinned":"",u?"attention-pulse":"",he?"pinned":"",A?"trace-node":"",te?"trace-running":"",M?"group-node":"",O?"strict-size":"",z?"agent-mutating":"",tr.value&&RC.value.has(e.id)?"session-edited":"",sg.value&&!sg.value.has(e.id)?"lens-dimmed":"",Vl.value&&!Vl.value.cards.has(e.id)?"relation-dimmed":"",Oe.value&&Jn(e.id)?.retired?"lifecycle-retired":"",jf.value==="To review"&&!Jn(e.id)?.due&&!Jn(e.id)?.sources.length?"lifecycle-filter-dimmed":"",jf.value==="Retired"&&!Jn(e.id)?.retired?"lifecycle-filter-dimmed":""].filter(Boolean).join(" "),Ne=M?(Array.isArray(e.data.children)?e.data.children:[]).filter((W)=>typeof W==="string"&&H.value.has(W)):[],[ke,ae]=E(!1),Se=Xo.value,pe=M&&Se?.groupId===e.id&&Se.mode==="add",Ue=M&&Se?.groupId===e.id&&Se.mode==="remove",xe=At.value?.targetId===e.id,qe=M?[...new Set(Ne.map((W)=>H.value.get(W)?.type).filter((W)=>!!W))].slice(0,4):[];if(M&&e.collapsed)return r("div",{class:`${re} group-chip`,"data-node-type":e.type,style:{...ve,width:"auto",height:"auto"},onPointerDown:L,onDblClick:N,"data-testid":"group-chip",children:[r("div",{class:"node-titlebar group-chip-inner",onPointerDown:P,children:[r("button",{type:"button",class:"group-chip-expand","aria-label":`Expand group ${B}`,onClick:(W)=>{W.stopPropagation(),Hi(e.id)},children:r(oi,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"group-chip-text",children:[r("div",{class:"group-chip-name",children:B},void 0,!1,void 0,this),r("div",{class:"group-chip-meta",children:[qe.map((W)=>r("span",{class:"group-kind-dot","aria-hidden":"true"},W,!1,void 0,this)),r("span",{class:"group-chip-count",children:[Ne.length," node",Ne.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),r(jd,{nodeId:e.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{class:"canvas-node-owner",style:{...ve,zIndex:"auto"},onPointerEnter:()=>{Qa.value=e.id},onPointerLeave:()=>{if(Qa.value===e.id)Qa.value=null},children:[M&&r("div",{class:"group-frame-hit","aria-hidden":"true",style:{zIndex:`calc(${e.zIndex} - var(--node-hit-offset, 3))`},onPointerDown:(W)=>{if(L(W),W.button===0&&!W.shiftKey)l.current?.focus({preventScroll:!0})},onMouseDown:(W)=>{if(W.button===0||W.shiftKey)W.preventDefault()},onDblClick:N},void 0,!1,void 0,this),r("div",{ref:l,class:`${re}${pe?" is-drop-target":""}${Ue?" is-drop-source":""}${xe?" is-edge-target":""}${M&&ke?" group-menu-open":""}`,"data-node-type":e.type,"data-node-id":e.id,style:{position:"relative",left:0,top:0,width:"100%",height:e.collapsed?"auto":"100%",zIndex:e.zIndex},tabIndex:o?0:-1,onKeyDown:Y,onPointerDown:L,onMouseDown:(W)=>{if(W.shiftKey)W.preventDefault()},onDblClick:N,children:[r("div",{class:"node-content",children:[M&&r("div",{class:"node-titlebar group-edge-row",onPointerDown:P,children:[r("span",{class:"group-name-pill",children:[h?r("input",{ref:v,class:"node-title-input group-title-input",value:B,onBlur:(W)=>J(W.target.value),onKeyDown:(W)=>{if(W.key==="Enter")J(W.target.value);if(W.key==="Escape")g(!1)},onClick:(W)=>W.stopPropagation()},void 0,!1,void 0,this):r("span",{class:"group-name",children:B},void 0,!1,void 0,this),r("span",{class:"group-count",children:Ne.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"group-edge-spacer"},void 0,!1,void 0,this),r("span",{class:"group-actions",role:"toolbar","aria-label":`${B} actions`,children:[r(_e,{label:"Auto-arrange children",align:"end",children:r("button",{type:"button",class:"group-action","aria-label":"Auto-arrange children",disabled:Ne.length===0,onClick:(W)=>{W.stopPropagation(),em(e.id,Ne,"grid")},children:r("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[r("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("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)},void 0,!1,void 0,this),r(_e,{label:"Collapse group",align:"end",children:r("button",{type:"button",class:"group-action","aria-label":"Collapse group",onClick:(W)=>{W.stopPropagation(),Hi(e.id)},children:r("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:r("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)},void 0,!1,void 0,this),r("button",{type:"button",class:"group-action","aria-label":"Group menu","aria-expanded":ke,onClick:(W)=>{W.stopPropagation(),ae((ye)=>!ye)},children:r(ml,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),ke&&r("div",{class:"group-menu",role:"menu",onPointerDown:(W)=>W.stopPropagation(),children:[r("button",{type:"button",role:"menuitem",onClick:(W)=>{W.stopPropagation(),ae(!1),g(!0),requestAnimationFrame(()=>v.current?.focus())},children:"Rename"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",onClick:(W)=>{W.stopPropagation(),ae(!1),ei(e.id),Ms(e.id)},children:"Ungroup"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",disabled:Ne.length===0,onClick:(W)=>{W.stopPropagation(),ae(!1),Su(Ne)},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),!M&&r("div",{class:"node-titlebar",onPointerDown:P,children:[r(hC,{node:e,pinned:s,title:B,fold:De,children:(()=>{let W=Bo(e.type);return r(W,{size:Math.round(14*Fe)},void 0,!1,void 0,this)})()},void 0,!1,void 0,this),typeof e.data.axWorkStatus==="string"&&r("span",{class:`node-ax-status node-ax-status-${e.data.axWorkStatus}`,children:e.data.axWorkStatus},void 0,!1,void 0,this),h?r("input",{ref:v,class:"node-title-input",value:B,onBlur:(W)=>J(W.target.value),onKeyDown:(W)=>{if(W.key==="Enter")J(W.target.value);if(W.key==="Escape")g(!1)},onClick:(W)=>W.stopPropagation()},void 0,!1,void 0,this):r("span",{ref:a,class:"node-title",children:B},void 0,!1,void 0,this),r(yC,{node:e,pinned:s,fold:De},void 0,!1,void 0,this),r(mC,{node:e,pinned:s,fold:De},void 0,!1,void 0,this),r("div",{class:"node-controls",children:[he&&r(_e,{label:"Pinned in place",align:"end",fitWithin:".node-content",tapToOpen:!0,children:r("span",{class:"pin-indicator",children:"⊙"},void 0,!1,void 0,this)},void 0,!1,void 0,this),qa.has(e.type)&&r(_e,{label:"Expand (focus mode)",align:"end",fitWithin:".node-content",children:r("button",{type:"button",onClick:(W)=>{W.stopPropagation(),xo(e.id)},"aria-label":"Expand (focus mode)",children:r(uS,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e.type==="board"?c&&r(ho,{board:c,inNodeHeader:!0},void 0,!1,void 0,this):r(_e,{label:s?"Remove from context":"Add to context",align:"end",fitWithin:".node-content",children:r("button",{type:"button",class:`ctx-pin-btn${s?" ctx-pin-active":""}`,onClick:(W)=>{W.stopPropagation(),lo(e.id)},"aria-label":s?"Remove from context":"Add to context","aria-pressed":s,children:r("span",{class:"ctx-pin-mark",children:[r(uo,{},void 0,!1,void 0,this),s&&gC(e.id)&&r("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)},void 0,!1,void 0,this),r("button",{type:"button",class:"node-hover-control",onClick:(W)=>{W.stopPropagation(),n?.(W,e.id)},"aria-label":"More actions",children:r(ml,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",class:"node-hover-control",onClick:(W)=>{W.stopPropagation(),Xr(e.id)},"aria-label":"Close",children:r(Tt,{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&&r("div",{ref:X,class:"node-body",children:[t,r(qd,{node:e},void 0,!1,void 0,this),!M&&r(jd,{nodeId:e.id},void 0,!1,void 0,this),r(Zd,{node:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(e.collapsed||M)&&r(jd,{nodeId:e.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&r("div",{class:"node-resize-handle",onPointerDown:(W)=>I(W,e.size.width,e.size.height)},void 0,!1,void 0,this),i&&["tl","tr","bl","br"].map((W)=>r("span",{class:`node-selection-handle is-${W}`,"aria-hidden":"true"},W,!1,void 0,this)),$i.value.has(e.id)&&r("span",{class:"node-yield-pill","data-testid":"yield-pill",children:[r("span",{class:"node-yield-dot","aria-hidden":"true"},void 0,!1,void 0,this),$i.value.get(e.id)," took over — agent yielded"]},void 0,!0,void 0,this),!M&&["top","right","bottom","left"].map((W)=>r("span",{class:`node-port-dot node-port-dot-${W}`,"aria-hidden":"true"},W,!1,void 0,this))]},void 0,!0,void 0,this),!M&&["top","right","bottom","left"].map((W)=>r("div",{class:`node-port node-port-${W}`,onPointerDown:(ye)=>{if(ye.button!==0)return;ye.stopPropagation(),ye.preventDefault(),ye.currentTarget.setPointerCapture(ye.pointerId);let He=e.position.x+e.size.width/2,R=e.position.y+e.size.height/2,ne=e.size.width/2,Ce=e.size.height/2,Ie,fe;switch(W){case"top":Ie=He,fe=R-Ce;break;case"bottom":Ie=He,fe=R+Ce;break;case"left":Ie=He-ne,fe=R;break;case"right":Ie=He+ne,fe=R;break}At.value={fromId:e.id,fromX:Ie,fromY:fe,cursorX:Ie,cursorY:fe}}},W,!1,void 0,this))]},void 0,!0,void 0,this)}function Gd({node:e}){let t=typeof e.data.boardId==="string"?e.data.boardId:"",n=Ge.value.find((o)=>o.id===t);return r("div",{class:"board-node",children:[r("div",{class:"board-node-content",children:[r("div",{class:"board-node-label",children:"Linked board"},void 0,!1,void 0,this),r("strong",{class:"board-node-title",children:n?.name??"Missing board"},void 0,!1,void 0,this),r("div",{class:"board-node-meta",children:n?`${n.nodeCount} nodes${n.pin?" · pinned, so it travels with you":""}`:t||"No target id"},void 0,!1,void 0,this),n?.summary&&r("p",{class:"board-node-summary",children:n.summary},void 0,!1,void 0,this),!!n?.pinnedTitles?.length&&r("p",{class:"board-node-meta",children:["Pinned: ",n.pinnedTitles.map((o)=>o.title).join(", ")]},void 0,!0,void 0,this),!!n?.backlinks?.length&&r("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),r("button",{class:"board-node-open",type:"button",disabled:!n,onClick:()=>n&&void Mn(n.id),children:[n?"Open board":"Target unavailable",n&&r(ri,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function QC(){let e=Yn(),t=[...et.value.values()],n=D(null);if(q(()=>{let s=n.current;if(!s)return;let a=new ResizeObserver(()=>void Jr());return a.observe(s),()=>a.disconnect()},[e?.id,t.length>0]),!e||t.length===0)return null;let o=[...new Set(t.map(Gn))],i=Io.value?.boardId===e.id?Io.value.kind:null;return r("div",{ref:n,class:"relation-legend","aria-label":"Relation legend",onPointerDown:(s)=>s.stopPropagation(),children:[r("select",{"aria-label":"Filter board relations",value:i??"",onChange:(s)=>{let a=s.currentTarget.value;Io.value=a?{boardId:e.id,kind:a}:null},children:[r("option",{value:"",children:"All relations"},void 0,!1,void 0,this),o.map((s)=>r("option",{value:s,children:[s," · ",t.filter((a)=>Gn(a)===s).length]},s,!0,void 0,this))]},void 0,!0,void 0,this),o.map((s)=>{let a=mo({kind:s},e.relationVocabulary);return r("button",{type:"button","aria-pressed":i===s,style:{"--relation-ink":`var(--c-rel-${a.ink})`},onClick:()=>{Io.value=i===s?null:{boardId:e.id,kind:s}},children:[r("span",{class:"relation-swatch","aria-hidden":"true"},void 0,!1,void 0,this),s," ",r("span",{class:"relation-count",children:t.filter((l)=>Gn(l)===s).length},void 0,!1,void 0,this)]},s,!0,void 0,this)})]},void 0,!0,void 0,this)}function eT(){let e=mi.value?.label;return e&&e!==ua?e:"the agent"}var ug=ie(null);function lg(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":` · ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function cg(e){return e.actor==="agent"?Nr(e):"you"}function q$(e,t){if(e.changedBy?.actor!=="agent"&&e.changedBy?.actor!=="human")return null;let n=cg(e.changedBy),i=!!e.createdBy&&cg(e.createdBy)!==n?`${n==="you"?"You":n} relabelled it${lg(e.changedAt)} (drawn by ${e.createdBy?cg(e.createdBy):""}${lg(e.createdAt)})`:`${n==="you"?"You drew it":`Drawn by ${n}`}${lg(e.createdAt??e.changedAt)}`;return t?`${i} · not seen by ${eT()} yet`:i}function tT(){let e=ug.value;if(!e||e.view!==Te.value||!et.value.has(e.edgeId))return null;return r("span",{class:"toolbar-tooltip edge-hint",role:"tooltip","data-testid":"edge-hint",style:{left:`${e.x}px`,top:`${e.y}px`},children:r("span",{class:"toolbar-tooltip-label",children:e.text},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var G$="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";function K$(e){if(!Number.isFinite(e)||e<=0)return 1;return e<1?1/e:1}function V$(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.style&&mo(e,Yn()?.relationVocabulary).kind==="related")return`${2*t} ${5*t}`;if(e.type==="references"&&!e.style)return n;return}function Kd(e,t){let n=e.position.x+e.size.width/2,o=e.position.y+e.size.height/2,i=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=i-n,l=s-o,c=e.size.width/2,u=e.size.height/2,d=Math.abs(l/(a||0.001)),p=u/(c||0.001);if(d>p){let m=l>0?1:-1;return{x:n+u/d*(a>0?1:-1),y:o+u*m,side:m>0?"bottom":"top"}}let f=a>0?1:-1;return{x:n+c*f,y:o+d*c*(l>0?1:-1),side:f>0?"right":"left"}}function Vd(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 X$(e,t,n,o,i,s,a,l){return{x:0.125*e+0.375*n+0.375*i+0.125*a,y:0.125*t+0.375*o+0.375*s+0.125*l}}function J$({edge:e,fromNode:t,toNode:n,start:o,end:i,focused:s,dimmed:a,selected:l,scale:c,part:u}){let d=i.x-o.x,p=i.y-o.y,f=Math.sqrt(d*d+p*p),m=Math.min(Math.max(f*0.35,32),160),h=Vd(o,m),g=Vd(i,m),v=`M ${o.x} ${o.y} C ${h.x} ${h.y}, ${g.x} ${g.y}, ${i.x} ${i.y}`,b=mo(e,Yn()?.relationVocabulary),x=`var(--c-rel-${b.ink})`,C=b.directed,y=V$(e,c),k=Math.min(c,2.2),_=Te.value.scale,I=dC(e),w=e.label??e.kind,P=!!w&&_>=0.35,L=P?9:5,N=P?(w?.length??0)*7:0,Y=`not seen by ${eT()}`,B=12+Y.length*6.2+4,J=L*2+N+(I.notSeen?(N?12:0)+B:0),X=I.notSeen&&_>=0.6&&f>=(J+60)*k,V=I.notSeen?(N?12:0)+(X?B:12):0,ee=L*2+N+V,he=-ee/2+L,A=he+N+(N?12:0),M=P||I.notSeen?X$(o.x,o.y,h.x,h.y,g.x,g.y,i.x,i.y):null,O=`edge-path-${e.id}`,Pe=(Ae)=>{Ae.stopPropagation(),br.value=e.id},Fe=(Ae,ve)=>{let z=[`${String(t.data.title??t.id)} → ${String(n.data.title??n.id)}`,ma(e),q$(e,I.notSeen)].filter(Boolean).join(`
386
- `),re=Ae.getBoundingClientRect();ug.value={x:ve?.x??re.left+re.width/2,y:(ve?.y??re.bottom)+8,text:z,edgeId:e.id,view:Te.value}},De=()=>{ug.value=null};if(u==="pill-hits"){if(!M)return null;return r("rect",{class:"edge-pill-hit","data-testid":"edge-pill-hit","data-edge-id":e.id,x:M.x-ee/2*k,y:M.y-10*k,width:ee*k,height:20*k,rx:10*k,fill:"transparent",onClick:Pe,onPointerEnter:(Ae)=>Fe(Ae.currentTarget),onPointerLeave:De},void 0,!1,void 0,this)}if(u==="pills"){if(!M)return null;return r("g",{transform:`translate(${M.x}, ${M.y})`,class:"edge-pill","data-testid":"edge-pill",opacity:a&&!l?0.35:1,children:[r("rect",{class:"edge-label-bg",x:-ee/2*k,y:-10*k,width:ee*k,height:20*k,rx:10*k},void 0,!1,void 0,this),P&&r("text",{class:"edge-label",x:(he+N/2)*k,"text-anchor":"middle","dominant-baseline":"central",fill:x,children:w},void 0,!1,void 0,this),I.notSeen&&r("g",{class:"edge-link-mark is-not-seen","data-testid":"edge-link-mark",children:[N>0&&r("line",{x1:(A-6)*k,x2:(A-6)*k,y1:-6*k,y2:6*k,stroke:"var(--c-line)","stroke-width":k},void 0,!1,void 0,this),r("path",{transform:`translate(${A*k}, ${-5*k}) scale(${0.4166666666666667*k})`,d:G$,fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},void 0,!1,void 0,this),X&&r("text",{class:"edge-label",x:(A+14)*k,"text-anchor":"start","dominant-baseline":"central",fill:"currentColor",children:Y},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}return r("g",{children:[r("path",{"data-edge-id":e.id,d:v,fill:"none",stroke:"transparent","stroke-width":12*c,style:{cursor:"pointer",pointerEvents:"stroke"},onClick:Pe,onPointerEnter:(Ae)=>Fe(Ae.currentTarget,{x:Ae.clientX,y:Ae.clientY}),onPointerLeave:De},void 0,!1,void 0,this),r("path",{id:O,d:v,class:l?"edge-line edge-selected":"edge-line",fill:"none",stroke:x,"stroke-width":(l?3:s?2.5:1.5)*c,"stroke-dasharray":y,"marker-end":C?"url(#edge-arrow)":void 0,opacity:l?1:a?0.2:s?1:0.85,style:{color:x}},void 0,!1,void 0,this),e.animated&&r("circle",{r:3*c,fill:x,opacity:"0.9",children:r("animateMotion",{dur:"2s",repeatCount:"indefinite",children:r("mpath",{href:`#${O}`},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 Xd({nodes:e,edges:t,part:n}){let o=e.value,i=Array.from(t.value.values()),s=ag.value,a=s!==null,l=wr.value,c=l!==null,u=K$(Te.value.scale),d=new Map,p=new Map;for(let y of i){if(y.toBoardId)continue;let k=Bs(y.from),_=Bs(y.to);if(!k||!_||k.id===_.id)continue;let I=Kd(k,_),w=Kd(_,k);d.set(y.id,{start:I,end:w});for(let[P,L,N]of[[I,k,_],[w,_,k]]){let Y=`${L.id}:${P.side}`,B=P.side==="left"||P.side==="right",J=p.get(Y)??[];J.push({anchor:P,node:L,order:B?N.position.y:N.position.x,id:y.id}),p.set(Y,J)}}for(let y of p.values()){if(y.length<2)continue;y.sort((k,_)=>k.order-_.order||k.id.localeCompare(_.id)),y.forEach(({anchor:k,node:_},I)=>{let w=(I+1)/(y.length+1);if(k.side==="left"||k.side==="right")k.y=_.position.y+_.size.height*w;else k.x=_.position.x+_.size.width*w})}if(i.length===0&&(n!=="lines"||!At.value))return null;let f=96,m=Array.from(o.values());if(m.length===0)return null;let h=Math.min(...m.map((y)=>y.position.x))-f,g=Math.min(...m.map((y)=>y.position.y))-f,v=Math.max(...m.map((y)=>y.position.x+y.size.width))+f,b=Math.max(...m.map((y)=>y.position.y+y.size.height))+f,x=Math.max(1,v-h),C=Math.max(1,b-g);return r("svg",{"aria-label":n==="lines"?"Canvas connections":void 0,"aria-hidden":n!=="lines"?"true":void 0,role:n==="lines"?"img":void 0,viewBox:`${h} ${g} ${x} ${C}`,width:x,height:C,style:{position:"absolute",top:`${g}px`,left:`${h}px`,zIndex:n==="pills"?1:n==="pill-hits"?"calc(var(--node-port-z, -1) - 1)":"var(--edge-line-z, -5)",pointerEvents:"none",overflow:"visible","--edge-chrome-scale":u.toFixed(3),"--edge-label-scale":Math.min(u,2.2).toFixed(3)},children:[n==="lines"&&r("title",{children:"Canvas connections"},void 0,!1,void 0,this),r("defs",{children:r("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:r("path",{d:"M 0 1 L 10 5 L 0 9 z",fill:"context-stroke",opacity:"0.75"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i.map((y)=>{if(y.toBoardId)return null;let k=Bs(y.from),_=Bs(y.to),I=d.get(y.id);if(!k||!_||!I)return null;let w=a&&(y.from===s||y.to===s),P=c&&!(l.has(y.from)||l.has(y.to)),L=Vl.value;return r(J$,{edge:y,fromNode:k,toNode:_,start:I.start,end:I.end,focused:w,dimmed:L!==null&&!L.links.has(y.id)||P,selected:br.value===y.id,scale:u,part:n},y.id,!1,void 0,this)}),n==="lines"&&At.value&&(()=>{let y=At.value,k=Bs(y.fromId),_={position:{x:y.cursorX,y:y.cursorY},size:{width:1,height:1}},I;if(k){let w=Kd(k,_),P=Kd(_,k),L=P.x-w.x,N=P.y-w.y,Y=Math.sqrt(L*L+N*N),B=Math.min(Math.max(Y*0.35,32),160),J=Vd(w,B),X=Vd(P,B);I=`M ${w.x} ${w.y} C ${J.x} ${J.y}, ${X.x} ${X.y}, ${P.x} ${P.y}`}else{let w=y.cursorX-y.fromX,P=y.cursorY-y.fromY,L=Math.sqrt(w*w+P*P),N=Math.min(L*0.25,80),Y=w/(L||1),B=P/(L||1);I=`M ${y.fromX} ${y.fromY} C ${y.fromX+Y*N} ${y.fromY+B*N}, ${y.cursorX-Y*N} ${y.cursorY-B*N}, ${y.cursorX} ${y.cursorY}`}return r("g",{children:[r("path",{d:I,fill:"none",stroke:"var(--c-accent)","stroke-width":6*u,opacity:"0.1",style:{filter:"blur(3px)"}},void 0,!1,void 0,this),r("path",{d:I,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),r("circle",{cx:y.cursorX,cy:y.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 Y$(e){let[t,...n]=e;if(!t)return"";return n.reduce((o,i)=>`${o} L ${i.x} ${i.y}`,`M ${t.x} ${t.y}`)}function dg({annotations:e}){if(e.length===0)return null;return r("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 r("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 r("path",{d:Y$(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 Q$(e){switch(e.type){case"markdown":return r(Yu,{node:e},void 0,!1,void 0,this);case"mcp-app":return r(di,{node:e},void 0,!1,void 0,this);case"webpage":return r(Ed,{node:e},void 0,!1,void 0,this);case"json-render":return r(di,{node:e},void 0,!1,void 0,this);case"graph":return r(di,{node:e},void 0,!1,void 0,this);case"board":return r(Gd,{node:e},void 0,!1,void 0,this);case"prompt":return r(Ad,{node:e},void 0,!1,void 0,this);case"response":return r(Rd,{node:e},void 0,!1,void 0,this);case"status":return r(Td,{node:e},void 0,!1,void 0,this);case"context":return r(zu,{node:e},void 0,!1,void 0,this);case"ledger":return r(Du,{node:e},void 0,!1,void 0,this);case"trace":return r(Pd,{node:e},void 0,!1,void 0,this);case"file":return r(Ou,{node:e},void 0,!1,void 0,this);case"diff":return r($u,{node:e},void 0,!1,void 0,this);case"mermaid":return r(sd,{node:e},void 0,!1,void 0,this);case"image":return r(Id,{node:e},void 0,!1,void 0,this);case"html":return r(Hl,{node:e},void 0,!1,void 0,this);case"group":return r(q_,{node:e},void 0,!1,void 0,this);default:return r("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}class iT extends Br{shouldComponentUpdate(e){return e.node!==this.props.node||e.onContextMenu!==this.props.onContextMenu}render(){let{node:e,onContextMenu:t}=this.props;return r(YC,{node:e,onContextMenu:t,children:Q$(e)},void 0,!1,void 0,this)}}function eL(e,t,n){let o=n.x-t.x,i=n.y-t.y,s=o*o+i*i;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)*i)/s));return Math.hypot(e.x-(t.x+a*o),e.y-(t.y+a*i))}function tL(e,t,n){for(let o=e.length-1;o>=0;o--){let i=e[o];if(!i)continue;let s=n+i.width;if(t.x<i.bounds.x-s||t.x>i.bounds.x+i.bounds.width+s||t.y<i.bounds.y-s||t.y>i.bounds.y+i.bounds.height+s)continue;if(i.type==="text")return i;for(let a=1;a<i.points.length;a++){let l=i.points[a-1],c=i.points[a];if(l&&c&&eL(t,l,c)<=n+i.width/2)return i}}return null}var pg="currentColor",nT=4,oT=24,nL=14,rT={width:520,height:420};function oL(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 mg(e){let t=e.trim();if(!t)return[];let n=t.includes(`
387
- `)?t.split(/\r?\n/):t.split(/\s+/),o=new Set,i=[];for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let l=oL(a);if(!l||o.has(l))continue;o.add(l),i.push(l)}return i}function rL(e){let t=mg(e.getData("text/uri-list"));if(t.length>0)return t;return mg(e.getData("text/plain"))}function iL(e){if(!e)return!1;return e.types.includes("text/uri-list")||e.types.includes("text/plain")}function fg(e){if(!(e instanceof HTMLElement))return!1;return Boolean(e.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}function sL(e,t,n=new Set){let o=[],i=0;for(let s of e){if(n.has(s.id))continue;if(t&&s.id===t)continue;if(s.type==="group")o.splice(i++,0,s);else o.push(s)}return o}function sT({onNodeContextMenu:e,onEdgeContextMenu:t,onCanvasContextMenu:n,annotationMode:o=!1,annotationTool:i=null}){let s=Te.value,a=D(!1),l=D(null),c=D(!1),u=D([]),[d,p]=E(null),[f,m]=E(null),[h,g]=E(null),v=D(null),[b,x]=E(!1),C=D(0),y=D(null),k=D(null);q(()=>{let z=null,re=sn(()=>{Te.value;let Ne=k.current;if(!Ne)return;if(Ne.style.willChange="transform",z)clearTimeout(z);z=setTimeout(()=>{Ne.style.willChange="auto"},180)});return()=>{if(z)clearTimeout(z);re()}},[]);let _=Au({viewport:Te,disabled:o,onBackgroundContextMenu:n,onEdgeContextMenu:t,onViewportChange:(z)=>{if(a.current||o)return;co(),Jk(z)},onViewportCommit:(z)=>{if(a.current||o)return;co(),pl(z)}}),I=oe((z)=>{v.current=z,g(z)},[]),w=oe(async(z,re,Ne)=>{if(z.length===0)return;let{width:ke,height:ae}=rT,Se=24,pe=Math.ceil(Math.sqrt(z.length)),Ue=Math.ceil(z.length/pe),xe=pe*ke+Math.max(0,pe-1)*Se,qe=Ue*ae+Math.max(0,Ue-1)*Se;for(let W=0;W<z.length;W++){let ye=W%pe,He=Math.floor(W/pe),R=re-xe/2+ye*(ke+Se),ne=Ne-qe/2+He*(ae+Se);await No({type:"webpage",content:z[W],x:R,y:ne,width:ke,height:ae})}},[]),P=oe((z)=>{let re=_.current;if(!re)return;if(i==="eraser"){if((z.target instanceof Element?z.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;z.preventDefault(),z.stopPropagation();let Ue=re.getBoundingClientRect(),xe=Te.value,qe={x:(z.clientX-Ue.left-xe.x)/xe.scale,y:(z.clientY-Ue.top-xe.y)/xe.scale},W=tL(Array.from(Ls.value.values()),qe,nL/xe.scale);if(W)Xk(W.id);return}if(i==="text"){if((z.target instanceof Element?z.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;z.preventDefault(),z.stopPropagation(),gt.value=null,$n();let Ue=re.getBoundingClientRect(),xe=Te.value;I({x:(z.clientX-Ue.left-xe.x)/xe.scale,y:(z.clientY-Ue.top-xe.y)/xe.scale,value:""});return}if(i==="pen"){if((z.target instanceof Element?z.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;z.preventDefault(),z.stopPropagation(),gt.value=null,$n(),c.current=!0;let Ue=re.getBoundingClientRect(),xe=Te.value,qe={x:(z.clientX-Ue.left-xe.x)/xe.scale,y:(z.clientY-Ue.top-xe.y)/xe.scale};u.current=[qe],m({id:"draft-annotation",type:"freehand",points:[qe],bounds:{x:0,y:0,width:0,height:0},color:pg,width:nT,createdAt:""}),re.setPointerCapture(z.pointerId);return}if(z.target!==re)return;if(Ds()||z.button===1||z.button===2){if(!z.shiftKey&&!y.current)gt.value=null,$n();return}z.preventDefault(),z.stopPropagation(),a.current=!0;let Ne=re.getBoundingClientRect(),ke=z.clientX-Ne.left,ae=z.clientY-Ne.top,Se={startX:ke,startY:ae,currentX:ke,currentY:ae};y.current=Se,p(Se),re.setPointerCapture(z.pointerId)},[i,_]);q(()=>sn(()=>{let z=Te.value,re=l.current,Ne=_.current;if(!re||!Ne)return;let ke=Ne.getBoundingClientRect();uu({x:(re.x-ke.left-z.x)/z.scale,y:(re.y-ke.top-z.y)/z.scale})}),[]);let L=oe((z)=>{{let ke=_.current;if(ke){l.current={x:z.clientX,y:z.clientY};let ae=ke.getBoundingClientRect(),Se=Te.value;uu({x:(z.clientX-ae.left-Se.x)/Se.scale,y:(z.clientY-ae.top-Se.y)/Se.scale})}}if(c.current){let ke=_.current;if(!ke)return;let ae=ke.getBoundingClientRect(),Se=Te.value,pe={x:(z.clientX-ae.left-Se.x)/Se.scale,y:(z.clientY-ae.top-Se.y)/Se.scale},Ue=u.current.at(-1);if(Ue&&Math.hypot(pe.x-Ue.x,pe.y-Ue.y)<2)return;u.current=[...u.current,pe],m((xe)=>xe?{...xe,points:u.current}:null);return}if(!a.current||!y.current)return;let re=_.current?.getBoundingClientRect();if(!re)return;let Ne={...y.current,currentX:z.clientX-re.left,currentY:z.clientY-re.top};y.current=Ne,p(Ne)},[_]),N=oe((z)=>{if(c.current){c.current=!1;let pe=u.current;if(u.current=[],m(null),pe.length>=2)dm({points:pe,color:pg,width:nT});let Ue=_.current;if(Ue?.hasPointerCapture(z.pointerId))Ue.releasePointerCapture(z.pointerId);return}let re=y.current;if(!a.current||!re)return;a.current=!1,y.current=null;let Ne=Math.min(re.startX,re.currentX),ke=Math.max(re.startX,re.currentX),ae=Math.min(re.startY,re.currentY),Se=Math.max(re.startY,re.currentY);if(ke-Ne<=5&&Se-ae<=5)gt.value=null,$n();if(ke-Ne>5||Se-ae>5){let pe=Te.value,Ue=(Ne-pe.x)/pe.scale,xe=(ke-pe.x)/pe.scale,qe=(ae-pe.y)/pe.scale,W=(Se-pe.y)/pe.scale,ye=[];for(let He of H.value.values()){let R=He.position.x,ne=He.position.y;if(R+He.size.width>Ue&&R<xe&&ne+He.size.height>qe&&ne<W)ye.push(He.id)}if(ye.length>0)Fk(ye)}p(null)},[]);q(()=>{if(o)return;if(!c.current&&!f&&!h)return;c.current=!1,u.current=[],m(null),I(null)},[o,f,I,h]);let Y=oe(()=>{let z=v.current;if(!z)return;let re=z.value.trim();if(I(null),!re)return;let Ne={x:z.x,y:z.y};dm({type:"text",points:[Ne],color:pg,width:oT,text:re})},[I]);q(()=>{if(i!=="text"&&h)I(null)},[i,I,h]),q(()=>{let z=(Se,pe,Ue)=>{let xe=null;for(let qe of H.value.values()){if(qe.id===Ue||qe.type==="group")continue;if(Se>=qe.position.x&&Se<=qe.position.x+qe.size.width&&pe>=qe.position.y&&pe<=qe.position.y+qe.size.height)xe=qe.id}return xe};function re(Se){if(!At.value)return;let pe=_.current;if(!pe)return;let Ue=pe.getBoundingClientRect(),xe=Te.value,qe=(Se.clientX-Ue.left-xe.x)/xe.scale,W=(Se.clientY-Ue.top-xe.y)/xe.scale;At.value={...At.value,cursorX:qe,cursorY:W,targetId:z(qe,W,At.value.fromId)}}function Ne(){let Se=At.value;if(!Se)return;At.value=null;let pe=Se.targetId;if(!pe)return;if(Se.withLabel){On("Edge label","label text").then((Ue)=>{yr(Se.fromId,pe,"relation",Ue??void 0)});return}yr(Se.fromId,pe,"relation",void 0)}function ke(Se){let pe=At.value;if(!pe)return;if(Se.key==="Escape")Se.preventDefault(),At.value=null;else if(Se.key==="l"||Se.key==="L")Se.preventDefault(),At.value={...pe,withLabel:!pe.withLabel}}function ae(){At.value=null}return document.addEventListener("pointermove",re),document.addEventListener("pointerup",Ne),document.addEventListener("pointercancel",ae),document.addEventListener("keydown",ke),()=>{document.removeEventListener("pointermove",re),document.removeEventListener("pointerup",Ne),document.removeEventListener("pointercancel",ae),document.removeEventListener("keydown",ke)}},[_]);let B=oe((z)=>{if(o)return;let re=_.current;if(!re||z.target!==re||!n)return;let Ne=re.getBoundingClientRect(),ke=Te.value,ae=(z.clientX-Ne.left-ke.x)/ke.scale,Se=(z.clientY-Ne.top-ke.y)/ke.scale;n(z,ae,Se)},[o,_,n]),J=oe((z)=>{z.preventDefault()},[]),X=oe((z)=>{if(fg(z.target instanceof Element?z.target:null))return;z.preventDefault()},[]),V=oe((z)=>{if(z.preventDefault(),C.current++,z.dataTransfer?.types.includes("Files")||iL(z.dataTransfer))x(!0)},[]),ee=oe((z)=>{if(z.preventDefault(),z.dataTransfer)z.dataTransfer.dropEffect="copy"},[]),he=oe((z)=>{if(z.preventDefault(),C.current--,C.current<=0)C.current=0,x(!1)},[]),A=oe(async(z)=>{z.preventDefault(),x(!1),C.current=0;let re=_.current;if(!re||!z.dataTransfer)return;let Ne=re.getBoundingClientRect(),ke=Te.value,ae=(z.clientX-Ne.left-ke.x)/ke.scale,Se=(z.clientY-Ne.top-ke.y)/ke.scale,pe=Array.from(z.dataTransfer.files);if(pe.length===0){let Ue=rL(z.dataTransfer);await w(Ue,ae,Se);return}await ca(pe,ae,Se)},[_,w]);q(()=>{let z=async(re)=>{if(re.defaultPrevented)return;if(fg(re.target instanceof Element?re.target:null))return;if(fg(document.activeElement))return;let Ne=re.clipboardData?.getData("text/plain")??"",ke=mg(Ne);if(ke.length===0)return;let ae=_.current;if(!ae)return;re.preventDefault();let Se=ae.getBoundingClientRect(),pe=Te.value,Ue=(Se.width/2-pe.x)/pe.scale,xe=(Se.height/2-pe.y)/pe.scale;await w(ke,Ue,xe)};return document.addEventListener("paste",z),()=>{document.removeEventListener("paste",z)}},[_,w]);let te=sL(H.value.values(),Bt.value,new Set(al.value.keys())),M=te.reduce((z,re)=>Math.min(z,Math.floor(re.zIndex)),0),Pe=te.reduce((z,re)=>Math.max(z,Math.ceil(re.zIndex)),0)-M+3,Fe=Xo.value,De=Fe?H.value.get(Fe.groupId):void 0,Ae=Fe?H.value.get(Fe.nodeId):void 0,ve=null;if(d){let z=Math.min(d.startX,d.currentX),re=Math.min(d.startY,d.currentY),Ne=Math.abs(d.currentX-d.startX),ke=Math.abs(d.currentY-d.startY);ve={position:"absolute",left:`${z}px`,top:`${re}px`,width:`${Ne}px`,height:`${ke}px`,pointerEvents:"none"}}return r("div",{class:`canvas-viewport${Ds()?" pan-mode":""}`,ref:_,tabIndex:0,onPointerDown:P,onPointerMove:L,onPointerLeave:()=>{l.current=null,uu(null)},onPointerUp:N,onContextMenu:J,onDblClick:B,onDragStart:X,onDragEnter:V,onDragOver:ee,onDragLeave:he,onDrop:A,style:{width:"100%",height:"100%",position:"relative",overflow:"clip",cursor:i==="eraser"?"cell":i==="text"?"text":o||At.value||a.current||Wn.value==="connect"?"crosshair":Ds()?"grab":"default"},children:[r("div",{ref:k,class:"canvas-world",style:{transform:`matrix(${s.scale}, 0, 0, ${s.scale}, ${s.x}, ${s.y})`,transformOrigin:"0 0","--node-port-z":M-1,"--node-hit-offset":Pe,"--edge-line-z":M-Pe-1,position:"absolute",top:0,left:0},children:[r(MC,{},void 0,!1,void 0,this),r(rC,{},void 0,!1,void 0,this),r(lC,{},void 0,!1,void 0,this),r(cC,{},void 0,!1,void 0,this),r(Xd,{nodes:H,edges:et,part:"lines"},void 0,!1,void 0,this),r(Xd,{nodes:H,edges:et,part:"pills"},void 0,!1,void 0,this),r(Xd,{nodes:H,edges:et,part:"pill-hits"},void 0,!1,void 0,this),At.value&&r("div",{class:"edge-hint-pill","data-testid":"edge-hint",style:{left:`${At.value.cursorX+14}px`,top:`${At.value.cursorY+14}px`},children:[r("span",{class:"edge-hint-main",children:At.value.targetId?"release to connect":"drag onto a node"},void 0,!1,void 0,this),r("span",{class:"edge-hint-keys",children:["esc cancels · L labels",At.value.withLabel?" · label on":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Fe&&De&&Ae&&r("div",{class:"drop-pill","data-testid":"drop-pill",style:{left:`${Ae.position.x}px`,top:`${Ae.position.y+Ae.size.height+10}px`},children:[r("span",{class:"drop-pill-text",children:Fe.mode==="add"?`release to add to ${String(De.data.title??"group")}`:`release to remove from ${String(De.data.title??"group")}`},void 0,!1,void 0,this),r("span",{class:"drop-pill-hint",children:Fe.mode==="add"?"esc keeps it out":"esc keeps it in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(dg,{annotations:Array.from(Ls.value.values())},void 0,!1,void 0,this),f&&f.points.length>=2&&r(dg,{annotations:[f]},void 0,!1,void 0,this),te.map((z)=>r(iT,{node:z,onContextMenu:e},z.id,!1,void 0,this)),is.value&&r("svg",{class:"snap-guides-svg",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"visible"},children:is.value.map((z,re)=>z.axis==="x"?r("line",{x1:z.pos,y1:z.from-20,x2:z.pos,y2:z.to+20,class:"snap-guide-line"},re,!1,void 0,this):r("line",{x1:z.from-20,y1:z.pos,x2:z.to+20,y2:z.pos,class:"snap-guide-line"},re,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&r("div",{class:`annotation-capture-layer${i==="eraser"?" erasing":""}${i==="text"?" text":""}`,"aria-hidden":"true"},void 0,!1,void 0,this),h&&r("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:`${oT*s.scale}px`},onInput:(z)=>I({...h,value:z.target.value}),onBlur:Y,onPointerDown:(z)=>z.stopPropagation(),onKeyDown:(z)=>{if(z.key==="Enter")z.preventDefault(),Y();if(z.key==="Escape")z.preventDefault(),I(null)}},void 0,!1,void 0,this),r(xC,{},void 0,!1,void 0,this),r(wC,{},void 0,!1,void 0,this),ve&&r("div",{class:"lasso-rect",style:ve},void 0,!1,void 0,this),b&&r("div",{class:"drop-zone-overlay",children:r("div",{class:"drop-zone-indicator",children:[r("div",{class:"drop-zone-icon",children:"+"},void 0,!1,void 0,this),r("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 Mr({label:e,value:t,options:n,onChange:o,className:i="",above:s=!1}){let[a,l]=E(!1),c=D(null),u=D(null),d=D(null),p=()=>{l(!1),u.current?.focus()};return Me(()=>{if(!a)return;(d.current?.querySelector('[aria-checked="true"]:not(:disabled)')??d.current?.querySelector("button:not(:disabled)"))?.focus();let m=(h)=>{if(h.target instanceof Node&&!c.current?.contains(h.target))l(!1)};return document.addEventListener("pointerdown",m),()=>document.removeEventListener("pointerdown",m)},[a]),r("div",{ref:c,class:`choice-menu ${i}`,onBlur:(f)=>{if(f.relatedTarget instanceof Node&&!c.current?.contains(f.relatedTarget))l(!1)},onKeyDown:(f)=>{if(f.key!=="Tab"&&(f.key!=="Escape"||a))f.stopPropagation();if(f.key==="Escape"&&a)f.preventDefault(),f.stopPropagation(),p();if(["ArrowDown","ArrowUp","Home","End"].includes(f.key)){if(f.preventDefault(),f.stopPropagation(),!a){l(!0);return}let m=[...d.current?.querySelectorAll("button:not(:disabled)")??[]];if(!m.length)return;let h=m.findIndex((v)=>v===document.activeElement),g=f.key==="Home"?0:f.key==="End"?m.length-1:(h+(f.key==="ArrowUp"?-1:1)+m.length)%m.length;m[g]?.focus()}},children:[r("button",{ref:u,type:"button",class:"choice-menu-trigger","aria-label":e,"aria-haspopup":"menu","aria-expanded":a,onClick:()=>l(!a),children:[r("span",{children:n.find((f)=>f.value===t)?.label??e},void 0,!1,void 0,this),r(Us,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a&&r("div",{ref:d,role:"menu","aria-label":e,class:`toolbar-menu choice-menu-options${s?" opens-above":""}`,children:n.map((f)=>r("button",{type:"button",role:"menuitemradio",class:`toolbar-menu-item${f.value===t?" active":""}`,"aria-checked":f.value===t,disabled:f.disabled,tabIndex:-1,"data-value":f.value,onClick:()=>{o(f.value),p()},children:[r("span",{children:f.label},void 0,!1,void 0,this),f.value===t&&r("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},f.value,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Jd(e){let t=D(null);return Me(()=>{let n=t.current,o=n?.parentElement;if(!n||!o)return;let i=()=>o.style.setProperty(e,`${n.getBoundingClientRect().height}px`);i();let s=new ResizeObserver(i);return s.observe(n),()=>{s.disconnect(),o.style.removeProperty(e)}},[e]),t}function aT(){let e=Jd("--command-bar-height"),t=[...Di.value],n=H.value,[o,i]=E(""),[s,a]=E(!1),l=aC.value,[c,u]=E(null),d=l.length>=2,p=!d&&l.length===1&&l[0].steerable?l[0]:null,f=d?c?l.find((g)=>g.value===c&&g.steerable)??null:null:p,m=f?.value??null,h=async()=>{let g=o.trim();if(!xt.value||!g||s)return;a(!0);let v=await fa(g,m);if(a(!1),v)i("")};return r("div",{ref:e,class:"command-bar","data-testid":"command-bar",hidden:!xt.value,style:!xt.value?{display:"none"}:void 0,children:[t.length>0&&r("div",{class:"command-bar-chips","aria-label":"Pinned context",children:[t.map((g)=>{let v=n.get(g),b=typeof v?.data.title==="string"&&v.data.title.trim()?v.data.title:v?.type??g;return r("span",{class:"command-bar-chip","data-node-id":g,children:[r("span",{class:"command-bar-chip-label",children:b},void 0,!1,void 0,this),r(_e,{label:"Remove from context",side:"up",children:r("button",{type:"button",class:"command-bar-chip-unpin","aria-label":`Unpin ${b}`,onClick:()=>lo(g),children:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},g,!0,void 0,this)}),r("span",{class:"command-bar-chips-note",children:"in agent context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"command-bar-composer",children:[r(js,{size:15,class:"command-bar-icon"},void 0,!1,void 0,this),d&&r(Mr,{className:"command-bar-target",label:"Steer which agent",value:m??"",above:!0,onChange:(g)=>u(g||null),options:[{value:"",label:"All agents"},...l.map((g)=>{let v=g.pendingSteers&&g.pendingSteers>0?` · ${g.pendingSteers} queued`:"",b=g.polling?" · polling":"";return{value:g.value,disabled:!g.steerable,label:g.attached?`${g.label}${b}${v}`:g.steerable?`${g.label} · writer${b}${v}`:`${g.label} · no inbox`}})]},void 0,!1,void 0,this),r("input",{class:"command-bar-input",type:"text",value:o,placeholder:`Steer ${f?.label??"the agent"}, or ${Ft("K")} to search the board…`,"aria-label":"Steer the agent",disabled:s,onInput:(g)=>i(g.target.value),onKeyDown:(g)=>{if(g.key==="Enter")g.preventDefault(),h()}},void 0,!1,void 0,this),r("button",{type:"button",class:"command-bar-send",disabled:s||!o.trim(),onClick:()=>void h(),children:s?"Sending…":"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function hg(e){let t=Math.max(0,Math.floor((Date.now()-new Date(e).getTime())/60000));if(t<1)return"just now";if(t<60)return`${t}m`;let n=Math.floor(t/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function Yd(e){let t=hg(e);return t==="just now"?t:`${t} ago`}var gg=ie(null),ep=ie(new Map);function yg(e){return e>=1000?`${(e/1000).toFixed(1)}k`:`${Math.round(e)}`}function Jl(e){return yg(e/4)}var Qd=null,lT=0;function zr(e=250){if(Qd)clearTimeout(Qd);Qd=setTimeout(()=>{Qd=null,aL()},e)}async function aL(){let e=++lT,t=se.value,n=()=>e===lT&&t===se.value,o=await de("fetchBriefSize","/api/canvas/context",null,{headers:{"x-pmx-proxied-read":"1"}});if(!n())return;if(o?.entries)gg.value={chars:JSON.stringify(o).length};let i=Ge.value.filter((a)=>a.pin);if(i.length===0){if(n())ep.value=new Map;return}let s=await de("fetchBoardReadStatus",`/api/canvas/ax/context-status?boards=${i.map((a)=>encodeURIComponent(a.id)).join(",")}`,null);if(n())ep.value=new Map(i.map((a)=>[a.id,s?.boards?.[a.id]??null]))}function uT(){let e=Di.value.size;if(e===0||qr.value)return null;return r("div",{class:"context-pin-bar",role:"region","aria-label":"Pinned context",children:[r(uo,{size:14},void 0,!1,void 0,this),r("span",{children:[bg(e,"node")," in context"]},void 0,!0,void 0,this),r(_e,{label:"Clear all context pins",side:"up",align:"end",children:r("button",{type:"button","aria-label":"Clear all context pins",onClick:lm,children:r(Tt,{size:12},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 bg(e,t){return`${e} ${t}${e===1?"":"s"}`}function vg(e){let t=H.value.get(e);return typeof t?.data.title==="string"&&t.data.title?t.data.title:e}function dT(){let[e,t]=E(!1),n=D(null),o=D(null),i=se.value;q(()=>{if(!e)return;zr();let v=(x)=>{if(x.key!=="Escape")return;t(!1),o.current?.focus()},b=(x)=>{if(n.current&&!n.current.contains(x.target))t(!1)};return window.addEventListener("keydown",v),window.addEventListener("pointerdown",b),()=>{window.removeEventListener("keydown",v),window.removeEventListener("pointerdown",b)}},[e]);let s=ut.value;if(!i&&!s)return null;let a=s?[]:[...Di.value],l=s?[]:[...ro.value.entries()],c=Ge.value.filter((v)=>v.pin&&(s||v.id!==i)),u=a.length===0&&c.length===0,d=[...a.map((v)=>hi.value[v]?.pinnedBy),...c.map((v)=>v.pin?.pinnedBy)],p=!u&&d.every((v)=>v?.actor==="agent"),f=gg.value,m=f?`≈ ${Jl(f.chars)} tokens`:"",h=mi.value,g=[];if(a.length)g.push({text:bg(a.length,"card")});if(l.length)g.push({text:`${l.length} near`,kind:"near"});if(c.length)g.push({text:bg(c.length,"board")});if(p){let v=d.find((b)=>b?.actor==="agent");g.push({text:`by ${v?Nr(v):"agent"}`,kind:"agent"})}return r("div",{class:"context-chip-wrap",ref:n,children:[r("button",{ref:o,type:"button",class:`context-chip${u?" is-empty":""}${e?" is-open":""}`,"aria-expanded":e,"aria-haspopup":"dialog","data-testid":"context-chip",onClick:()=>t(!e),children:[r("span",{class:"context-chip-pin",children:[r(uo,{size:13},void 0,!1,void 0,this),p&&r("span",{class:"context-chip-agent-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u?r("span",{children:"Nothing in context"},void 0,!1,void 0,this):r(be,{children:[r("span",{class:"context-chip-wide",children:g.map((v,b)=>r("span",{class:v.kind?`is-${v.kind}`:void 0,children:[b>0?" · ":"",v.text]},v.text,!0,void 0,this))},void 0,!1,void 0,this),r("span",{class:"context-chip-narrow",children:[a.length+c.length," in context"]},void 0,!0,void 0,this),m&&r("span",{class:"context-chip-cost","data-testid":"token-cost",children:m},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e&&r("div",{class:"context-panel",role:"dialog","aria-label":"In the agent's context",children:[r("div",{class:"context-panel-head",children:[r("span",{class:"context-panel-title",children:"In the agent’s context"},void 0,!1,void 0,this),m&&r("span",{class:"context-panel-mono",children:m},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u?r("p",{class:"context-panel-cap",children:"Nothing is pinned. Pin a card or a board and the agent gets it first; it can still find and pull anything else on the board."},void 0,!1,void 0,this):r(be,{children:[r("p",{class:"context-panel-cap",children:["What the canvas sends the agent costs ",m||"a few tokens",".",h?.contextUsage?` ${h.label}’s whole context holds ${yg(h.contextUsage.used)} tokens.`:""]},void 0,!0,void 0,this),r("div",{class:"context-panel-section",children:[r("span",{children:["Cards on this board · ",a.length]},void 0,!0,void 0,this),a.length>0&&r("button",{type:"button",class:"context-panel-link",onClick:()=>lm(),children:"Clear all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("ul",{class:"context-panel-list",children:a.map((v)=>{let b=H.value.get(v),x=Od(v,b?.contentRevision??0),C=x.kind==="read"&&Dd(v,b?.linksRevision??0),y=hi.value[v]?.pinnedBy.actor==="agent";return r("li",{class:"context-panel-row",children:[r("span",{class:"context-panel-pin",children:[r(uo,{size:9},void 0,!1,void 0,this),y&&r("span",{class:"context-chip-agent-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"context-panel-name",children:vg(v)},void 0,!1,void 0,this),C?r("span",{class:"context-tag is-links",children:[r("svg",{viewBox:"0 0 24 24",width:"10",height:"10","aria-hidden":"true",children:r("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"links changed"]},void 0,!0,void 0,this):r(cT,{state:x.kind,at:x.kind==="not-read"?null:x.at},void 0,!1,void 0,this),r("button",{type:"button",class:"context-panel-x","aria-label":`Unpin ${vg(v)}`,onClick:()=>lo(v),children:"×"},void 0,!1,void 0,this)]},v,!0,void 0,this)})},void 0,!1,void 0,this),l.length>0&&r(be,{children:[r("div",{class:"context-panel-section",children:[r("span",{children:["Near · ",l.length]},void 0,!0,void 0,this),r("span",{class:"context-panel-cap-inline",children:["derived · ",r("span",{class:"context-panel-wide",children:"sent as "},void 0,!1,void 0,this),"title + summary"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("ul",{class:"context-panel-list",children:l.map(([v,b])=>r("li",{class:"context-panel-row is-near",children:[r("span",{class:"context-panel-near-ring","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"context-panel-name is-soft",children:vg(v)},void 0,!1,void 0,this),r("span",{class:"context-panel-cap-inline",children:["near ",b[0]?.pinTitle]},void 0,!0,void 0,this),r("button",{type:"button",class:"context-panel-promote",onClick:()=>lo(v),children:"Pin"},void 0,!1,void 0,this)]},v,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c.length>0&&r(be,{children:[r("div",{class:"context-panel-section",children:[r("span",{children:["Boards · ",c.length]},void 0,!0,void 0,this),r("span",{class:"context-panel-cap-inline",children:"sent as a map"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("ul",{class:"context-panel-list",children:c.map((v)=>{let b=ep.value.get(v.id);return r("li",{class:"context-panel-row",children:[r("svg",{class:"context-panel-board",viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",children:r("path",{d:"M4 4h16v16H4zM9 9h6v6H9z"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"context-panel-name",children:v.name},void 0,!1,void 0,this),r(cT,{state:b?"read":"not-read",at:b?.lastReadAt??null},void 0,!1,void 0,this),r("span",{class:"context-panel-cap-inline",children:"map"},void 0,!1,void 0,this),r("button",{type:"button",class:"context-panel-x","aria-label":`Unpin ${v.name}`,onClick:()=>void $s(v.id,!1),children:"×"},void 0,!1,void 0,this)]},v.id,!0,void 0,this)})},void 0,!1,void 0,this),r("p",{class:"context-panel-cap",children:"A pinned board travels as a map: its folder, README summary, each pinned card’s title and summary, and its links and backlinks. The agent pulls a card or the whole board in full when it decides it needs to."},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 cT({state:e,at:t}){let[n,o,i]=e==="changed"?["is-changed",gi.warn,"changed"]:e==="read"&&t?["is-read",gi.eye,`read ${hg(t)}`]:["is-not-read",gi.eyeOff,"not read yet"];return r("span",{class:`context-tag ${n}`,children:[r("svg",{viewBox:"0 0 24 24",width:"11",height:"11","aria-hidden":"true",children:r("path",{d:o},void 0,!1,void 0,this)},void 0,!1,void 0,this),i]},void 0,!0,void 0,this)}var xg=Ve(()=>{if(ao.value==="disconnected")return"reconnecting";if(ao.value==="connected"&&!cn.value&&Zi.value>1)return"resyncing";return null});function pT(){let e=xg.value;if(!e)return null;if(e==="reconnecting"){let t=Wi.value,n=qi.value;return r("div",{class:"connection-banner is-reconnecting",role:"status","data-testid":"connection-banner",children:[r("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"↻"},void 0,!1,void 0,this),r("span",{class:"connection-banner-text",children:[r("b",{children:"Reconnecting…"},void 0,!1,void 0,this)," live updates are paused; retry refused saves after reconnect. The board may be stale."]},void 0,!0,void 0,this),r("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 r("div",{class:"connection-banner is-resyncing",role:"status","data-testid":"connection-banner",children:[r("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"⟳"},void 0,!1,void 0,this),r("span",{class:"connection-banner-text",children:[r("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),r("span",{class:"connection-banner-progress","aria-hidden":"true",children:r("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 lL={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 Eo(e){if(e.x!==void 0&&e.y!==void 0)return No(e);let t=lL[e.type]??{width:360,height:200},n=e.width??t.width,o=e.height??t.height,i=Zr(),s=Te.value,a=await No({...e,width:n,height:o,x:Math.round((i.x-s.x)/s.scale-n/2),y:Math.round((i.y-s.y)/s.scale-o/2)});if(a.ok&&a.id)$t(a.id);return a}var tp=!1,fT=!1,ss=null,va=null;function wg(){return tp}function np(){tp=!1,fT=!0,mT()}function mT(){if(ss&&va)ss.removeEventListener("change",va);ss=null,va=null}function cL(){if(typeof window>"u"||!window.location)return null;let e=new URLSearchParams(window.location.search).get("theme");if(e==="auto")return"auto";return El(e)?e:null}function hT(e){if(fT)return;let t=cL();if(!t)return;if(mT(),tp=!0,t!=="auto"){e(t);return}ss=window.matchMedia("(prefers-color-scheme: light)"),va=()=>{if(tp&&ss)e(ss.matches?"daylight":"harbor")},va(),ss.addEventListener("change",va)}var uL='a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), summary, [tabindex]:not([tabindex="-1"])';function bn(e,t,n={}){let o=D(n.onEscape);o.current=n.onEscape,Me(()=>{if(!t)return;let i=e.current;if(!i)return;let s=document.activeElement,a=n.restoreTo,l=()=>Array.from(i.querySelectorAll(uL)).filter((p)=>{if(p.closest("[hidden], [inert]"))return!1;for(let f=p;f&&f!==i;f=f.parentElement){if(getComputedStyle(f).display==="none"||getComputedStyle(f).visibility==="hidden")return!1;if(f.matches("details:not([open])")&&!f.querySelector(":scope > summary")?.contains(p))return!1}return!0}),c=n.initial?.current??l()[0];if(c&&!i.contains(document.activeElement))c.focus();let u=(p)=>{if(p.key!=="Tab")return;let f=l();if(f.length===0)return;let m=f[0],h=f[f.length-1],g=document.activeElement;if(p.shiftKey&&(g===m||!i.contains(g)))p.preventDefault(),h.focus();else if(!p.shiftKey&&g===h)p.preventDefault(),m.focus()},d=(p)=>{if(p.key!=="Escape"||!o.current||i.contains(p.target))return;p.preventDefault(),p.stopPropagation(),o.current()};return i.addEventListener("keydown",u),window.addEventListener("keydown",d,!0),()=>{if(i.removeEventListener("keydown",u),window.removeEventListener("keydown",d,!0),a)requestAnimationFrame(()=>a()?.focus());else if(s&&document.contains(s)&&s!==document.body)s.focus()}},[e,t,n.initial,n.restoreTo])}function dL(e,t){let n=e.toLowerCase(),o=t.toLowerCase(),i=[],s=0,a=0,l=-1;for(let c=0;c<o.length&&s<n.length;c++)if(o[c]===n[s]){if(i.push(c),a+=l===c-1?10:1,c===0||o[c-1]===" "||o[c-1]==="-"||o[c-1]==="_")a+=5;l=c,s++}return{match:s===n.length,score:a,indices:i}}function pL(e,t){if(t.length===0)return e;let n=[],o=0;for(let i of t){if(i>o)n.push(e.slice(o,i));n.push(r("mark",{children:e[i]},i,!1,void 0,this)),o=i+1}if(o<e.length)n.push(e.slice(o));return n}var kg={md:"markdown",app:"mcp-app",web:"webpage",ui:"json-render",chart:"graph",ctx:"context",log:"ledger"};function fL(e){let t=e.toLowerCase().trim();if(t.startsWith("type:")){let n=t.slice(5).trim(),i=Object.keys(an).find((a)=>a.startsWith(n));if(i)return{typeFilter:i,remaining:""};let s=kg[n];if(s)return{typeFilter:s,remaining:""}}if(kg[t])return{typeFilter:kg[t],remaining:""};return{typeFilter:null,remaining:e}}function gT({onClose:e,onToggleMinimap:t}){let[n,o]=E(""),[i,s]=E(0),[a,l]=E([]),[c,u]=E("idle"),d=D(null),p=D(null),f=D(null);bn(f,!0,{initial:d}),q(()=>{setTimeout(()=>d.current?.focus(),30)},[]),q(()=>{let _=n.trim();if(_.length<2){l([]),u("idle");return}let I=!0;u("loading");let w=window.setTimeout(()=>void de("paletteLibrarySearch",`/api/canvas/search?q=${encodeURIComponent(_)}&scope=library&limit=12`,null).then((P)=>{if(!I)return;if(!P){l([]),u("error");return}l(P.results??[]),u("idle")}),150);return()=>{I=!1,window.clearTimeout(w)}},[n]);let m=oe(()=>{let _=[];for(let w of H.value.values()){let P=w.data.title||an[w.type],L=w.data.content||w.data.path||"",N=w.type==="group"&&Array.isArray(w.data.children)?w.data.children.length:0;_.push({id:`node:${w.id}`,kind:"node",label:P,description:w.type==="group"?`group · ${N} node${N===1?"":"s"}`:L.length>60?`${an[w.type].toLowerCase()} · ${L.slice(0,60)}…`:L?`${an[w.type].toLowerCase()} · ${L}`:an[w.type].toLowerCase(),icon:Bo(w.type),nodeType:w.type,action:()=>{$t(w.id),e()}})}let I=[{label:"New markdown note",shortcut:"M",icon:ni,iconTone:"accent",action:()=>{Eo({type:"markdown",title:"New note",width:520,height:360}),e()}},{label:"Link to board…",icon:Bo("board"),iconTone:"accent",action:()=>{window.dispatchEvent(new CustomEvent("pmx-open-board-link")),e()}},...!xt.value||_o.value?[]:[{label:"Start agent session",icon:js,iconTone:"purple",action:()=>{vi(),e()}}],{label:"Fit view",shortcut:"F",icon:Pu,iconTone:"muted",action:()=>{Fs(Jt().width,Jt().height),e()}},{label:"Auto-arrange (grid)",icon:Tr,iconTone:"muted",action:()=>{Tu(),e()}},{label:"Auto-arrange (graph-aware)",icon:Tr,iconTone:"muted",action:()=>{Iu(),e()}},{label:"Toggle minimap",icon:hS,iconTone:"muted",action:()=>{t(),e()}},{label:"Toggle theme (Harbor/Daylight)",icon:gS,iconTone:"muted",action:()=>{let w=ea(Qt.value)==="dark"?"daylight":"harbor";np(),document.documentElement.setAttribute("data-theme",w),aa(),Qt.value=w,hu(w),e()}}];for(let w of I)_.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:g}=fL(n),v=m(),b;if(!n.trim())b=v.map((_)=>({..._,score:0,indices:[]}));else{b=[];for(let _ of v){if(h){if(_.kind!=="node"||_.nodeType!==h)continue;if(!g){b.push({..._,score:0,indices:[]});continue}}let I=dL(g||n,_.label);if(I.match)b.push({..._,score:I.score,indices:I.indices})}b.sort((_,I)=>I.score-_.score)}for(let _ of a)b.push({id:`library:${_.boardId}:${_.cardId}`,kind:"library",label:_.title||_.boardTitle,description:`${_.boardTitle} · ${_.snippet}`,icon:Bo("board"),score:0,indices:[],action:()=>{(async()=>{await zt(_),e()})()}});b=[...b.filter((_)=>_.kind==="action"),...b.filter((_)=>_.kind==="node"),...b.filter((_)=>_.kind==="library")];let x=b.findIndex((_)=>_.kind==="node"),C=b.findIndex((_)=>_.kind==="library");q(()=>{if(!n.trim()){wr.value=null;return}let _=new Set;for(let I of b)if(I.kind==="node")_.add(I.id.slice(5));wr.value=_.size>0?_:null},[n,b]),q(()=>()=>{wr.value=null},[]);let y=Math.min(i,Math.max(0,b.length-1)),k=oe((_)=>{if(_.key==="ArrowDown")_.preventDefault(),s((I)=>Math.min(I+1,b.length-1));else if(_.key==="ArrowUp")_.preventDefault(),s((I)=>Math.max(I-1,0));else if(_.key==="Enter"){if(_.preventDefault(),b[y])b[y].action()}else if(_.key==="Escape")_.preventDefault(),_.stopPropagation(),e()},[b,y,e]);return q(()=>{let _=p.current;if(!_)return;_.children[y]?.scrollIntoView({block:"nearest"})},[y]),q(()=>{s(0)},[n]),r("div",{class:"command-palette-backdrop",onMouseDown:e,children:r("div",{ref:f,class:"command-palette",role:"dialog","aria-modal":"true","aria-label":"Search and commands",onMouseDown:(_)=>_.stopPropagation(),children:[r("div",{class:"command-palette-search",children:[r("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:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("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),r("input",{ref:d,type:"text",class:"command-palette-input",value:n,onInput:(_)=>o(_.target.value),onKeyDown:k,placeholder:"Search nodes, run actions, jump to…","aria-label":"Search nodes, run actions, jump to"},void 0,!1,void 0,this),r("kbd",{class:"command-palette-esc",children:"esc"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"command-palette-results",ref:p,children:[c==="loading"&&r("div",{class:"command-palette-empty",role:"status",children:"Searching all boards…"},void 0,!1,void 0,this),c==="error"&&r("div",{class:"command-palette-empty",role:"alert",children:"Library search is unavailable."},void 0,!1,void 0,this),b.length===0&&c!=="loading"&&r("div",{class:"command-palette-empty",children:"No matching nodes, boards, or actions"},void 0,!1,void 0,this),b.map((_,I)=>{let w=_.icon,P=I===0&&_.kind==="action"?"Actions":I===x?"Jump to":I===C?"Across boards":null;return r("div",{class:"command-palette-row",children:[P&&r("div",{class:"command-palette-group",children:P},void 0,!1,void 0,this),r("button",{type:"button",class:`command-palette-item${I===y?" selected":""}`,onMouseEnter:()=>s(I),onClick:()=>_.action(),children:[r("span",{class:`command-palette-icon tone-${_.iconTone??"kind"}`,"aria-hidden":"true",children:r(w,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"command-palette-label",children:[_.indices.length>0?pL(_.label,_.indices):_.label,_.description&&r("span",{class:"command-palette-desc",children:[" — ",_.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_.shortcut&&r("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),r("div",{class:"command-palette-hint",children:[r("span",{children:"↑↓ navigate"},void 0,!1,void 0,this),r("span",{children:"↵ open"},void 0,!1,void 0,this),r("span",{children:"esc close"},void 0,!1,void 0,this),r("span",{children:"type: filter"},void 0,!1,void 0,this),r("span",{class:"command-palette-hint-spacer"},void 0,!1,void 0,this),r("span",{children:Ft("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 yT({onClose:e,sourceNodeId:t,wikiRef:n}){let o=D(null),i=D(null),s=D(se.value).current,a=D(t?H.value.get(t):void 0).current,[l,c]=E(null),[u,d]=E(""),[p,f]=E(""),[m,h]=E(!1);bn(o,!0,{initial:i}),q(()=>{let y=!1;if(t&&!n)de("linkCardChoices","/api/canvas/memory-graph",null).then((k)=>{if(!y){if(c(k),!k)f("Could not load cards. Close and retry.")}});return()=>{y=!0}},[t,n]);let g=Ge.value.filter((y)=>y.id!==s&&y.name.toLowerCase().includes(u.trim().toLowerCase())),v=(l?.nodes??[]).filter((y)=>y.kind==="card"&&y.boardId!==s&&`${y.title} ${Ge.value.find((k)=>k.id===y.boardId)?.name??""}`.toLowerCase().includes(u.trim().toLowerCase())),b=async()=>{if(!n||!a||se.value!==s)return f("The source board changed. Reopen it before creating the link.");h(!0);let y=await de("createWikiBoard","/api/canvas/boards",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,expectedBoardId:s})});if(!y?.board)return h(!1),f("Could not create the board.");let k=await ln(a.id,{content:typeof a.data.content==="string"?a.data.content:"",expectedBoardId:s,expectedContentRevision:a.contentRevision??0});if(await il(),h(!1),!k.ok)return f("Board created, but the source changed. Save its Markdown again to resolve the link.");e(),await zt({boardId:y.board.id})},x=async(y,k)=>{if(!t)return;h(!0);let _=await yr(t,k,"references",void 0,{toBoardId:y,expectedBoardId:s});if(h(!1),!_.ok)return f("Could not add the connection. Check the source board and target card, then retry.");e()},C=async(y)=>{let k=Ge.value.find((P)=>P.id===y);if(!k)return f("That board is no longer available.");let _=Zr(),I=Te.value;if(!(await de("createBoardLink","/api/canvas/node",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedBoardId:s,type:"board",title:k.name,x:Math.round((_.x-I.x)/I.scale-180),y:Math.round((_.y-I.y)/I.scale-100),width:360,height:200,data:{boardId:y}})})).ok)return f("Could not create the board link.");e()};return r("div",{class:"text-prompt-backdrop",onMouseDown:e,children:r("div",{ref:o,class:"text-prompt board-link-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-link-title",onMouseDown:(y)=>y.stopPropagation(),children:[r("h2",{id:"board-link-title",children:n?"Create unresolved board":t?"Connect to a card on another board":"Link to a board"},void 0,!1,void 0,this),n?r("p",{children:["Create “",n,"” and save this link to its board ID?"]},void 0,!0,void 0,this):r("input",{ref:i,type:"search",class:"text-prompt-input","aria-label":t?"Find a card to connect":"Find a board to link",placeholder:t?"Find a board or card…":"Find a board…",value:u,onInput:(y)=>d(y.currentTarget.value)},void 0,!1,void 0,this),p&&r("div",{role:"alert",class:"board-copy-error",children:p},void 0,!1,void 0,this),!n&&r("ul",{class:"board-link-results",children:[t?v.map((y)=>r("li",{children:r("button",{type:"button",disabled:m,onClick:()=>void x(y.boardId,y.cardId),children:[r("span",{children:y.title},void 0,!1,void 0,this),r("small",{children:Ge.value.find((k)=>k.id===y.boardId)?.name??y.boardId},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},y.key,!1,void 0,this)):g.map((y)=>r("li",{children:r("button",{type:"button",onClick:()=>void C(y.id),children:[r("span",{children:y.name},void 0,!1,void 0,this),r("small",{children:[y.nodeCount," nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},y.id,!1,void 0,this)),(t?v.length:g.length)===0&&r("li",{class:"board-copy-status",children:Ge.value.length<=1?"Create another board first, then link it here.":t&&!l?"Loading cards…":"No matches. Try another search."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"text-prompt-actions",children:[n&&r("button",{type:"button",disabled:m,onClick:()=>void b(),children:m?"Creating…":"Create board"},void 0,!1,void 0,this),r("button",{type:"button",onClick:e,children:"Cancel"},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 ba={decayType:"reality",rate:"medium",cadenceDays:90,triggers:[],revalidationMethod:""};function Yl({value:e,onChange:t}){return r("div",{class:"lifecycle-fields",children:[r("div",{class:"knowledge-field",children:[r("span",{children:"Why review?"},void 0,!1,void 0,this),r(Mr,{label:"Why review?",value:e.decayType,onChange:(n)=>t({...e,decayType:n}),options:[{value:"reality",label:"Reality · facts change"},{value:"decision",label:"Decision · superseded"},{value:"dependency",label:"Dependency · prerequisites change"},{value:"relevance",label:"Relevance · task changes"}]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"knowledge-field",children:[r("span",{children:"Review frequency"},void 0,!1,void 0,this),r(Mr,{label:"Review frequency",value:e.rate,onChange:(n)=>t({...e,rate:n}),options:[{value:"fast",label:"Fast · at use"},{value:"medium",label:"Medium · on a cadence"},{value:"slow",label:"Slow · on resume"},{value:"durable",label:"Durable · no passive expiry"}]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.rate==="medium"&&r("label",{children:["Cadence in days",r("input",{type:"number",min:"1",max:"36500",required:!0,value:e.cadenceDays??"",onInput:(n)=>t({...e,cadenceDays:n.currentTarget.value?Number(n.currentTarget.value):void 0})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("details",{class:"lifecycle-triggers",children:[r("summary",{children:"Additional review triggers"},void 0,!1,void 0,this),r("label",{children:["Also review when · one trigger per line",r("textarea",{value:e.triggers.join(`
385
+ </script>`}function L_(){return"<style data-pmx-canvas-ext-app-base>html, body { background: transparent !important; }</style>"}function O_(e,t){if(!t)return e;let n=/<head\b[^>]*>/i.exec(e);if(n?.index!==void 0){let i=n.index+n[0].length;return`${e.slice(0,i)}${t}${e.slice(i)}`}let o=/<body\b[^>]*>/i.exec(e);if(o?.index!==void 0){let i=o.index+o[0].length;return`${e.slice(0,i)}${t}${e.slice(i)}`}return`${t}${e}`}function aa(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 Wh(e,t){let n=e?.getBoundingClientRect();return{width:aa(e?.clientWidth??0,aa(n?.width??0,t.width)),height:aa(e?.clientHeight??0,aa(n?.height??0,t.height))}}function Vz(e,t){return typeof e==="number"&&Number.isFinite(e)&&e>0&&!t}function Xz(e,t){return Math.max(aa(e,1),aa(t,1))}function B_({node:e,expanded:t=!1}){let n=D(null),o=D(null),i=D(null),s=D(null),a=D({}),l=D(void 0),c=D(!1),u=D(void 0),d=D(null),p=D(!1),f=D(null),m=D(0),h=D([]),g=D(""),v=D(!1),b=D(!1),x=D([]),C=D(!1),y=D(!1),k=D(!1),_=D(!1),[I,w]=E("loading"),[P,L]=E(null),[N,Y]=E(0),[B,J]=E(!1),[X,V]=E(!1),[ee,he]=E(()=>t||typeof navigator>"u"||typeof window>"u"||!es(navigator.userAgent)),A=e.data.html,te=e.data.serverName,M=e.data.appSessionId,O=e.data.toolInput??{},Pe=e.data.toolResult,Fe=e.data.toolName??"ext-app",De=e.data.toolDefinition,Ae=e.data.toolCallId,ve=typeof Ae==="string"||typeof Ae==="number"?Ae:void 0,z=e.data.resourceMeta,re=e.data.sessionStatus,Ne=e.data.sessionError,ke=e.size.height,ae=e.id,Se=Zz(e,N),de=qz(null),xe=e.data.axCapabilities?.enabled===!0&&typeof A==="string"&&A.length>0,qe=Ke(()=>`ax-${crypto.randomUUID()}`,[]),W=xe?Gz(qe,ae):"",ye=typeof A==="string"&&A.length>0?Kz(qe,ae):"",He=R_(O_(A??"",L_()+ye+W),de);q(()=>{function le(we){if(we.source!==n.current?.contentWindow)return;let ge=we.data;if(!ge||ge.source!==nd||ge.token!==qe||ge.nodeId!==ae)return;if(b.current=!0,ge.kind==="paint-tick"){let Le=ge,Rt={content:Le.content===!0,detail:typeof Le.detail==="string"?Le.detail:""};for(let pt of h.current.splice(0))pt(Rt)}}return window.addEventListener("message",le),()=>window.removeEventListener("message",le)},[qe,ae]),q(()=>{if(ee)return;z_({remount:()=>{if(_.current)return!1;return vn(ae,"mount-slot"),he(!0),!0},awaitBoot:()=>new Promise((le)=>{let we=window.setTimeout(ge,P_);function ge(){window.clearTimeout(we),le()}x.current.push(ge)})})},[]),sa({enabled:xe,token:qe,nodeId:ae,sourceSurface:"mcp-app",iframeRef:n});let R=3,ne=(le)=>{if(m.current>=R)return vn(ae,`remount-cap-hit (${le})`),!1;if(C.current)return!0;return m.current+=1,C.current=!0,vn(ae,`remount-queued #${m.current} (${le})`),z_({remount:()=>{if(C.current=!1,_.current||!t&&Bt.value===ae)return vn(ae,"remount-skipped"),J(!1),!1;return y.current=typeof document<"u"&&document.visibilityState==="hidden",vn(ae,`remount-run #${m.current}`),w("loading"),Y((we)=>we+1),!0},awaitBoot:()=>new Promise((we)=>{let ge=window.setTimeout(Le,P_);function Le(){window.clearTimeout(ge),we()}x.current.push(Le)})}),!0},Ce=1500,Te=()=>new Promise((le)=>{let we=n.current?.contentWindow;if(!we||_.current){le("timeout");return}let ge=!1,Le=window.setTimeout(()=>{if(ge)return;ge=!0,le("timeout")},Ce);h.current.push((Rt)=>{if(ge)return;ge=!0,window.clearTimeout(Le),g.current=Rt.detail,le(Rt.content?"content-verified":"tick-no-content")}),we.postMessage({source:lh,token:qe},"*")}),fe=async(le)=>{let we=Date.now()+le;while(Date.now()<we&&!_.current){if(await Te()==="content-verified")return!0;await new Promise((ge)=>window.setTimeout(ge,400))}return!1},it=()=>new Promise((le)=>{let we=n.current;if(!we){le();return}let ge=we.style.width,Le=we.style.height;we.style.width="140%",we.style.height="140%",requestAnimationFrame(()=>{requestAnimationFrame(()=>{we.style.width=ge,we.style.height=Le,vn(ae,"soft-expand-cycle"),le()})})}),Ht=600,Ye=()=>{if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;let le=n.current;if(!le||_.current)return;if(!Uz({userAgent:navigator.userAgent,visibilityState:document.visibilityState,rect:le.getBoundingClientRect(),viewport:{width:window.innerWidth,height:window.innerHeight},alreadyRearmed:k.current}))return;k.current=!0,window.setTimeout(()=>{if(_.current||document.visibilityState==="visible")return;m.current=0,V(!1),y.current=!1,vn(ae,"assume-visible-rearm"),ne("assume-visible")},Ht)},Lt=(le="")=>{let we=g.current?` [${g.current}]`:"";return typeof document<"u"&&document.visibilityState==="hidden"?`paint-ok (content-verified)${we}${le} (host hidden)`:`paint-ok (content-verified)${we}${le}`},F=async()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!es(navigator.userAgent))return;J(!0);let le=await Te();if(le==="content-verified"){vn(ae,Lt()),J(!1),Ye();return}if(vn(ae,le==="tick-no-content"?`paint-fail (tick without content: ${g.current||"unknown"})`:"paint-fail (no tick)"),await it(),le=await Te(),le==="content-verified"){vn(ae,Lt(" (after soft-expand)")),J(!1),Ye();return}if(_.current)return;if(le==="tick-no-content"&&await fe(3000)){vn(ae,Lt(" (after content wait)")),J(!1),Ye();return}if(_.current)return;if(!ne("paint-fail"))vn(ae,"recovery-exhausted"),J(!1),V(!0),Ye()};q(()=>{if(t)return;if(typeof document>"u"||typeof navigator>"u"||typeof window>"u")return;if(!es(navigator.userAgent))return;function le(){if(document.visibilityState!=="visible")return;if(!y.current||_.current)return;y.current=!1,m.current=0,V(!1),vn(ae,"visible-again-rearm"),ne("visible-after-hidden-boot")}return document.addEventListener("visibilitychange",le),()=>document.removeEventListener("visibilitychange",le)},[t,ae]);let Ie=6000;q(()=>{if(typeof navigator>"u"||typeof window>"u")return;if(!es(navigator.userAgent))return;if(!He.ready||!ee)return;let le=window.setTimeout(()=>{if(v.current||b.current||_.current)return;ne("boot-watchdog")},Ie);return()=>window.clearTimeout(le)},[Se,He.ready,t,ee]),q(()=>()=>{_.current=!0;for(let le of x.current.splice(0))le();for(let le of h.current.splice(0))le({content:!1,detail:"unmounted"})},[]);let S=(le)=>ta(le),K=t||Bt.value===ae;a.current=O,l.current=Pe;let ue=re==="error"&&typeof A==="string"&&A.length>0,$e=re==="error"?ue?`Live session unavailable — showing saved content. Reopen the app to restore interactivity.${Ne?` (${Ne})`:""}`:Ne??"Saved app session is unavailable. Reopen the app to restore interactivity.":"Reconnecting saved app session...",je=(le)=>{let we=l.current;if(!le||!p.current||!we)return null;if(u.current===we)return null;if(u.current&&E_(u.current,we))return u.current=we,null;if(d.current)return d.current;let ge=le.sendToolResult(we).then(()=>{u.current=we,c.current=!0,w("done")}).catch((Le)=>{let Rt=Le instanceof Error?Le.message:String(Le);throw L(`Tool result delivery failed: ${Rt}`),Le}).finally(()=>{d.current=null});return d.current=ge,ge};if(q(()=>{if(!A||!He.ready||!ee)return;let le=n.current;if(!le)return;let we=!1,ge=null,Le=null,Rt=null,pt=null,pn=null;c.current=!1,u.current=void 0,d.current=null,p.current=!1,v.current=!1,b.current=!1;let on=()=>{if(!ge)return;clearTimeout(ge),ge=null};return(async()=>{if(!A)return;let Pn=le.contentWindow;if(!Pn)throw Error("Ext-app iframe window is unavailable");let xn=(ot=Bt.value===ae?"fullscreen":"inline")=>({theme:S(Qt.value),platform:"web",containerDimensions:Wh(le,{width:e.size.width,height:ke}),displayMode:ot,locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,...De?{toolInfo:{id:ve,tool:De}}:{}}),fn=()=>{if(pt!==null)return;pt=requestAnimationFrame(()=>{if(pt=null,we||!p.current)return;ft.setHostContext?.(xn())})},cr=()=>{if(pn!==null)return;pn=requestAnimationFrame(()=>{pn=requestAnimationFrame(()=>{if(pn=null,we||!p.current)return;ft.sendHostContextChange?.(xn())})})},ms=()=>{if(!es(navigator.userAgent))return;if(Le)clearTimeout(Le);Le=setTimeout(()=>{if(Le=null,we)return;F()},D_+200)},ft=new Hh(null,{name:"PMX Canvas",version:"1.0.0"},{openLinks:{},serverTools:{listChanged:!1},serverResources:{listChanged:!1},logging:{},updateModelContext:{text:{},structuredContent:{}}},{hostContext:xn(K?"fullscreen":"inline")});ft.onsizechange=async({height:ot})=>{let Ot=H.value.get(ae);if(!Ot||Ot.data.userResized===!0)return{};if(Vz(ot,Bt.value===ae)){let Hn=Wh(le.parentElement??le,{width:e.size.width,height:ke}),Lr=Xz(ot,Hn.height);le.style.height=`${Lr}px`;let ur=Ot.size,cc=Math.max(ur.height,Lr+Js);if(Math.abs(cc-ur.height)>8){if(Tu(ae,{width:ur.width,height:cc}),s.current!==null)window.clearTimeout(s.current);s.current=window.setTimeout(()=>{s.current=null;let uc=H.value.get(ae);if(uc&&uc.data.userResized!==!0)dn({recordHistory:!1})},0)}}return{}},ft.onopenlink=async({url:ot})=>(window.open(ot,"_blank","noopener"),{}),ft.onsandboxready=async()=>{await ft.sendSandboxResourceReady({html:O_(A,L_()),sandbox:ch,...z?.csp?{csp:z.csp}:{},...z?.permissions?{permissions:z.permissions}:{}})},ft.onrequestdisplaymode=async({mode:ot})=>{let{nextMode:Ot,shouldExpand:Hn,shouldCollapse:Lr}=Wz(ot,K);if(Hn)xo(ae);else if(Lr)Cr();return{mode:Ot}},ft.oncalltool=async(ot)=>{if(!M)throw Error($e);try{let Ot=await Qi("/api/ext-app/call-tool",{sessionId:M,nodeId:ae,serverName:te,toolName:ot.name,arguments:ot.arguments??{}});return L(null),Ot}catch(Ot){let Hn=Ot instanceof Error?Ot.message:String(Ot);throw L(`Tool call failed: ${Hn}`),Ot}},ft.setRequestHandler(kd,async()=>{if(!M)return{tools:[]};return Qi("/api/ext-app/list-tools",{sessionId:M})}),ft.onlistresources=async()=>M?Qi("/api/ext-app/list-resources",{sessionId:M}):{resources:[]},ft.onlistresourcetemplates=async()=>M?Qi("/api/ext-app/list-resource-templates",{sessionId:M}):{resourceTemplates:[]},ft.onreadresource=async(ot)=>{if(!M)throw Error($e);return Qi("/api/ext-app/read-resource",{sessionId:M,uri:ot.uri})},ft.onlistprompts=async()=>M?Qi("/api/ext-app/list-prompts",{sessionId:M}):{prompts:[]},ft.onupdatemodelcontext=async(ot)=>{if(!M)return{};return await Qi("/api/ext-app/model-context",{nodeId:ae,...Array.isArray(ot.content)?{content:ot.content}:{},...ot.structuredContent&&typeof ot.structuredContent==="object"?{structuredContent:ot.structuredContent}:{}}),{}};let Ta=new Fh(Pn,Pn);if(ft.oninitialized=()=>{if(we)return;on(),p.current=!0,v.current=!0,vn(ae,"initialized"),w("ready"),L(null),Promise.resolve(ft.sendHostContextChange(xn(K?"fullscreen":"inline"))).then(()=>$_(ft,a.current,void 0)).then(()=>je(ft)).then(()=>{let ot=()=>{for(let Ot of x.current.splice(0))Ot()};if(typeof navigator<"u"&&es(navigator.userAgent))fe(4000).then((Ot)=>{vn(ae,Ot?"settled (content-verified)":`settled (content-timeout${g.current?`: ${g.current}`:""})`),ot()});else vn(ae,"settled"),ot();cr(),ms()}).catch((ot)=>{let Ot=ot instanceof Error?ot.message:String(ot);L(`Bridge bootstrap failed: ${Ot}`)})},ge=setTimeout(()=>{if(we||p.current)return;let ot=l.current,Ot=xn(K?"fullscreen":"inline");p.current=!0,ft.setHostContext?.(Ot),Promise.resolve(ft.sendHostContextChange(Ot)).then(()=>$_(ft,a.current,ot)).then(()=>{if(c.current=Boolean(ot),ot)u.current=ot;if(w(ot?"done":"ready"),L(null),cr(),ms(),b.current){vn(ae,"settled (fallback)");for(let Hn of x.current.splice(0))Hn()}}).catch((Hn)=>{let Lr=Hn instanceof Error?Hn.message:String(Hn);L(`Bridge bootstrap fallback failed: ${Lr}`)})},1200),await ft.connect(Ta),we){on(),await Ta.close();return}if(o.current=ft,i.current=Ta,Rt=new ResizeObserver(fn),Rt.observe(le),le.parentElement)Rt.observe(le.parentElement);let Ia=!0;f.current=Qt.subscribe((ot)=>{if(Ia){Ia=!1;return}if(we)return;ft.setHostContext?.({...xn(),theme:S(ot)}),ft.sendHostContextChange?.(xn())}),je(ft)})().catch((Pn)=>{on(),console.error("[ext-app] Bridge init failed:",Pn),L(Pn?.message??"Bridge initialization failed")}),()=>{if(we=!0,on(),Le)clearTimeout(Le),Le=null;if(Rt?.disconnect(),Rt=null,pt!==null)cancelAnimationFrame(pt),pt=null;if(pn!==null)cancelAnimationFrame(pn),pn=null;if(p.current=!1,d.current=null,f.current?.(),f.current=null,s.current!==null)window.clearTimeout(s.current),s.current=null;if(o.current=null,i.current)i.current.close().catch((Pn)=>{console.error("[ext-app] transport close failed:",Pn)}),i.current=null}},[Se,He.key,ee]),q(()=>{if(Pe&&o.current&&(I==="ready"||I==="done"))je(o.current)},[Pe,I]),q(()=>{let le=o.current;if(n.current)n.current.style.height="100%";if(!le||!p.current)return;let we=null,ge=null;return we=requestAnimationFrame(()=>{we=null,ge=requestAnimationFrame(()=>{if(ge=null,!p.current)return;let Le={theme:S(Qt.value),platform:"web",containerDimensions:Wh(n.current,{width:e.size.width,height:ke}),displayMode:K?"fullscreen":"inline",locale:navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone};le.setHostContext?.(Le),le.sendHostContextChange?.(Le)})}),()=>{if(we!==null)cancelAnimationFrame(we);if(ge!==null)cancelAnimationFrame(ge)}},[K,ke]),!A)return r("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--c-muted)",fontSize:"13px",flexDirection:"column",gap:"8px"},children:[r("div",{style:{opacity:0.6},children:["Loading ",Fe," viewer..."]},void 0,!0,void 0,this),r("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),r("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{style:{flex:1,width:"100%",height:"100%",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[re&&re!=="ready"&&r("div",{style:{padding:"6px 10px",fontSize:"11px",background:re==="error"&&!ue?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 10%, transparent)",color:re==="error"&&!ue?"var(--c-danger)":"var(--c-warn)",borderBottom:`1px solid ${re==="error"&&!ue?"color-mix(in srgb, var(--c-danger) 12%, transparent)":"color-mix(in srgb, var(--c-warn) 15%, transparent)"}`},children:$e},void 0,!1,void 0,this),P&&r("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:[r("span",{children:"⚠"},void 0,!1,void 0,this),r("span",{style:{flex:1},children:P},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>{L(null),w("loading"),Y((le)=>le+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),r("button",{type:"button",onClick:()=>L(null),"aria-label":"Dismiss error",style:{background:"none",border:"none",color:"var(--c-danger)",cursor:"pointer",fontSize:"13px",padding:"0 2px"},children:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{style:{flex:1,position:"relative",display:"flex",minHeight:0,height:"100%"},children:[ee&&r("iframe",{ref:n,...He.attributes,sandbox:de,allow:I_(z?.permissions),style:{flex:1,width:"100%",height:"100%",minHeight:0,border:"none",background:"var(--c-panel)",pointerEvents:K?"auto":"none"},title:`Ext App: ${Fe}`},Se,!1,void 0,this),X&&!P&&r("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:[r("div",{children:"App surface failed to paint."},void 0,!1,void 0,this),r("button",{type:"button",onClick:(le)=>{le.stopPropagation(),vn(ae,"manual-retry"),m.current=0,V(!1),w("loading"),Y((we)=>we+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),(I==="loading"||B)&&!P&&!X&&r("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:[r("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),r("div",{children:I==="loading"?`Connecting to ${Fe}...`:"Finishing paint..."},void 0,!1,void 0,this),r("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!K&&!(X&&!P)&&r("button",{type:"button",onClick:(le)=>{le.stopPropagation(),xo(ae)},class:"ext-app-preview-catcher",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 Fl=new Map,F_=!1;function H_(e,t,n,o){if(!F_)F_=!0,sn(()=>{let l=H.value,c=Po.value;for(let[u,d]of Fl){let p=l.get(u);if(!p||d.epoch!==c||d.version!==p.data.specVersion||d.documentUrl!==p.data.url){for(let f of d.owners)f.cancel();Fl.delete(u)}}}),window.addEventListener("message",(l)=>{let c=l.data;if(!c||c.source!==ah||typeof c.nodeId!=="string")return;let u=Fl.get(c.nodeId),d=u?.owners.findIndex((h)=>h.token===c.token&&h.source===l.source)??-1;if(!u||d<0)return;if(c.type==="mounted"){u.owners[d].mounted();return}if(c.type==="ready"){u.owners[d].ready();return}if(c.type!=="snapshot")return;if(!c.state||typeof c.state!=="object"||Array.isArray(c.state))return;let{ax:p,...f}=c.state;u.state=f;let m=u.owners.slice(0,d);u.owners=u.owners.slice(d);for(let h of m)h.cancel()});let i=H.value.get(e);if(!i||o?.aborted)return Promise.resolve("cancelled");let s=Fl.get(e)??{epoch:Po.value,version:i.data.specVersion,documentUrl:i.data.url,state:null,owners:[]};Fl.set(e,s);let a=new Promise((l)=>{let c=(p)=>{if(clearTimeout(d),o?.removeEventListener("abort",u.cancel),p!==!0)s.owners=s.owners.filter((f)=>f!==u);l(p)},u={token:t,source:n,mounted:()=>clearTimeout(d),ready:()=>c(!0),cancel:()=>c("cancelled")},d=setTimeout(()=>c(!1),1e4);for(let p of s.owners.filter((f)=>f.source===n))p.cancel();while(s.owners.length>1)s.owners[0].cancel();s.owners.push(u),o?.addEventListener("abort",u.cancel,{once:!0})});return n.postMessage({source:ah,type:"restore",token:t,state:s.state},"*"),a}function Jz(e,t,n,o,i,s,a,l){if(!e)return e;try{let c=tt()&&e.startsWith("/"),u=new URL(e,c?"https://pmx.invalid":window.location.origin);if(u.searchParams.set("theme",ta(Qt.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(i)u.searchParams.set("axNodeId",i);if(s)u.searchParams.set("frameToken",s);if(a)u.searchParams.set("fit","content");if(l)u.searchParams.set("stateToken",l);return c?`${u.pathname}${u.search}`:u.toString()}catch{return e}}function Yz(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 qh({source:e,iframeRef:t,onLoad:n,onDocumentLoad:o,title:i,className:s="mcp-app-frame",sandbox:a="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",allow:l="clipboard-read; clipboard-write",tabIndex:c}){let u=e.src??e.srcdoc??"",[d,p]=E({key:u,source:e,attempt:0}),[f,m]=E(null),h=D(0),g=D(new Set);Me(()=>{h.current+=1;for(let b of g.current)b.abort();if(g.current.clear(),!u||u===d.key){m(null);return}if(!d.key){p({key:u,source:e,attempt:0});return}m({key:u,source:e,attempt:0})},[u,d.key]),q(()=>()=>{h.current+=1;for(let b of g.current)b.abort();g.current.clear()},[]);let v=(b,x)=>r("iframe",{ref:x?void 0:t,...b.source,class:s,sandbox:a,allow:l,tabIndex:c,inert:x,"aria-hidden":x?!0:void 0,loading:_n.value==="srcdoc"?void 0:"lazy",onLoad:async(C)=>{let y=x?++h.current:h.current,k=C.currentTarget,_=new AbortController;g.current.add(_);let I=o?.(k,_.signal),w=I?await I:void 0;if(g.current.delete(_),h.current!==y||w==="cancelled")return;if(w===!1){if(b.attempt===0){let P={...b,attempt:1};if(x)m(P);else p(P)}else{if(x)m(null);hn("remove","Viewer could not load",`${x?"Keeping the last view. ":""}Reload to retry.`)}return}if(!x){n();return}requestAnimationFrame(()=>requestAnimationFrame(()=>{if(h.current!==y)return;t.current=k,p(b),m(null),n()}))},style:{position:"absolute",inset:0,width:"100%",height:"100%",visibility:"visible",zIndex:x?0:1,background:"var(--c-panel-soft)"},title:i},`${b.key}:${b.attempt}`,!1,void 0,this);return r("div",{class:"mcp-app-frame-stack",children:[v(d,!1),f&&v(f,!0)]},void 0,!0,void 0,this)}function di({node:e,expanded:t=!1}){if(e.data.mode==="ext-app")return r(B_,{node:e,expanded:t},void 0,!1,void 0,this);return r(Qz,{node:e,expanded:t},void 0,!1,void 0,this)}function Qz({node:e,expanded:t}){let n=D(null),o=e.type==="mcp-app"&&e.data.viewerType==="web-artifact",i=e.type==="json-render"||e.type==="graph",s=e.data.axCapabilities?.enabled,l=(i||o)&&(o?s===!0:s!==!1),c=o?"mcp-app":"json-render",u=Ke(()=>l?`ax-${crypto.randomUUID()}`:"",[l]),d=dh(e)&&!t,p=Ke(()=>d?`frame-${crypto.randomUUID()}`:"",[d]);Ys(e,n,p),sa({enabled:l&&Boolean(u),token:u,nodeId:e.id,sourceSurface:c,iframeRef:n});let f=Lo.value,m=()=>{if(!l||!u||f==null)return;n.current?.contentWindow?.postMessage({source:Qn,type:"ax-update",token:u,state:f},"*")};q(m,[l,u,f]);let h=typeof e.data.specVersion==="number"?e.data.specVersion:void 0,g=Ke(()=>i?`ui-${crypto.randomUUID()}`:"",[i,h,e.data.url]),v=Jz(e.data.url||"",t,h,u||void 0,l?e.id:void 0,p||void 0,d,g||void 0),b=Qs(v),x=e.data.sourceServer||"",C=e.data.hostMode||"hosted",y=e.data.fallbackReason,k=e.data.trustedDomain===!0||Yz(v);if(C==="fallback")return r("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[r("div",{style:{color:"var(--c-warn)",display:"flex",alignItems:"center",gap:"6px"},children:[r("span",{children:"⚠"},void 0,!1,void 0,this),r("span",{children:"Cannot embed — opened externally"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y&&r("div",{style:{color:"var(--c-muted)",fontSize:"11px"},children:["Reason: ",y]},void 0,!0,void 0,this),r("a",{href:v,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--c-accent)",fontSize:"12px",wordBreak:"break-all"},children:v},void 0,!1,void 0,this),x&&r("div",{style:{color:"var(--c-dim)",fontSize:"10px"},children:["Source: ",x]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return r("div",{style:{height:"100%",display:"flex",flexDirection:"column",...t?{flex:1,minHeight:0,width:"100%"}:{}},children:[!k&&r("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),r(qh,{source:b,iframeRef:n,onDocumentLoad:(_,I)=>{if(g&&_.contentWindow)return H_(e.id,g,_.contentWindow,I)},onLoad:m,title:`MCP App: ${x}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var e$=null;function la(){e$=null}var U_={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 t$(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 Id({node:e}){let t=t$(e),n=e.data.detail||"",o=e.data.message||"",i=e.data.level||"ok",s=e.data.activeTool,a=e.data.subagent,l=U_[t]??"var(--c-muted)",c=t!=="idle";return r("div",{style:{display:"flex",flexDirection:"column",gap:"8px",fontSize:"12px"},children:[r("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:l,boxShadow:c?`0 0 8px ${l}`:"none",animation:c?"pulse 1.5s infinite":"none",flexShrink:0}},void 0,!1,void 0,this),r("span",{style:{fontWeight:600,color:l,textTransform:"uppercase",letterSpacing:"0.05em"},children:t},void 0,!1,void 0,this),n&&r("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&&r("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-agent)"},children:[r("span",{style:{fontSize:"10px"},children:"⚙"},void 0,!1,void 0,this),r("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"&&r("div",{style:{display:"flex",alignItems:"center",gap:"6px",color:"var(--c-subagent)"},children:[r("span",{style:{fontSize:"10px"},children:"⠉"},void 0,!1,void 0,this),r("span",{children:a.name},void 0,!1,void 0,this),r("span",{style:{color:"var(--c-muted)",fontSize:"10px"},children:["(",a.state,")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o&&r("div",{style:{color:i==="warn"?"var(--c-warn)":i==="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 ca(e){return typeof e==="string"&&e.trim().length>0?e.trim():null}function j_(e){if(typeof e==="string"){let i=ca(e);return i?{title:"Evidence warning",detail:i}:null}if(!e||typeof e!=="object")return null;let t=e,n=ca(t.title)??"Evidence warning",o=ca(t.detail);return o?{title:n,detail:o}:null}function n$(e){let t=[],n=j_(e.data.warning);if(n)t.push(n);let o=e.data.warnings;if(Array.isArray(o))for(let s of o){let a=j_(s);if(a)t.push(a)}let i=ca(e.data.validationStatus)?.toLowerCase();if(i==="failed"||i==="invalid")t.push({title:"Image failed validation",detail:ca(e.data.validationMessage)??"Review this image before using it as evidence."});return t}function o$(e){let t=[e.data.title,e.data.caption,e.data.alt,e.data.src,e.data.path].map((n)=>ca(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 Z_(e){let t=n$(e);if(t.length>0)return t;if(o$(e))return[{title:"Captured login page",detail:"This image looks like an auth screen. Treat it as environment context, not product evidence."}];return[]}function Ed({node:e,expanded:t=!1}){let n=e.data.src||"",o=e.data.alt||e.data.title||"Image",i=e.data.caption||"",s=Z_(e),a=qs(n.startsWith("data:")||n.startsWith("http://")||n.startsWith("https://")?n:`/api/canvas/image/${e.id}`),[l,c]=E(!1),[u,d]=E(!1),[p,f]=E(1),[m,h]=E({x:0,y:0}),[g,v]=E({w:0,h:0}),b=D(null),x=D(!1),C=D({x:0,y:0}),y=oe((B)=>{let J=B.target;v({w:J.naturalWidth,h:J.naturalHeight}),c(!0),d(!1)},[]),k=oe(()=>{d(!0),c(!1)},[]);q(()=>{f(1),h({x:0,y:0})},[n]);let _=oe((B)=>{B.preventDefault(),B.stopPropagation();let J=B.deltaY>0?0.9:1.1;f((X)=>Math.max(0.25,Math.min(10,X*J)))},[]),I=oe((B)=>{if(p<=1)return;B.stopPropagation(),x.current=!0,C.current={x:B.clientX,y:B.clientY},B.target.setPointerCapture(B.pointerId)},[p]),w=oe((B)=>{if(!x.current)return;let J=B.clientX-C.current.x,X=B.clientY-C.current.y;C.current={x:B.clientX,y:B.clientY},h((V)=>({x:V.x+J,y:V.y+X}))},[]),P=oe(()=>{x.current=!1},[]),L=oe(()=>{f(1),h({x:0,y:0})},[]);if(!n)return r("div",{class:"image-node-empty",children:[r("div",{class:"image-node-empty-icon",children:"\uD83D\uDDBC"},void 0,!1,void 0,this),r("div",{class:"image-node-empty-text",children:"No image source"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let N=g.w>0?`${g.w}×${g.h}`:"",Y=Math.round(p*100);return r("div",{class:`image-node ${t?"image-node-expanded":""}`,ref:b,children:[s.length>0&&r("div",{class:"image-node-warning-stack",children:s.map((B)=>r("div",{class:"image-node-warning",children:[r("span",{class:"image-node-warning-title",children:B.title},void 0,!1,void 0,this),r("span",{class:"image-node-warning-detail",children:B.detail},void 0,!1,void 0,this)]},`${B.title}-${B.detail}`,!0,void 0,this))},void 0,!1,void 0,this),r("div",{class:"image-node-viewport",onWheel:_,onPointerDown:I,onPointerMove:w,onPointerUp:P,style:{cursor:p>1?"grab":"default"},children:[!l&&!u&&r("div",{class:"image-node-loading",children:"Loading…"},void 0,!1,void 0,this),u&&r("div",{class:"image-node-error",children:[r("div",{class:"image-node-error-icon",children:"⚠"},void 0,!1,void 0,this),r("div",{children:"Failed to load image"},void 0,!1,void 0,this),r("div",{class:"image-node-error-path",children:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("img",{src:a,alt:o,onLoad:y,onError:k,draggable:!1,style:{transform:`translate(${m.x}px, ${m.y}px) scale(${p})`,opacity:l?1:0,display:u?"none":"block"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(i||N||p!==1)&&r("div",{class:"image-node-footer",children:[i&&r("span",{class:"image-node-caption",children:i},void 0,!1,void 0,this),r("span",{class:"image-node-meta",children:[N&&r("span",{children:N},void 0,!1,void 0,this),p!==1&&r("button",{type:"button",class:"image-node-zoom-reset",onClick:L,"aria-label":"Reset zoom",children:[Y,"% ",r(Pu,{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 W_({node:e}){if((e.data.children??[]).filter((o)=>H.value.has(o)).length>0)return null;return r("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 r$(e){try{return new URL(e).host}catch{return e}}function i$(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleString()}function Ad({node:e,expanded:t=!1}){let n=typeof e.data.url==="string"?e.data.url:"",o=typeof e.data.pageTitle==="string"?e.data.pageTitle:"",i=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",l=typeof e.data.error==="string"?e.data.error:"",c=i$(typeof e.data.fetchedAt==="string"?e.data.fetchedAt:void 0),u=typeof e.data.statusCode==="number"?e.data.statusCode:null,d=typeof e.data.imageUrl==="string"?e.data.imageUrl:"",p=e.data.frameBlocked===!0,f=typeof e.data.frameBlockedReason==="string"?e.data.frameBlockedReason:"",[m,h]=E(!1),[g,v]=E(t);q(()=>{if(t)v(!0)},[t]);let b=oe(async()=>{if(!n||m)return;h(!0);try{await yu(e.id)}finally{h(!1)}},[e.id,m,n]);if(!n)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No webpage URL set"},void 0,!1,void 0,this);let x=a==="ready"?"var(--c-ok)":a==="error"?"var(--c-danger)":"var(--c-muted)";return r("div",{style:{display:"flex",flexDirection:"column",gap:"12px",height:"100%"},children:[r("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[r("div",{style:{minWidth:0,flex:1},children:[r("div",{style:{fontSize:"12px",color:"var(--c-muted)"},children:r$(n)},void 0,!1,void 0,this),r("div",{style:{fontSize:t?"18px":"15px",fontWeight:700,color:"var(--c-text)"},children:o||e.data.title||n},void 0,!1,void 0,this),r("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),r("div",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 8px",borderRadius:"999px",background:"rgba(255,255,255,0.04)",color:x,fontSize:"11px",textTransform:"uppercase",letterSpacing:"0.04em",flexShrink:0},children:[r("span",{style:{width:"7px",height:"7px",borderRadius:"999px",background:x}},void 0,!1,void 0,this),a]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(i||d)&&r("div",{style:{display:"grid",gridTemplateColumns:d&&t?"160px 1fr":"1fr",gap:"12px",alignItems:"start"},children:[d&&t&&r("img",{src:d,alt:o||"Webpage preview image",style:{width:"160px",height:"96px",objectFit:"cover",borderRadius:"10px",border:"1px solid var(--c-line)",background:"var(--c-panel-soft)"}},void 0,!1,void 0,this),i&&r("p",{style:{margin:0,color:"var(--c-text-soft)",lineHeight:1.5,fontSize:t?"14px":"12px"},children:i},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap"},children:[r("button",{type:"button",onClick:b,disabled:m,style:{border:"1px solid var(--c-line)",background:"var(--c-panel-soft)",color:"var(--c-text)",borderRadius:"8px",padding:"6px 10px",cursor:m?"progress":"pointer",fontSize:"12px"},children:m||a==="fetching"?"Refreshing…":"Refresh"},void 0,!1,void 0,this),t&&!p&&r("button",{type:"button",onClick:()=>v((C)=>!C),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:g?"Hide live preview":"Show live preview"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>window.open(n,"_blank","noopener"),style:{border:"1px solid var(--c-line)",background:"transparent",color:"var(--c-accent)",borderRadius:"8px",padding:"6px 10px",cursor:"pointer",fontSize:"12px"},children:"Open in browser"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&p&&r("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[r("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),r("div",{style:{padding:"20px",color:"var(--c-text-soft)",lineHeight:1.6,fontSize:"13px"},children:f||"The remote site blocks iframe embedding."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&g&&!p&&r("div",{style:{border:"1px solid var(--c-line)",borderRadius:"12px",overflow:"hidden",background:"var(--c-panel-soft)"},children:[r("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),r("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),(c||u!==null)&&r("div",{style:{display:"flex",gap:"12px",flexWrap:"wrap",color:"var(--c-muted)",fontSize:"11px"},children:[c&&r("span",{children:["Fetched ",c]},void 0,!0,void 0,this),u!==null&&r("span",{children:["HTTP ",u]},void 0,!0,void 0,this),p&&r("span",{children:"Preview blocked by site"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),l&&r("div",{style:{color:"var(--c-danger)",fontSize:"12px",lineHeight:1.5},children:l},void 0,!1,void 0,this),r("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?r("div",{style:{whiteSpace:"pre-wrap",lineHeight:1.55,color:"var(--c-text)",fontSize:t?"14px":"12px"},children:s},void 0,!1,void 0,this):r("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 q_(e){return e.type==="html"&&e.data.presentation===!0}function s$(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 Hl({node:e,expanded:t=!1,presentation:n=!1,presentationExitToken:o,autoFocus:i=!1}){let s=D(null),a=Qt.value,l=s$(e.data.axCapabilities),c=Ke(()=>`theme-${crypto.randomUUID()}`,[]),u=Ke(()=>`ax-${crypto.randomUUID()}`,[l]),d=Ke(()=>`frame-${crypto.randomUUID()}`,[]),p=typeof e.data.html==="string"?e.data.html:typeof e.data.content==="string"?e.data.content:"",f=Ke(()=>Xs(p),[p]),m=Ke(()=>p?Il(e.id,{theme:a,themeToken:c,present:n,presentToken:o,v:f,axToken:u,frameToken:d}):"",[p,n,o,c,f,e.id,u,d]),h=Qs(m);Ys(e,s,t?"":d),sa({enabled:!0,token:u,nodeId:e.id,sourceSurface:"html-node",iframeRef:s}),q(()=>{if(s.current?.contentWindow?.postMessage({source:Qn,type:"theme-update",token:c,theme:a},"*"),i)s.current?.focus()},[a,c]);let g=e.data.axCapabilities,v=g?.enabled===!0&&(!Array.isArray(g.allowed)||g.allowed.length>0),b=Lo.value;q(()=>{if(!v||b==null)return;s.current?.contentWindow?.postMessage({source:Qn,type:"ax-update",token:u,state:b},"*")},[v,b,u]),q(()=>{if(!i)return;let y=window.setTimeout(()=>s.current?.focus(),0);return()=>window.clearTimeout(y)},[i,m]);let x=(y,k)=>{if(k.aborted)return Promise.resolve(!1);return new Promise((_)=>{let I=(N)=>{clearTimeout(L),window.removeEventListener("message",P),k.removeEventListener("abort",w),_(N)},w=()=>I(!1),P=(N)=>{if(N.source!==y.contentWindow||N.data?.source!==Qn||N.data?.token!==c)return;if(N.data.type==="mounted")clearTimeout(L);if(N.data.type==="ready")I(!0)},L=setTimeout(w,1e4);window.addEventListener("message",P),k.addEventListener("abort",w,{once:!0}),y.contentWindow?.postMessage({source:Qn,type:"check-ready",token:c},"*")})},C=()=>{if(s.current?.contentWindow?.postMessage({source:Qn,type:"theme-update",token:c,theme:a},"*"),v&&Lo.value!=null)s.current?.contentWindow?.postMessage({source:Qn,type:"ax-update",token:u,state:Lo.value},"*");if(i)s.current?.focus()};if(!p)return r("div",{style:{color:"var(--c-dim)",fontStyle:"italic",padding:"12px"},children:"No HTML content set"},void 0,!1,void 0,this);return r(qh,{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:i?0:void 0,onLoad:C,onDocumentLoad:x},void 0,!1,void 0,this)}var Gh=null;async function G_(){if(!Gh)Gh=await hk();return Gh}function K_(e,t){if(!e)return null;let n=e.toLowerCase(),o=t.find((s)=>s.name.toLowerCase()===n);if(o)return o.name;let i=t.filter((s)=>s.name.toLowerCase().startsWith(n));return i.length===1?i[0].name:null}function a$({html:e}){let t=D(null);return q(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=er(e),n.append(o.content.cloneNode(!0))},[e]),r("div",{ref:t},void 0,!1,void 0,this)}function l$(e,t){return`${e.role}:${e.status??"none"}:${t}:${e.text}`}function V_({count:e}){if(e===0)return null;return r("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 X_({message:e,onDismiss:t}){if(!e)return null;return r("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:[r("span",{style:{flex:1},children:e},void 0,!1,void 0,this),r("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:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Rd({node:e,expanded:t=!1}){let n=Array.isArray(e.data.turns)?e.data.turns:[],o=n.length===0,i=e.data.text||"",s=e.data.status||"draft",a=o?s:e.data.threadStatus||"draft",l=a==="draft",c=a==="pending"||a==="sending",u=a==="streaming",d=a==="answered",[p,f]=E(""),[m,h]=E(""),[g,v]=E(null),[b,x]=E(new Map),C=D(null),y=D(null),k=n[n.length-1],_=`${n.length}:${k?.role??""}:${k?.status??""}:${Math.floor((k?.text?.length??0)/200)}`;q(()=>{if(t&&l&&C.current)C.current.focus()},[t,l]),q(()=>{if(!_)return;if(y.current)y.current.scrollTo({top:y.current.scrollHeight,behavior:"smooth"})},[_]);let I=D(null),w=D(n);w.current=n,q(()=>{let J=n.some((V)=>V.role==="assistant"&&V.status==="streaming"),X=()=>{let V=!1,he=w.current.map((A,te)=>({turn:A,index:te})).filter(({turn:A})=>A.role==="assistant"&&A.text);if(he.length===0)return;return Promise.all(he.map(async({turn:A,index:te})=>{let M=await Vo(A.text);return{index:te,html:er(M??"")}})).then((A)=>{if(V)return;let te=new Map;for(let M of A)te.set(M.index,M.html);x(te)}),()=>{V=!0}};if(!J){if(I.current)clearTimeout(I.current),I.current=null;return X()}if(I.current)clearTimeout(I.current);return I.current=setTimeout(()=>{I.current=null,X()},400),()=>{if(I.current)clearTimeout(I.current),I.current=null}},[n]);let P=oe(async()=>{let J=p.trim();if(!J)return;let X=p;v(null),Xe(e.id,{turns:[{role:"user",text:J,status:"pending"}],threadStatus:"pending",text:J}),f("");let V=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds:void 0;if(!(await rl(J,e.position,e.id,V,e.id)).ok)Xe(e.id,{turns:[],threadStatus:"draft",text:"",status:"draft"}),f(X),v("Failed to send prompt. Your draft has been restored.")},[p,e.id,e.position,e.data.contextNodeIds]),L=oe(async()=>{let J=m.trim();if(!J)return;let X=m;v(null);let V=Array.isArray(e.data.turns)?[...e.data.turns]:[];if(V.push({role:"user",text:J,status:"pending"}),Xe(e.id,{turns:V,threadStatus:"pending"}),h(""),!(await gk(e.id,J)).ok)V.pop(),Xe(e.id,{turns:V,threadStatus:"answered"}),h(X),v("Failed to send reply. Your draft has been restored.")},[m,e.id,e.data.turns]),N=oe((J)=>{if(J.key==="Enter"&&(J.metaKey||J.ctrlKey)){J.preventDefault(),P();return}if(J.key==="Tab"&&p.startsWith("/")){J.preventDefault();let X=p.slice(1).split(/\s/)[0];if(X)G_().then((V)=>{let ee=K_(X,V);if(ee)f(`/${ee}`)})}},[P,p]),Y=oe((J)=>{if(J.key==="Enter"&&(J.metaKey||J.ctrlKey)){J.preventDefault(),L();return}if(J.key==="Tab"&&m.startsWith("/")){J.preventDefault();let X=m.slice(1).split(/\s/)[0];if(X)G_().then((V)=>{let ee=K_(X,V);if(ee)h(`/${ee}`)})}},[L,m]),B=Array.isArray(e.data.contextNodeIds)?e.data.contextNodeIds.length:0;if(l&&n.length===0)return r("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%",gap:"8px"},children:[r(V_,{count:B},void 0,!1,void 0,this),r(X_,{message:g,onDismiss:()=>v(null)},void 0,!1,void 0,this),r("textarea",{ref:C,value:p,onInput:(J)=>f(J.target.value),onKeyDown:N,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),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter to send"]},void 0,!0,void 0,this),r("button",{type:"button",onClick:P,disabled:!p.trim(),style:{padding:"5px 14px",fontSize:"12px",fontWeight:600,background:p.trim()?"var(--c-accent)":"var(--c-line)",color:p.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:p.trim()?"pointer":"default"},children:"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);if(o)return r("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[r("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:i},void 0,!1,void 0,this),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px"},children:r("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:c?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:c?"Sending…":d?"Answered":s},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{class:"prompt-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[r(V_,{count:B},void 0,!1,void 0,this),r(X_,{message:g,onDismiss:()=>v(null)},void 0,!1,void 0,this),r("div",{ref:y,style:{flex:1,overflow:"auto",minHeight:0},children:n.map((J,X)=>r("div",{children:[X>0&&r("div",{class:"thread-turn-divider"},void 0,!1,void 0,this),J.role==="user"?r("div",{class:"thread-turn-user",children:[r("div",{class:"thread-turn-role",children:[r("span",{class:"status-dot"},void 0,!1,void 0,this),"You"]},void 0,!0,void 0,this),r("div",{style:{fontSize:t?"15px":"13px",lineHeight:t?"1.7":"1.55",color:"var(--c-text)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:J.text},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("div",{class:"thread-turn-assistant",children:[r("div",{class:"thread-turn-role",children:[r("span",{class:`status-dot${J.status==="streaming"?" pulsing":""}`},void 0,!1,void 0,this),"PMX"]},void 0,!0,void 0,this),J.status==="streaming"&&!J.text&&r("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),r("div",{class:t?"md-reader-content":void 0,style:{fontSize:t?void 0:"13px",lineHeight:t?void 0:"1.55",opacity:J.text?1:0.4},children:b.get(X)?r(be,{children:[r(a$,{html:b.get(X)??""},void 0,!1,void 0,this),J.status==="streaming"&&r("span",{class:"streaming-cursor"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("div",{style:{color:"var(--c-muted)",fontStyle:"italic"},children:J.status==="streaming"?"Waiting for response…":J.text||"Empty response"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},l$(J,X),!0,void 0,this))},void 0,!1,void 0,this),r("div",{style:{flexShrink:0,borderTop:"1px solid var(--c-line)",marginTop:"4px",paddingTop:"6px"},children:[r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:d?"6px":0},children:[r("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:u?"var(--c-accent)":c?"var(--c-warn)":d?"var(--c-ok)":"var(--c-muted)"},children:u?"Streaming…":c?"Sending…":d?"Answered":a},void 0,!1,void 0,this),r("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:[n.length," turn",n.length!==1?"s":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d&&r("div",{class:"thread-reply-area",children:[r("textarea",{value:m,onInput:(J)=>h(J.target.value),onKeyDown:Y,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),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"4px"},children:[r("span",{style:{fontSize:"10px",color:"var(--c-muted)"},children:["⌘","+Enter"]},void 0,!0,void 0,this),r("button",{type:"button",onClick:L,disabled:!m.trim(),style:{padding:"3px 10px",fontSize:"11px",fontWeight:600,background:m.trim()?"var(--c-accent)":"var(--c-line)",color:m.trim()?"var(--c-contrast-fg)":"var(--c-muted)",border:"none",borderRadius:"var(--radius-sm)",cursor:m.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 c$({html:e}){let t=D(null);return q(()=>{let n=t.current;if(!n)return;if(n.replaceChildren(),!e)return;let o=document.createElement("template");o.innerHTML=er(e),n.append(o.content.cloneNode(!0))},[e]),r("div",{ref:t},void 0,!1,void 0,this)}function Pd({node:e,expanded:t=!1}){let n=e.data.content||"",o=e.data.status||"streaming",[i,s]=E(""),a=o==="streaming",l=o==="complete";q(()=>{if(!n){s("");return}let u=!1;return Vo(n).then((d)=>{if(!u)s(er(d??""))}),()=>{u=!0}},[n]);let c=oe(()=>{rl("",{x:e.position.x,y:e.position.y+e.size.height+24},e.id)},[e]);return r("div",{class:"response-node-inner",style:{display:"flex",flexDirection:"column",height:"100%"},children:[a&&r("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),r("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:i?r("div",{class:t?"md-reader-content":void 0,children:r(c$,{html:i},void 0,!1,void 0,this)},void 0,!1,void 0,this):r("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),r("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",paddingTop:"6px",borderTop:"1px solid var(--c-line)",marginTop:"4px",flexShrink:0},children:[r("span",{style:{fontSize:"10px",textTransform:"uppercase",fontWeight:600,color:a?"var(--c-accent)":l?"var(--c-ok)":"var(--c-muted)"},children:a?"Streaming…":l?"Complete":o},void 0,!1,void 0,this),l&&r("button",{type:"button",onClick:c,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 J_(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 Y_={mcp:"var(--c-muted)",file:"var(--c-muted)",subagent:"var(--c-subagent)",other:"var(--c-muted)"},u$={running:"⠋",success:"✓",failed:"✕"},d$={running:"var(--c-accent)",success:"var(--c-ok)",failed:"var(--c-danger)"};function Nd({node:e}){let{toolName:t,category:n,status:o,duration:i,resultSummary:s,error:a}=J_(e.data),l=Y_[n]??Y_.other,c=u$[o]??"◌",u=d$[o]??"var(--c-muted)",d=o==="running",p=a?a.slice(0,30):s.length>30?`${s.slice(0,28)}…`:s;return r("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"0 12px",height:"100%",overflow:"hidden"},children:[r("span",{style:{fontSize:"14px",color:u,flexShrink:0,animation:d?"pulse 1.5s infinite":"none"},children:c},void 0,!1,void 0,this),r("div",{style:{flex:1,minWidth:0,overflow:"hidden"},children:[r("div",{style:{fontFamily:"var(--font-code)",fontSize:"11px",fontWeight:600,color:l,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t},void 0,!1,void 0,this),p&&r("div",{style:{fontSize:"10px",color:a?"var(--c-danger)":"var(--c-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:1.3},children:p},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i&&r("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:i},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var p$=new Set(["png","jpg","jpeg","gif","svg","webp","bmp","ico","avif"]),f$=new Set(["md","mdx","markdown"]);function m$(e){let t=e.split(".").pop()?.toLowerCase()??"";if(p$.has(t))return"image";if(f$.has(t))return"markdown";return"file"}async function ua(e,t,n){let o=se.value,i=400,s=300,a=20,l=Math.ceil(Math.sqrt(e.length));for(let c=0;c<e.length;c++){let u=e[c],d=c%l,p=Math.floor(c/l),f=t-l*420/2+d*420,m=n-150+p*320,h=m$(u.name),g=u.name;if(/\.(pdf|pptx?|xlsx?|docx?|od[pts])$/i.test(g)){if(!o||u.size===0||u.size>20971520){hn("remove","File not attached","Open a board and choose a nonempty file under 20 MiB.");continue}let v=new URLSearchParams({boardId:o,name:g,mime:u.type,x:String(f),y:String(m)});hn("context","Attaching document",g),await pe("attachDocument",`/api/canvas/attachments?${v}`,null,{method:"POST",body:u});continue}if(se.value!==o)return;if(h==="image"){let v=new FileReader,b=await new Promise((x)=>{v.onload=()=>x(v.result),v.readAsDataURL(u)});if(se.value!==o)return;await No({type:"image",title:g,content:b,x:f,y:m,width:400,height:300,...o?{boardId:o}:{}})}else{let v=await u.text();if(se.value!==o)return;let b=h==="markdown"||h==="file";await No({type:h,title:g,content:v,x:f,y:m,width:b?720:400,height:b?500:300,...o?{boardId:o}:{}})}}}var Q_={width:260,height:150},h$={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 Vh(e){return!!e&&e in an}function Pr(e){if(!e)return null;let t=H.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 Kh(e){return{x:e.left+e.width/2,y:e.top+e.height/2}}function Ul(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 eC(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 Xh({intent:e}){let t=Vh(e.nodeType)?Do(e.nodeType):null,n=e.label||e.kind,o=typeof e.confidence==="number"?`${Math.round(e.confidence*100)}%`:null;return r("div",{class:"intent-info",onMouseEnter:()=>Ts.value=e.id,onMouseLeave:()=>{if(Ts.value===e.id)Ts.value=null},children:[r("div",{class:"intent-chip",children:[typeof e.seq==="number"&&r("span",{class:"intent-seq",children:e.seq},void 0,!1,void 0,this),t&&r("span",{class:"intent-chip-icon","aria-hidden":"true",children:r(t,{size:12},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"intent-chip-label",children:n},void 0,!1,void 0,this),o&&r("span",{class:"intent-confidence",children:o},void 0,!1,void 0,this),e.phase==="forming"&&!e.auto&&r(_e,{label:"Veto this move",shortcut:"Esc",children:r("button",{type:"button",class:"intent-veto","aria-label":"Veto this move",onClick:(i)=>{i.stopPropagation(),Li(e)},children:r(Tt,{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),e.reason&&r("div",{class:"intent-reason",children:e.reason},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function tC({intent:e,rect:t}){let n=Vh(e.nodeType)?Do(e.nodeType):null,o=Vh(e.nodeType)?an[e.nodeType]:"Node";return r("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:Ul(e)},children:[r("div",{class:"intent-ghost-titlebar",children:[r("span",{class:"intent-ghost-icon","aria-hidden":"true",children:n?r(n,{size:13},void 0,!1,void 0,this):"◇"},void 0,!1,void 0,this),r("span",{class:"intent-ghost-badge",children:o},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(Xh,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nC({intent:e,rect:t,variant:n}){return r("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:Ul(e)},children:[n==="edit"&&r("div",{class:"intent-edit-bar"},void 0,!1,void 0,this),r(Xh,{intent:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function g$(e){let t=e.phase==="settling"?Pr(e.settledNodeId):null;switch(e.kind){case"create":{if(!e.position)return null;let n=e.nodeType&&h$[e.nodeType]||Q_,o=t??{left:e.position.x,top:e.position.y,...n};return r(tC,{intent:e,rect:o},e.id,!1,void 0,this)}case"move":{if(!e.position)return null;let o=Pr(e.nodeId)??Q_,i=t??{left:e.position.x,top:e.position.y,width:o.width,height:o.height};return r(tC,{intent:e,rect:i},e.id,!1,void 0,this)}case"remove":{let n=t??Pr(e.nodeId);if(!n)return null;return r(nC,{intent:e,rect:n,variant:"remove"},e.id,!1,void 0,this)}case"edit":{let n=t??Pr(e.nodeId);if(!n)return null;return r(nC,{intent:e,rect:n,variant:"edit"},e.id,!1,void 0,this)}case"connect":{if(!e.edge)return null;if("toBoardId"in e.edge&&e.edge.toBoardId&&e.edge.toBoardId!==se.value)return null;let n=Pr(e.edge.from),o=Pr(e.edge.to);if(!n||!o)return null;let i={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:i.x-110,top:i.y-18,width:220,height:36};return r("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:Ul(e)},children:r(Xh,{intent:e},void 0,!1,void 0,this)},e.id,!1,void 0,this)}default:return null}}function oC(){let e=Array.from(qt.value.values());if(q(()=>{function t(n){if(n.key!=="Escape")return;let o=Ts.value;if(!o)return;let i=qt.value.get(o);if(!i||i.phase!=="forming")return;n.stopImmediatePropagation(),n.preventDefault(),Li(i)}return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[]),e.length===0)return null;return r("div",{class:"intent-layer",onAnimationEnd:(t)=>{if(t.animationName!=="intent-settle"&&t.animationName!=="intent-dissolve")return;let n=t.target.dataset.intentId;if(n&&qt.value.get(n)?.phase!=="forming")zi(n)},children:[r("svg",{class:"intent-line-layer",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"},children:[r("defs",{children:r("marker",{id:"intent-arrow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"3",orient:"auto",children:r("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){if("toBoardId"in t.edge&&t.edge.toBoardId&&t.edge.toBoardId!==se.value)return null;let n=Pr(t.edge.from),o=Pr(t.edge.to);if(!n||!o)return null;return r("path",{d:eC(Kh(n),Kh(o)),class:`intent-edge type-${t.edge.type}`,style:{opacity:Ul(t)}},`line-${t.id}`,!1,void 0,this)}if(t.kind==="move"&&t.position){let n=Pr(t.nodeId);if(!n)return null;let o=n,i={x:t.position.x+o.width/2,y:t.position.y+o.height/2};return r("path",{d:eC(Kh(n),i),class:"intent-trail",markerEnd:"url(#intent-arrow)",style:{opacity:Ul(t)}},`line-${t.id}`,!1,void 0,this)}return null})]},void 0,!0,void 0,this),e.map(g$)]},void 0,!0,void 0,this)}var da="Agent session";function rC(e){return e.some((t)=>t.attached)}function iC(e){return e.filter((t)=>!t.attached)}function pi(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 en=ie([]),fi=ie([]),ts=ie(!1),pa=ie(!1),Jh=ie(null);function So(e){return en.value.find((n)=>n.sessionId===e)?.parentAgentId?"var(--c-subagent)":"var(--c-agent)"}function Md(e){return(e.trim().replace(/^[^a-z0-9]+/i,"").charAt(0)||e.trim().charAt(0)||"?").toUpperCase()}function zd(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 _o=Ve(()=>rC(en.value)),tr=Ve(()=>xt.value&&_o.value),$d=Ve(()=>xt.value?iC(en.value):en.value),sC=Ve(()=>{let e=new Set;return[...en.value].filter((t)=>t.label!==da).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))}),fa=Ve(()=>en.value.filter((e)=>e.attached)),mi=Ve(()=>en.value.find((e)=>e.attached)??null);function y$(e){let t=new Set;for(let n of e)if(n.nodeId&&n.kind!=="create")t.add(n.nodeId);return t}var Ld=Ve(()=>y$(qt.value.values()));function Od(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 aC(e){if(!e)return;if(Array.isArray(e.presences))en.value=e.presences;if(Array.isArray(e.activity))fi.value=e.activity}function lC(){let e=D(new Map),t=Ee.value.scale,n=H.value,o=1/Math.max(0.05,t),i=en.value.map((s)=>{let a=Od(s,(c)=>n.get(c));if(a)e.current.set(s.sessionId,a);let l=a??e.current.get(s.sessionId)??null;return l?{presence:s,position:l}:null}).filter((s)=>s!==null);if(i.length===0)return null;return r("div",{class:"agent-presence-layer","aria-hidden":"true",children:i.map(({presence:s,position:a})=>r("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":So(s.sessionId)},children:r("div",{class:"agent-cursor-inner",style:{transform:`scale(${o})`},children:[r("svg",{class:"agent-cursor-glyph",width:"16",height:"18",viewBox:"0 0 16 18","aria-hidden":"true",children:r("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),r("span",{class:"agent-cursor-chip",children:[r("span",{class:"agent-cursor-dot"},void 0,!1,void 0,this),r("span",{class:"agent-cursor-label",children:pi(s)},void 0,!1,void 0,this),r("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 nr(e=1000){let[t,n]=E(()=>Date.now());return q(()=>{if(e<=0)return;n(Date.now());let o=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(o)},[e]),t}function cC(){let e=nr(Ya.value.length>0?5000:0),t=Ya.value.filter((o)=>o.cursor!==null&&(!o.lastSeenAt||e-Date.parse(o.lastSeenAt)<Hw+5000));if(t.length===0)return null;let n=1/Math.max(0.05,Ee.value.scale);return r("div",{class:"human-presence-layer","aria-hidden":"true",children:t.map((o)=>r("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:r("div",{class:"human-cursor-inner",style:{transform:`scale(${n})`},children:[r("svg",{class:"human-cursor-glyph",width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",children:r("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),r("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)}var uC=ie(new Map),hi=ie({}),Yh=ie({});function Qh(e){uC.value=new Map((e.nodes??[]).map((t)=>[t.nodeId,t])),Yh.value=e.links??{},hi.value=e.pins??{}}async function jl(){let e=await pe("fetchContextStatus","/api/canvas/ax/context-status",{});if(e.ok&&e.boardId===se.value)Qh(e)}function Dd(e,t){let n=uC.value.get(e),o=hi.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 dC(e){if(e.changedBy?.actor==="agent")return{agent:Nr(e.changedBy),notSeen:!1};let t=Yh.value;return{agent:null,notSeen:!!e.revision&&Object.keys(t).length>0&&e.revision>Math.max(t[e.from]??-1,e.toBoardId===void 0?t[e.to]??-1:-1)}}function Bd(e,t){let n=Yh.value[e];if(n===void 0||t<=n)return!1;let o=[...et.value.values()].filter((i)=>(i.from===e||i.toBoardId===void 0&&i.to===e)&&(i.revision??0)>n);if(o.some((i)=>i.changedBy?.actor!=="agent"))return!0;return!o.some((i)=>i.revision===t)}function Nr(e){return e.agentId?.trim()||e.source}var gi={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 pC(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function fC(e,t){if(!t)return null;let n=hi.value[e.id],o=n?.pinnedBy.actor==="agent"?` Pinned by ${Nr(n.pinnedBy)}${n.reason?`: ${n.reason}`:""}.`:"",i=Dd(e.id,e.contentRevision??0);if(i.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(i.kind==="changed")return{tone:"warn",glyph:"warn",word:"changed",label:"The agent's copy is out of date",body:`Text changed after ${i.by} read it at ${pC(i.at)}${Bd(e.id,e.linksRevision??0)?" · links changed too":""}.${o}`};return{tone:"agent",glyph:"eye",word:"read",label:"Read by the agent",body:`${i.count>1?`Read ${i.count} times · last`:"Read"} ${pC(i.at)} by ${i.by}.${o}`}}function v$(e){if(e.lastEditedBy?.actor==="human")return null;if(e.createdBy?.actor==="agent")return`Written by ${Nr(e.createdBy)}`;if(e.lastEditedBy?.actor==="agent")return`Edited by ${Nr(e.lastEditedBy)}`;return null}function eg(e,t){let n=fC(e,t);if(n)return{amber:n.tone==="warn",folded:n.label};let o=t?void 0:ro.value.get(e.id);if(o&&o.length>0)return{amber:!1,folded:o.length>1?`near ${o.length} pins`:"near a pin"};return null}function mC({node:e,pinned:t,fold:n="word"}){let o=fC(e,t),i=o?.tone==="warn"?"word":n;if(!o||i==="hidden")return null;return r(_e,{label:o.label,body:o.body,align:"end",fitWithin:".node-content",tapToOpen:!0,children:r("span",{class:`node-context-mark is-${o.tone}${i==="glyph"?" is-glyph":""}`,"data-mark":o.word,"aria-label":i==="glyph"?o.word:void 0,children:[r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:r("path",{d:gi[o.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),i==="word"&&o.word]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function hC({node:e,pinned:t,title:n,fold:o,children:i}){let s=v$(e),a=o==="hidden"?eg(e,t):null,l=[s,a&&!a.amber?a.folded:"",an[e.type]].filter(Boolean).join(" · ");return r(_e,{label:n,body:l,align:"start",fitWithin:".node-content",tapToOpen:!0,children:r("span",{class:"node-type-icon","data-byline":s??void 0,children:i},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function gC(e){return hi.value[e]?.pinnedBy.actor==="agent"}function yC({node:e,pinned:t,fold:n="word"}){let o=t?void 0:ro.value.get(e.id),i=Bi.value?.nodeId===e.id?Bi.value:null,s=!o&&!t&&i?.kind==="out",a=o??(s?i.pins:void 0);if(!a||a.length===0||n==="hidden")return null;let l=a.length>1?`near ${a.length}`:"near",c=s?" is-fading":i?.kind==="in"?" is-pulse":Wo.value===e.id?" is-preview":"",u=(d)=>{if(!s)ak(e.id,d.currentTarget,tg())};return r("button",{type:"button",class:`node-near-mark${n==="glyph"?" is-glyph":""}${c}`,"aria-label":n==="glyph"?l:void 0,"aria-expanded":Vr.value?.nodeId===e.id,"data-near":a.map((d)=>d.pinNodeId).join(" "),onPointerDown:(d)=>d.stopPropagation(),onPointerEnter:u,onPointerLeave:As,onFocus:u,onBlur:As,onClick:u,onKeyDown:(d)=>{if(d.key!=="Enter"&&d.key!=="ArrowDown")return;d.preventDefault(),u(d),requestAnimationFrame(()=>document.querySelector(".near-hint button")?.focus())},onAnimationEnd:()=>qf(e.id),children:[r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[r("circle",{cx:"12",cy:"12",r:"8",class:"node-near-ring"},void 0,!1,void 0,this),r("circle",{cx:"12",cy:"12",r:"2.2",class:"node-near-dot"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n==="word"&&l]},void 0,!0,void 0,this)}function tg(){let e=Ee.value;return`${e.x},${e.y},${e.scale}`}var vC=600;function bC(e,t){let n={x:t.left+t.width/2,y:t.top+t.height/2},o=e.x-n.x,i=e.y-n.y,s=Math.min(o===0?Number.POSITIVE_INFINITY:t.width/2/Math.abs(o),i===0?Number.POSITIVE_INFINITY:t.height/2/Math.abs(i));return s>=1?n:{x:n.x+o*s,y:n.y+i*s}}function xC(){let e=rk.value;if(e.pinIds.length===0)return null;let t=Ee.value,n=H.value,o=ok.value,i=(s,a)=>({x:s*t.scale+t.x,y:a*t.scale+t.y});return r("svg",{class:"near-pin-layer","aria-hidden":"true",children:e.pinIds.map((s)=>{let a=n.get(s);if(!a)return null;if(![...n.values()].some((f)=>f.id!==s&&hr(f,a)<=vC))return null;let l=i(a.position.x,a.position.y),c={left:l.x,top:l.y,width:a.size.width*t.scale,height:a.size.height*t.scale},u={x:c.left+c.width/2,y:c.top+c.height/2},d=vC*t.scale,p=e.ringOnly?[]:(o.get(s)??[]).map((f)=>n.get(f)).filter((f)=>f!==void 0).sort((f,m)=>hr(f,a)-hr(m,a));return r("g",{"data-pin-id":s,children:[r("rect",{class:"near-pin-radius",x:c.left-d,y:c.top-d,width:c.width+2*d,height:c.height+2*d,rx:d},void 0,!1,void 0,this),p.map((f,m)=>{let h=i(f.position.x,f.position.y),g={left:h.x,top:h.y,width:f.size.width*t.scale,height:f.size.height*t.scale},v=bC(u,g),b=bC({x:g.left+g.width/2,y:g.top+g.height/2},c);return r("g",{class:"near-pin-tether","data-near-node":f.id,children:[r("path",{d:`M ${b.x} ${b.y} L ${v.x} ${v.y}`},void 0,!1,void 0,this),r("circle",{class:"near-pin-number",cx:v.x,cy:v.y,r:10},void 0,!1,void 0,this),r("text",{class:"near-pin-number-label",x:v.x,y:v.y,children:m+1},void 0,!1,void 0,this)]},f.id,!0,void 0,this)})]},s,!0,void 0,this)})},void 0,!1,void 0,this)}function wC(){let e=Vr.value;if(!e||e.view!==tg())return null;let t=H.value.get(e.nodeId),n=ro.value.get(e.nodeId);if(!t||!n)return null;let o=du.value===t.id,i=Math.max(8,Math.min(e.at.right-240,window.innerWidth-248)),s=e.at.bottom<window.innerHeight/2,a=s?window.innerHeight-e.at.bottom-16:e.at.top-16;return r("div",{class:"near-hint",role:"dialog","aria-label":n.length>1?`Near ${n.length} pins`:"Near a pin",style:{left:`${i}px`,maxHeight:`${Math.max(120,a)}px`,...s?{top:`${e.at.bottom+8}px`}:{bottom:`${window.innerHeight-e.at.top+8}px`}},onPointerEnter:Gf,onPointerLeave:As,onFocusIn:Gf,onFocusOut:As,onPointerDown:(l)=>l.stopPropagation(),onKeyDown:(l)=>{if(l.key!=="Escape")return;l.stopPropagation(),Vr.value=null,document.querySelector(`[data-node-id="${CSS.escape(t.id)}"] .node-near-mark`)?.focus()},children:[r("span",{class:"near-hint-label",children:n.length>1?`Near ${n.length} pins`:"Near a pin"},void 0,!1,void 0,this),n.map((l)=>{let c=H.value.get(l.pinNodeId);return r("span",{class:"near-hint-row",children:[r("span",{class:"near-hint-title",children:l.pinTitle},void 0,!1,void 0,this),c&&r("span",{class:"near-hint-distance",children:[Math.round(hr(t,c))," px"]},void 0,!0,void 0,this)]},l.pinNodeId,!0,void 0,this)}),r("span",{class:"near-hint-body",children:"Distance is measured between card edges. The agent gets its title and a short summary because a pin is nearby. Pin it to put it first."},void 0,!1,void 0,this),r("span",{class:"near-hint-actions",children:[r("button",{type:"button",class:"near-hint-pin",onClick:()=>{Vr.value=null,lo(t.id)},children:"Pin to put it first"},void 0,!1,void 0,this),r("button",{type:"button",class:"near-hint-show","aria-pressed":o,onClick:()=>{du.value=o?null:t.id},children:o?"Hide pins":"Show pins"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Fd(e,t){let{POSITIVE_INFINITY:n,POSITIVE_INFINITY:o,NEGATIVE_INFINITY:i,NEGATIVE_INFINITY:s}=Number,a=0;for(let l of e)a+=1,n=Math.min(n,l.position.x),o=Math.min(o,l.position.y),i=Math.max(i,l.position.x+l.size.width),s=Math.max(s,l.position.y+l.size.height);if(a===0)return null;return{x:n-t,y:o-t,width:i-n+t*2,height:s-o+t*2}}var eo=ie(!1);function og(){let e=Lo.value;return e&&typeof e==="object"?e:{}}var SC=Ve(()=>og().workItems??[]),rg=Ve(()=>og().approvalGates??[]),Co=Ve(()=>rg.value.filter((e)=>e.status==="pending")),To=Ve(()=>{let e=og().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 _C(e){return(await so("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 os=Ve(()=>rg.value.filter((e)=>e.status==="held")),ig=Ve(()=>rg.value.filter((e)=>e.status==="approved"||e.status==="rejected")),CC=ie({events:[],evidence:[],steering:[]}),rs=ie("all");function b$(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 x$=new Set(["api","mcp","sdk","cli"]);function ng(e,t){if(e?.trim())return e.trim();let n=t?.trim();if(n&&!x$.has(n))return n;return null}var w$=/^(node|edge|group|annotation|jsonrender|graph|render)\.|^arrange$|^canvas\.clear$|^snapshot\.restore$/,TC=ie(null),Wl=ie(new Set),k$={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 S$(e,t=40,n=[],o=null,i="all"){let s=n.find((c)=>w$.test(c.op)),a=[...n.map((c)=>({id:`update-${c.id}`,kind:"update",label:"Update",body:c.summary,createdAt:c.at,who:c.sessionId??null,...!tt()&&o?.actor==="agent"&&s?.id===c.id?{undoable:!0}:{}})),...e.events.map((c)=>({id:`event-${c.id}`,kind:c.kind,label:k$[c.kind]??c.kind,body:c.detail?`${c.summary} — ${c.detail}`:c.summary,createdAt:c.createdAt,who:ng(c.agentId,c.source)})),...e.evidence.map((c)=>({id:`evidence-${c.id}`,kind:"evidence",label:"Evidence",body:c.body?`${c.title} — ${c.body}`:c.title,createdAt:c.createdAt,who:ng(c.agentId,c.source)})),...e.steering.map((c)=>{let u=c.agentId??(c.source&&c.source!=="browser"?c.source:null),d=c.target?`→ ${c.target} · `:u?"→ all · ":"",p=c.target&&c.delivered===!1?` — waiting for ${c.target} to pick it up`:"";return{id:`steer-${c.id}`,kind:"steer",label:"Steer",body:`${u?`${u} `:""}${d}${c.message}${p}`,createdAt:c.createdAt,who:ng(c.agentId,c.source)}})],l=i==="all"?a:a.filter((c)=>b$(c.kind)===i);return l.sort((c,u)=>c.createdAt<u.createdAt?1:c.createdAt>u.createdAt?-1:0),l.slice(0,t)}var IC=Ve(()=>S$(CC.value,40,fi.value,TC.value,rs.value));async function yi(){let[e,t]=await Promise.all([pe("refreshTimeline","/api/canvas/ax/timeline?limit=40",null),pe("refreshHistoryTop","/api/canvas/history",null)]);if(t)TC.value=t.top??null;if(!e)return;CC.value={events:Array.isArray(e.events)?e.events:[],evidence:Array.isArray(e.evidence)?e.evidence:[],steering:Array.isArray(e.steering)?e.steering:[]}}async function sg(e){if(!(await so("undoAgentEdit","/api/canvas/undo",{method:"POST"})).ok)return!1;return Wl.value=new Set([...Wl.value,e.id]),await oo("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"})}),yi(),!0}async function ag(e=!1){if(tt())return hn("remove","Undo / redo unavailable","Open the local PMX workbench to use shared history."),!1;let t=await so(e?"redo":"undo",e?"/api/canvas/redo":"/api/canvas/undo",{method:"POST"});if(t.ok)yi();return t.ok}async function EC(e,t){if(!(await so("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 oo("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 AC(e){return(await so("reopenGate",`/api/canvas/ax/approval/${encodeURIComponent(e.id)}/reopen`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser"})})).ok}async function ma(e,t){return(await so("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 vi(){if(!xt.value)return!1;return(await so("startSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"browser",label:da,attached:!0,phase:"idle"})})).ok}async function ql(e){return(await so("endSession","/api/canvas/ax/presence",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:e.source,agentId:e.agentId,attached:!1,endedBy:"human"})})).ok}var or=(e)=>JSON.stringify([e.boardId,e.id]);function Zl(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.boardId==="string"?{boardId:n.boardId}:{},...typeof n.reason==="string"?{reason:n.reason}:{},...typeof n.change==="string"?{change:n.change}:{},...typeof n.before==="string"?{before:n.before}:{},...typeof n.after==="string"?{after:n.after}:{}}]})}var Fn=ie(null),kC=(e)=>new Set(e.flat().map((t)=>typeof t==="string"?t:t.id)),lg=Ve(()=>{if(!xt.value)return null;let e=Fn.value;if(e?.kind==="live"){let n=en.value.find((o)=>o.attached&&o.sessionId===e.sessionId)?.session;return n?kC([n.read,n.pinned,n.created,n.edited]):null}let t=e?.kind==="receipt"?ns.value?.context:void 0;return t?kC([t.read,t.pinned,t.created,t.edited].map((n)=>n.filter((o)=>!o.boardId||o.boardId===se.value))):null}),RC=Ve(()=>new Set([...en.value.flatMap((e)=>e.attached?e.session?.edited??[]:[]),...ns.value?.context.edited.filter((e)=>!e.boardId||e.boardId===se.value).map((e)=>e.id)??[]]));function Gl(e,t){Fn.value=e?t?{kind:"live",...t}:{kind:"receipt"}:null}var ns=ie(null);function _$(e,t){let n=new Map(t.map((i)=>[or(i),i]));return[...e.map((i)=>{let s=n.get(or(i));if(!s)return i;return n.delete(or(i)),{...s,change:[i.change,s.change].filter(Boolean).join("; then "),before:i.before??s.before}}),...n.values()]}function Hd(e,t){let n=new Set(e.map(or));return[...e,...t.filter((o)=>!n.has(or(o)))]}function C$(e,t){return{labels:[...new Set([...e.labels,...t.labels])],sessions:e.sessions+1,startedAt:e.startedAt&&t.startedAt&&t.startedAt<e.startedAt?t.startedAt:e.startedAt,endedAt:t.endedAt,endedBy:e.endedBy===t.endedBy?t.endedBy:void 0,counts:t.counts,snapshot:null,context:{read:Hd(e.context.read,t.context.read),pinned:Hd(e.context.pinned,t.context.pinned),created:Hd(e.context.created,t.context.created),edited:_$(e.context.edited,t.context.edited),changedSinceRead:Hd(e.context.changedSinceRead,t.context.changedSinceRead)}}}function PC(e){let{counts:t,snapshot:n,context:o}=e;if(typeof e.label!=="string"||typeof e.endedAt!=="string")return;let i=Fn.value,s=i?.kind==="live"&&i.sessionId===e.writer;if(e.unchanged===!0||typeof e.parentAgentId==="string"){if(s)Fn.value=null;return}let a={labels:[e.label],sessions:1,startedAt:typeof e.startedAt==="string"?e.startedAt:null,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??""),boardId:typeof n.boardId==="string"?n.boardId:null}:null,context:{read:Zl(o?.read),pinned:Zl(o?.pinned),created:Zl(o?.created),edited:Zl(o?.edited),changedSinceRead:Zl(o?.changedSinceRead)}},l=ns.value;if(ns.value=l?C$(l,a):a,s)Fn.value={kind:"receipt"}}async function NC(e,t){let n=!0,o=[];for(let i of t){if(i.boardId&&i.boardId!==se.value)continue;let s=i.id,a=H.value.get(s);if(!a||a.lastEditedBy?.actor==="human")continue;let l=await pe("undoSessionEdit",`/api/canvas/snapshots/${encodeURIComponent(e)}/restore-node`,{ok:!1,restored:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nodeId:s,preserveHumanEdits:!0})});if(n=n&&l.ok,l.ok&&l.restored)o.push(s)}return{ok:n,restored:o}}function Ud(){if(ns.value=null,Fn.value?.kind==="receipt")Fn.value=null}function MC(){if(!_o.value)return null;let e=To.value;if(!e)return null;let t=H.value,n=e.nodeIds.map((s)=>t.get(s)).filter((s)=>s!==void 0),o=Fd(n,e.padding);if(!o)return null;let i=1/Math.max(0.05,Ee.value.scale);return r("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:[r("span",{class:"scope-fence-pill scope-fence-pill-top",style:{transform:`scale(${i})`},children:["Agent scope · ",n.length," node",n.length===1?"":"s"]},void 0,!0,void 0,this),r("span",{class:"scope-fence-pill scope-fence-pill-bottom",style:{transform:`scale(${i})`},children:"writes outside are blocked · reads allowed"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var T$=U().trim().min(1).max(80),CG=U().trim().max(4000),I$=Pi({kind:T$,ink:mn(["supports","contradicts","cites","derived","informs","related"]),directed:ht()}),E$=We(I$).max(64).refine((e)=>new Set(e.map((t)=>t.kind)).size===e.length,"Relation kinds must be unique."),TG=Pi({id:U().trim().min(1),name:U().trim().min(1).max(80),vocabulary:E$}),Kl=[{kind:"supports",ink:"supports",directed:!0},{kind:"contradicts",ink:"contradicts",directed:!0},{kind:"cites",ink:"cites",directed:!0},{kind:"derived-from",ink:"derived",directed:!0},{kind:"answers",ink:"informs",directed:!0},{kind:"depends-on",ink:"informs",directed:!0},{kind:"supersedes",ink:"informs",directed:!0},{kind:"flow",ink:"derived",directed:!0},{kind:"related",ink:"related",directed:!1}],A$={Research:Kl.filter((e)=>["supports","contradicts","cites","derived-from","related"].includes(e.kind)),Dependencies:Kl.filter((e)=>["depends-on","related"].includes(e.kind)),Decision:[{kind:"option",ink:"derived",directed:!0},{kind:"if",ink:"cites",directed:!0},{kind:"rejected",ink:"related",directed:!0},{kind:"supersedes",ink:"informs",directed:!0}],Flow:[{kind:"next",ink:"derived",directed:!0},{kind:"if-fails",ink:"contradicts",directed:!0},{kind:"loop",ink:"related",directed:!0}]};function zC(e=[]){return Object.entries(A$).find(([,t])=>t.length===e.length&&t.every((n)=>e.some((o)=>o.kind===n.kind&&o.ink===n.ink&&o.directed===n.directed)))?.[0]??null}function Gn(e){return e.kind??(e.type==="relation"?"related":e.type==="references"?"cites":e.type??"related")}function jd(e){let t=Gn(e);if(t==="depends-on")return"to";if(["derived-from","contradicts","supersedes"].includes(t))return"from";return null}function mo(e,t=[]){let n=Gn(e);return t.find((o)=>o.kind===n)??Kl.find((o)=>o.kind===n)??{kind:n,ink:"related",directed:!0}}function ha(e){return`${e.kind??e.type??"related"}${e.label?` "${e.label}"`:""}${e.reason?` (why: ${e.reason})`:""}`}var Io=ie(null);sn(()=>{let e=Io.value;if(e?.boardId===se.value&&![...et.value.values()].some((t)=>Gn(t)===e.kind))Io.value=null});var cg=Ve(()=>gt.value),Vl=Ve(()=>{let e=zC(Yn()?.relationVocabulary),t=cg.value,n=Io.value?.boardId===se.value?Io.value.kind:null,o=[...et.value.values()].filter((c)=>!c.toBoardId||c.toBoardId===se.value),i=new Set(st.value);if(t)i.add(t);if(i.size===0&&!n)return null;for(let c of i){let u=H.value.get(c);if(u?.type==="group"&&Array.isArray(u.data.children)){for(let d of u.data.children)if(typeof d==="string")i.add(d)}}let s=new Set(i),a=new Set,l=(c)=>{a.add(c.id),s.add(c.from),s.add(c.to)};if(!n){for(let c of o)if(i.has(c.from)&&i.has(c.to))l(c)}if(n){for(let c of o)if(Gn(c)===n)l(c)}else if(e==="Dependencies"||e==="Decision"){let c=!0;while(c){c=!1;for(let u of o){if(a.has(u.id))continue;let d=jd(u);if(e==="Dependencies"?d&&s.has(d==="from"?u.from:u.to):["option","if","chosen"].includes(Gn(u))&&s.has(u.to))l(u),c=!0}}}else if(e==="Flow"){let c=new Set;for(let u of H.value.values())if(["done","in-progress","blocked"].includes(String(u.data.axWorkStatus)))c.add(u.id),s.add(u.id);for(let u of o)if(["flow","next","if-fails","loop"].includes(Gn(u))&&c.has(u.from))l(u)}else for(let c of o)if((i.has(c.from)||i.has(c.to))&&(e!=="Research"||["supports","contradicts","cites","derived-from"].includes(Gn(c))))l(c);return{cards:s,links:a}});function $C(){let e=se.value,t=Ge.value,n=H.value,o=et.value,i=Oe.value;return q(()=>{let s=setTimeout(()=>void Kt(),100);return()=>clearTimeout(s)},[e,t,n,o,i]),q(()=>{let s=setInterval(()=>void Kt(),60000);return()=>clearInterval(s)},[]),null}function LC(){if(!Oe.value)return null;let e=[...H.value.keys()].map(Jn);return r(be,{children:[r("div",{class:"lifecycle-filters",role:"group","aria-label":"Lifecycle filter",children:[["All","To review","Retired"].map((t)=>r("button",{type:"button","aria-pressed":Ro.value===t,onClick:()=>{if(!Oe.value)return;Ro.value=t},children:[t,t==="All"?"":` · ${e.filter((n)=>t==="Retired"?n?.retired:!n?.retired&&(n?.due||n?.sources.length)).length}`]},t,!0,void 0,this)),Oi.value&&r("span",{role:"status",children:"Qualification unavailable"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(R$,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function R$(){let e=Is.value,[t,n]=E(!1);if(!Oe.value||!e||e.boardId!==se.value||e.incarnation!==wt||Ct.value||!Jn(e.nodeId)?.retired)return null;return r("div",{class:"retirement-toast",role:"status",children:[r("span",{children:"Retired from active context. History kept."},void 0,!1,void 0,this),r("button",{type:"button",disabled:t,onClick:async()=>{if(t||!Oe.value)return;if(n(!0),(await pe("restore",`/api/canvas/node/${encodeURIComponent(e.nodeId)}/lifecycle/restore`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedBoardId:e.boardId,evidence:"Human undid retirement."})}))?.ok)Is.value=null,await Kt();n(!1)},children:"Undo retirement"},void 0,!1,void 0,this),r("button",{type:"button","aria-label":"Dismiss retirement notice",onClick:()=>{Is.value=null},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Zd({nodeId:e}){if(!Oe.value)return null;let t=Jn(e);if(!t||t.retired||!t.due&&t.sources.length===0)return null;let n=t.sources[0];return r("button",{type:"button",class:"node-lifecycle-warning",onClick:(o)=>{o.stopPropagation(),Es(e)},children:[r("span",{children:t.due?"⧗ review due":"⧗ source needs review"},void 0,!1,void 0,this),r("span",{children:t.due?t.reasons[0]:`${n.title} · ${n.reasons[0]}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Wd({node:e}){let t=[...et.value.values()].filter((i)=>i.toBoardId&&i.from===e.id),n=se.value,o=Ge.value.find((i)=>i.id===n);if(!t.length)return null;return r("div",{class:"node-memory-links",role:"region","aria-label":"Cross-board references",tabIndex:0,onWheel:(i)=>{if(!i.ctrlKey&&!i.metaKey)i.stopPropagation()},onKeyDown:(i)=>{if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"," "].includes(i.key))i.stopPropagation()},children:t.map((i)=>{let s=Ge.value.find((l)=>l.id===i.toBoardId),a=o?.links?.find((l)=>l.kind==="card"&&l.nodeId===e.id&&l.boardId===i.toBoardId&&l.cardId===i.to);return r("div",{class:"node-memory-link",children:r("button",{type:"button",disabled:!s||a?.missing===!0,onClick:async(l)=>{l.stopPropagation();let c=document.activeElement;if(c instanceof HTMLElement&&c.isContentEditable)c.blur();if(e.type==="markdown"&&!await sh(n,e.id))return;await zt({boardId:i.toBoardId,cardId:i.to})},children:["↗ ",i.label||i.type,": ",s?.name??"Missing board"," /"," ",a?.cardTitle??(a?.missing?"Missing card":"Loading card…")]},void 0,!0,void 0,this)},i.id,!1,void 0,this)})},void 0,!1,void 0,this)}function ho({board:e,inNodeHeader:t=!1}){let n=!!e.pin;return r("button",{type:"button",class:`ctx-pin-btn${t?"":" board-pin-btn"}${n?" ctx-pin-active":""}`,onClick:(i)=>{i.stopPropagation(),$s(e.id,!n)},"aria-label":n?"Unpin board from the agent's context":"Pin board to the agent's context","aria-pressed":n,"data-testid":"board-pin",children:r("span",{class:"ctx-pin-mark",children:[r(uo,{},void 0,!1,void 0,this),n&&e.pin?.pinnedBy.actor==="agent"&&r("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)}function P$(e){let t=typeof e==="number"&&Number.isFinite(e)?Math.floor(e):1;return Math.max(1,Math.min(20,t))}function qd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xl(e){return typeof e==="string"&&e.length>0}function OC(e){let t=e.axStep;if(!qd(t))return null;if(!Xl(t.flowId)||!Xl(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 DC(e){let t=e.axFlow;if(!qd(t)||!Xl(t.flowId)||!Array.isArray(t.steps))return null;let n=[];for(let i of t.steps){if(!qd(i)||!Xl(i.nodeId)||!Xl(i.workItemId))return null;if(typeof i.index!=="number")return null;n.push({index:i.index,nodeId:i.nodeId,workItemId:i.workItemId,title:typeof i.title==="string"?i.title:""})}if(n.length===0)return null;let o=qd(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:P$(o.maxRuns)}}}var N$={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)"},FC={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},HC={fontSize:"10px",color:"var(--c-muted)",textTransform:"uppercase",letterSpacing:"0.04em",marginRight:"auto"},UC={...Gi,background:"color-mix(in srgb, var(--c-accent) 25%, transparent)",color:"var(--c-text)"},M$=[{status:"in-progress",label:"Start",toast:"Step started"},{status:"done",label:"Done",toast:"Step done"},{status:"blocked",label:"Blocked",toast:"Step blocked"}];async function BC(e,t,n){let o={...t,loop:n};Xe(e.id,{axFlow:o}),await ln(e.id,{data:{axFlow:o}})}function jC(e){return typeof e?.axWorkStatus==="string"?e.axWorkStatus:"todo"}function z$({node:e,flow:t}){let[n,o]=E(""),{running:i,run:s,maxRuns:a}=t.loop,l=async()=>{await BC(e,t,{running:!0,run:s>=a?0:s,maxRuns:a});let u=t.steps.find((p)=>jC(H.value.get(p.nodeId)?.data)!=="done"),d=u??t.steps[t.steps.length-1];await ii(e,"ax.work.update",{id:d.workItemId,status:u?"in-progress":"done"},"Loop running")},c=async()=>{let u=n.trim();if(!u)return;await ii(e,"ax.steer",{message:u},"Steering sent"),o("")};return r("div",{class:"ax-flow-controls",style:{...FC,marginTop:"6px",rowGap:"4px"},children:[r("span",{class:"ax-flow-runs",style:HC,children:i?`Loop running · run ${s+1}/${a}`:`Loop idle · ${s}/${a} runs`},void 0,!1,void 0,this),i?r(_e,{label:"Stop the loop now",body:"The stop is persisted on this node, so it survives a refresh and no further step is opened.",side:"up",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action",style:UC,onClick:(u)=>{u.stopPropagation(),BC(e,t,{...t.loop,running:!1})},children:"Stop"},void 0,!1,void 0,this)},void 0,!1,void 0,this):r(_e,{label:"Run this flow as a loop",body:"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.",side:"up",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action",style:Gi,onClick:(u)=>{u.stopPropagation(),l()},children:"Run loop"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("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(),c()},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),r(_e,{label:"Send a steering message to the agent working this flow",side:"up",align:"end",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action",style:Gi,onClick:(u)=>{u.stopPropagation(),c()},children:"Steer"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Gd({node:e}){let t=OC(e.data);if(!t)return null;let n=DC(e.data),o=jC(e.data);return r("div",{class:"ax-step-dock",style:N$,children:[r("div",{class:"ax-step-controls",style:FC,children:[r("span",{class:"ax-step-position",style:HC,children:["Step ",t.index,"/",t.total]},void 0,!0,void 0,this),M$.map((i)=>r(_e,{label:`Set this step's work item to "${i.status}"`,side:"up",fitWithin:".node-content, .expanded-overlay-panel",children:r("button",{type:"button",class:"ax-node-action","aria-pressed":o===i.status,style:o===i.status?UC:Gi,onClick:(s)=>{s.stopPropagation(),ii(e,"ax.work.update",{id:t.workItemId,status:i.status},i.toast)},children:i.label},void 0,!1,void 0,this)},i.status,!1,void 0,this))]},void 0,!0,void 0,this),n&&r(z$,{node:e,flow:n},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ga=8,is=ie(null),ya=[],va=[],qC=null;function ZC(e){let t=e?.data.parentGroup;return typeof t==="string"&&t.length>0?t:null}function WC(e){if(!e||!Array.isArray(e.data.children))return[];return e.data.children.filter((t)=>typeof t==="string")}function $$(e,t){let n=new Map(t.map((l)=>[l.id,l])),o=new Set([e]),i=n.get(e);if(!i)return o;let s=ZC(i);while(s&&!o.has(s))o.add(s),s=ZC(n.get(s));if(i.type!=="group")return o;let a=[...WC(i)];while(a.length>0){let l=a.pop();if(!l||o.has(l))continue;o.add(l);let c=n.get(l);if(c?.type==="group")a.push(...WC(c))}return o}function GC(e,t){ya=[],va=[],qC=e;let n=Array.from(t),o=$$(e,n);for(let i of n){if(o.has(i.id))continue;let s=i.position.x,a=i.position.x+i.size.width,l=i.position.x+i.size.width/2,c=i.position.y,u=i.position.y+i.size.height,d=i.position.y+i.size.height/2;ya.push({val:s,minY:c,maxY:u}),ya.push({val:a,minY:c,maxY:u}),ya.push({val:l,minY:c,maxY:u}),va.push({val:c,minX:s,maxX:a}),va.push({val:u,minX:s,maxX:a}),va.push({val:d,minX:s,maxX:a})}}function KC(){ya=[],va=[],qC=null}function VC(e,t,n,o){let i=[e,e+n/2,e+n],s=[t,t+o/2,t+o],a=[0,n/2,n],l=[0,o/2,o],c=null,u=ga+1,d=null;for(let g=0;g<3;g++){let v=i[g];for(let b of ya){let x=Math.abs(v-b.val);if(x<u)u=x,c=b.val-a[g],d={axis:"x",pos:b.val,from:Math.min(b.minY,t),to:Math.max(b.maxY,t+o)}}}let p=null,f=ga+1,m=null;for(let g=0;g<3;g++){let v=s[g];for(let b of va){let x=Math.abs(v-b.val);if(x<f)f=x,p=b.val-l[g],m={axis:"y",pos:b.val,from:Math.min(b.minX,e),to:Math.max(b.maxX,e+n)}}}let h=[];if(d&&u<=ga)h.push(d);if(m&&f<=ga)h.push(m);return{x:c!==null&&u<=ga?c:e,y:p!==null&&f<=ga?p:t,guides:h}}function XC({nodeId:e,viewport:t,onMove:n,onDragEnd:o,onClick:i}){let s=D(!1),a=D({x:0,y:0}),l=D({x:0,y:0});return oe((u,d,p)=>{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},l.current={x:d,y:p};let f=null,m=null,h=!1,g=()=>{if(m=null,!s.current||!f)return;let x=f;f=null;let C=t.value.scale,y=(x.x-a.current.x)/C,k=(x.y-a.current.y)/C;n(e,l.current.x+y,l.current.y+k)},v=(x)=>{if(!s.current)return;if(!h&&Math.hypot(x.clientX-u.clientX,x.clientY-u.clientY)<4)return;if(!h)document.documentElement.classList.add("is-node-moving");if(h=!0,f={x:x.clientX,y:x.clientY},m!==null)return;m=window.requestAnimationFrame(g)},b=(x)=>{if(m!==null)window.cancelAnimationFrame(m),g();if(s.current=!1,document.documentElement.classList.remove("is-node-dragging","is-node-moving"),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",b),o(),!h&&x.type==="pointerup")i?.()};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",b)},[e,t,n,o,i])}var L$=200,O$=100;function JC({nodeId:e,viewport:t,onResize:n,onResizeEnd:o}){let i=D(!1),s=D({x:0,y:0}),a=D({w:0,h:0});return oe((c,u,d)=>{c.stopPropagation(),c.preventDefault(),i.current=!0,s.current={x:c.clientX,y:c.clientY},a.current={w:u,h:d},document.documentElement.classList.add("is-node-resizing");let p=null,f=null,m=()=>{if(f=null,!i.current||!p)return;let v=p;p=null;let b=t.value.scale,x=(v.x-s.current.x)/b,C=(v.y-s.current.y)/b;n(e,Math.max(L$,a.current.w+x),Math.max(O$,a.current.h+C))},h=(v)=>{if(!i.current)return;if(p={x:v.clientX,y:v.clientY},f!==null)return;f=window.requestAnimationFrame(m)},g=()=>{if(f!==null)window.cancelAnimationFrame(f),m();i.current=!1,document.documentElement.classList.remove("is-node-resizing"),document.removeEventListener("pointermove",h),document.removeEventListener("pointerup",g),document.removeEventListener("pointercancel",g),o()};document.addEventListener("pointermove",h),document.addEventListener("pointerup",g),document.addEventListener("pointercancel",g)},[e,t,n,o])}var D$={ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1}};function B$(e,t,n){let o=e.position.x+e.size.width/2,i=e.position.y+e.size.height/2,s=null,a=Number.POSITIVE_INFINITY;for(let l of n){if(l.id===e.id)continue;let c=l.position.x+l.size.width/2-o,u=l.position.y+l.size.height/2-i,d=c*t.dx+u*t.dy;if(d<=0)continue;let p=Math.abs(c*t.dy)+Math.abs(u*t.dx);if(p>d)continue;let f=d+p*2;if(f<a)a=f,s=l}return s}var F$=0.4,H$=0.55,U$=175;function j$(e,t,n=0){if(!Number.isFinite(e)||e>=1)return 1;let i=Math.min(2.2,1/Math.max(e,0.01));if(Number.isFinite(t)&&t>0)i=Math.min(i,t*F$/Js);if(Number.isFinite(n)&&n>0)i=Math.min(i,n*H$/U$);return Math.max(1,i)}var Z$=140;function W$(e,t,n,o,i){let[s,a]=E("word"),l=`${n}\x00${t?t.amber?"amber":t.folded:""}\x00${o}\x00${i.toFixed(3)}`,c=D(l);return Me(()=>{if(c.current!==l){if(c.current=l,s!=="word"){a("word");return}}let u=e.current;if(!u||!t||t.amber||s==="hidden")return;let d=Math.min(u.scrollWidth,Z$*i);if(u.clientWidth+0.5<d)a(s==="word"?"glyph":"hidden")},[l,s]),t?s:"word"}function YC({node:e,children:t,onContextMenu:n}){let o=gt.value===e.id,i=st.value.has(e.id),s=kt.value.has(e.id),a=D(null),l=D(null),c=e.type==="board"&&typeof e.data.boardId==="string"?Ge.value.find((W)=>W.id===e.data.boardId)??null:null,u=tu.value.has(e.id),d=!o&&Bk.value.has(e.id),p=wr.value,f=p!==null&&p.has(e.id),m=p!==null&&!p.has(e.id),[h,g]=E(!1),v=D(null),b=oe((W,ye,He)=>{let R=VC(ye,He,e.size.width,e.size.height),ne=H.value.get(W);if(ne?.position.x===R.x&&ne.position.y===R.y){is.value=R.guides.length>0?R.guides:null;return}un(W,{position:{x:R.x,y:R.y}}),is.value=R.guides.length>0?R.guides:null,Zk(W)},[e.size.width,e.size.height]),x=D(null),C=oe(()=>{if(KC(),is.value=null,jf(null),sk(e.id),x.current)document.removeEventListener("keydown",x.current),x.current=null;dn();let W=Xo.value;if(jk(),!W||W.nodeId!==e.id)return;if(W.mode==="add")tm(W.groupId,[e.id]);else{let ye=H.value.get(W.groupId),He=Array.isArray(ye?.data.children)?ye.data.children.filter((R)=>typeof R==="string"&&R!==e.id):[];xu(W.groupId,He)}},[e.id]),y=XC({nodeId:e.id,viewport:Ee,onMove:b,onDragEnd:C,onClick:()=>{st.value=new Set([e.id])}}),k=oe((W,ye,He)=>{let R=H.value.get(W);if(R?.size.width===ye&&R.size.height===He)return;un(W,{size:{width:ye,height:He}})},[]),_=oe(()=>{Xe(e.id,{userResized:!0}),ln(e.id,{data:{userResized:!0}}),dn()},[e.id]),I=JC({nodeId:e.id,viewport:Ee,onResize:k,onResizeEnd:_}),w=oe((W)=>{W.stopPropagation(),W.preventDefault(),At.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]),P=oe((W)=>{if(W.button!==0)return;if(h)return;if(W.target instanceof Element&&W.target.closest("button, input")){W.stopPropagation();return}if(Wn.value==="connect"){w(W);return}if(W.shiftKey){W.stopPropagation(),sm(e.id);return}if(Sr(e.id),jf(e.id),ik(e.id),Yw(e.id,typeof e.data.title==="string"&&e.data.title?e.data.title:e.type),GC(e.id,H.value.values()),e.type!=="group"){let ye=(He)=>{if(He.key==="Escape")Uk()};x.current=ye,document.addEventListener("keydown",ye)}y(W,e.position.x,e.position.y)},[e.id,e.type,e.data.title,e.position.x,e.position.y,y,h,w]),L=oe((W)=>{if(W.button!==0)return;if(W.stopPropagation(),Wn.value==="connect"){w(W);return}if(W.shiftKey){sm(e.id);return}Sr(e.id)},[e.id,w]),N=oe((W)=>{if((W.target instanceof Element?W.target:null)?.closest('button, input, textarea, select, a, [contenteditable="true"]'))return;if(n)n(W,e.id)},[n,e.id]),Y=oe((W)=>{let ye=W.target;if(ye&&ye!==W.currentTarget&&ye.closest('input, textarea, [contenteditable="true"]'))return;let He=D$[W.key];if(He){W.preventDefault();let R=B$(e,He,H.value.values());if(!R)return;Sr(R.id),requestAnimationFrame(()=>{document.querySelector(`.canvas-node[data-node-id="${CSS.escape(R.id)}"]`)?.focus()})}else if(W.key==="Enter"&&W.target===W.currentTarget&&Ga.has(e.type))W.preventDefault(),xo(e.id)},[e]),B=e.data.title||(e.type==="file"?(e.data.path||e.data.content||"").split(/[\\/]/).pop()??"":"")||an[e.type],J=oe((W)=>{let ye=W.trim();if(ye&&ye!==B)Xe(e.id,{title:ye}),ln(e.id,{title:ye});g(!1)},[e.id,B]),X=D(null),V=D(!1),ee=D(null);q(()=>{if(V.current||!uh(e))return;let W=X.current;if(!W)return;let ye=new ResizeObserver(()=>{if(V.current){ye.disconnect();return}let He=W.scrollHeight,R=o_(e,He);if(R===null)return;if(Math.abs(R-e.size.height)>8){if(Tu(e.id,{width:e.size.width,height:R}),ee.current!==null)window.clearTimeout(ee.current);ee.current=window.setTimeout(()=>{dn({recordHistory:!1}),ee.current=null},0)}V.current=!0,ye.disconnect()});return ye.observe(W),()=>{if(ye.disconnect(),ee.current!==null)window.clearTimeout(ee.current),ee.current=null}},[e.id,e.type,e.data.mode,e.data.strictSize,e.collapsed,e.size.width,e.size.height]);let he=e.pinned,A=e.type==="trace",te=A&&e.data.status==="running",M=e.type==="group",O=e.data.strictSize===!0,Pe=Math.max(Ee.value.scale,0.01),Fe=j$(Pe,e.collapsed?0:e.size.height,e.size.width),De=W$(a,eg(e,s),B,e.size.width,Fe),Ae=M&&e.data.color?e.data.color:void 0,ve={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":Fe.toFixed(3),"--node-port-scale":(1/Pe).toFixed(3),...Ae?{"--group-color":Ae}:{}},z=tr.value&&Ld.value.has(e.id),re=["canvas-node",o?"active":"",d?"neighbor":"",f?"search-match":"",m?"search-dimmed":"",i?"selected":"",s?"context-pinned":"",u?"attention-pulse":"",he?"pinned":"",A?"trace-node":"",te?"trace-running":"",M?"group-node":"",O?"strict-size":"",z?"agent-mutating":"",tr.value&&RC.value.has(e.id)?"session-edited":"",lg.value&&!lg.value.has(e.id)?"lens-dimmed":"",Vl.value&&!Vl.value.cards.has(e.id)?"relation-dimmed":"",Oe.value&&Jn(e.id)?.retired?"lifecycle-retired":"",Zf.value==="To review"&&!Jn(e.id)?.due&&!Jn(e.id)?.sources.length?"lifecycle-filter-dimmed":"",Zf.value==="Retired"&&!Jn(e.id)?.retired?"lifecycle-filter-dimmed":""].filter(Boolean).join(" "),Ne=M?(Array.isArray(e.data.children)?e.data.children:[]).filter((W)=>typeof W==="string"&&H.value.has(W)):[],[ke,ae]=E(!1),Se=Xo.value,de=M&&Se?.groupId===e.id&&Se.mode==="add",Ue=M&&Se?.groupId===e.id&&Se.mode==="remove",xe=At.value?.targetId===e.id,qe=M?[...new Set(Ne.map((W)=>H.value.get(W)?.type).filter((W)=>!!W))].slice(0,4):[];if(M&&e.collapsed)return r("div",{class:`${re} group-chip`,"data-node-type":e.type,style:{...ve,width:"auto",height:"auto"},onPointerDown:L,onDblClick:N,"data-testid":"group-chip",children:[r("div",{class:"node-titlebar group-chip-inner",onPointerDown:P,children:[r("button",{type:"button",class:"group-chip-expand","aria-label":`Expand group ${B}`,onClick:(W)=>{W.stopPropagation(),Hi(e.id)},children:r(oi,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"group-chip-text",children:[r("div",{class:"group-chip-name",children:B},void 0,!1,void 0,this),r("div",{class:"group-chip-meta",children:[qe.map((W)=>r("span",{class:"group-kind-dot","aria-hidden":"true"},W,!1,void 0,this)),r("span",{class:"group-chip-count",children:[Ne.length," node",Ne.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),r(Zd,{nodeId:e.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("div",{class:"canvas-node-owner",style:{...ve,zIndex:"auto"},onPointerEnter:()=>{el.value=e.id},onPointerLeave:()=>{if(el.value===e.id)el.value=null},children:[M&&r("div",{class:"group-frame-hit","aria-hidden":"true",style:{zIndex:`calc(${e.zIndex} - var(--node-hit-offset, 3))`},onPointerDown:(W)=>{if(L(W),W.button===0&&!W.shiftKey)l.current?.focus({preventScroll:!0})},onMouseDown:(W)=>{if(W.button===0||W.shiftKey)W.preventDefault()},onDblClick:N},void 0,!1,void 0,this),r("div",{ref:l,class:`${re}${de?" is-drop-target":""}${Ue?" is-drop-source":""}${xe?" is-edge-target":""}${M&&ke?" group-menu-open":""}`,"data-node-type":e.type,"data-node-id":e.id,style:{position:"relative",left:0,top:0,width:"100%",height:e.collapsed?"auto":"100%",zIndex:e.zIndex},tabIndex:o?0:-1,onKeyDown:Y,onPointerDown:L,onMouseDown:(W)=>{if(W.shiftKey)W.preventDefault()},onDblClick:N,children:[r("div",{class:"node-content",children:[M&&r("div",{class:"node-titlebar group-edge-row",onPointerDown:P,children:[r("span",{class:"group-name-pill",children:[h?r("input",{ref:v,class:"node-title-input group-title-input",value:B,onBlur:(W)=>J(W.target.value),onKeyDown:(W)=>{if(W.key==="Enter")J(W.target.value);if(W.key==="Escape")g(!1)},onClick:(W)=>W.stopPropagation()},void 0,!1,void 0,this):r("span",{class:"group-name",children:B},void 0,!1,void 0,this),r("span",{class:"group-count",children:Ne.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"group-edge-spacer"},void 0,!1,void 0,this),r("span",{class:"group-actions",role:"toolbar","aria-label":`${B} actions`,children:[r(_e,{label:"Auto-arrange children",align:"end",children:r("button",{type:"button",class:"group-action","aria-label":"Auto-arrange children",disabled:Ne.length===0,onClick:(W)=>{W.stopPropagation(),tm(e.id,Ne,"grid")},children:r("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[r("rect",{x:"1.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"9.5",y:"1.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"1.5",y:"9.5",width:"5",height:"5",rx:"1"},void 0,!1,void 0,this),r("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)},void 0,!1,void 0,this),r(_e,{label:"Collapse group",align:"end",children:r("button",{type:"button",class:"group-action","aria-label":"Collapse group",onClick:(W)=>{W.stopPropagation(),Hi(e.id)},children:r("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:r("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)},void 0,!1,void 0,this),r("button",{type:"button",class:"group-action","aria-label":"Group menu","aria-expanded":ke,onClick:(W)=>{W.stopPropagation(),ae((ye)=>!ye)},children:r(ml,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),ke&&r("div",{class:"group-menu",role:"menu",onPointerDown:(W)=>W.stopPropagation(),children:[r("button",{type:"button",role:"menuitem",onClick:(W)=>{W.stopPropagation(),ae(!1),g(!0),requestAnimationFrame(()=>v.current?.focus())},children:"Rename"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",onClick:(W)=>{W.stopPropagation(),ae(!1),ei(e.id),Ms(e.id)},children:"Ungroup"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",disabled:Ne.length===0,onClick:(W)=>{W.stopPropagation(),ae(!1),_u(Ne)},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),!M&&r("div",{class:"node-titlebar",onPointerDown:P,children:[r(hC,{node:e,pinned:s,title:B,fold:De,children:(()=>{let W=Do(e.type);return r(W,{size:Math.round(14*Fe)},void 0,!1,void 0,this)})()},void 0,!1,void 0,this),typeof e.data.axWorkStatus==="string"&&r("span",{class:`node-ax-status node-ax-status-${e.data.axWorkStatus}`,children:e.data.axWorkStatus},void 0,!1,void 0,this),h?r("input",{ref:v,class:"node-title-input",value:B,onBlur:(W)=>J(W.target.value),onKeyDown:(W)=>{if(W.key==="Enter")J(W.target.value);if(W.key==="Escape")g(!1)},onClick:(W)=>W.stopPropagation()},void 0,!1,void 0,this):r("span",{ref:a,class:"node-title",children:B},void 0,!1,void 0,this),r(yC,{node:e,pinned:s,fold:De},void 0,!1,void 0,this),r(mC,{node:e,pinned:s,fold:De},void 0,!1,void 0,this),r("div",{class:"node-controls",children:[he&&r(_e,{label:"Pinned in place",align:"end",fitWithin:".node-content",tapToOpen:!0,children:r("span",{class:"pin-indicator",children:"⊙"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Ga.has(e.type)&&r(_e,{label:"Expand (focus mode)",align:"end",fitWithin:".node-content",children:r("button",{type:"button",onClick:(W)=>{W.stopPropagation(),xo(e.id)},"aria-label":"Expand (focus mode)",children:r(cS,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e.type==="board"?c&&r(ho,{board:c,inNodeHeader:!0},void 0,!1,void 0,this):r(_e,{label:s?"Remove from context":"Add to context",align:"end",fitWithin:".node-content",children:r("button",{type:"button",class:`ctx-pin-btn${s?" ctx-pin-active":""}`,onClick:(W)=>{W.stopPropagation(),lo(e.id)},"aria-label":s?"Remove from context":"Add to context","aria-pressed":s,children:r("span",{class:"ctx-pin-mark",children:[r(uo,{},void 0,!1,void 0,this),s&&gC(e.id)&&r("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)},void 0,!1,void 0,this),r("button",{type:"button",class:"node-hover-control",onClick:(W)=>{W.stopPropagation(),n?.(W,e.id)},"aria-label":"More actions",children:r(ml,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",class:"node-hover-control",onClick:(W)=>{W.stopPropagation(),Xr(e.id)},"aria-label":"Close",children:r(Tt,{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&&r("div",{ref:X,class:"node-body",children:[t,r(Gd,{node:e},void 0,!1,void 0,this),!M&&r(Zd,{nodeId:e.id},void 0,!1,void 0,this),r(Wd,{node:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(e.collapsed||M)&&r(Zd,{nodeId:e.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!e.collapsed&&r("div",{class:"node-resize-handle",onPointerDown:(W)=>I(W,e.size.width,e.size.height)},void 0,!1,void 0,this),i&&["tl","tr","bl","br"].map((W)=>r("span",{class:`node-selection-handle is-${W}`,"aria-hidden":"true"},W,!1,void 0,this)),$i.value.has(e.id)&&r("span",{class:"node-yield-pill","data-testid":"yield-pill",children:[r("span",{class:"node-yield-dot","aria-hidden":"true"},void 0,!1,void 0,this),$i.value.get(e.id)," took over — agent yielded"]},void 0,!0,void 0,this),!M&&["top","right","bottom","left"].map((W)=>r("span",{class:`node-port-dot node-port-dot-${W}`,"aria-hidden":"true"},W,!1,void 0,this))]},void 0,!0,void 0,this),!M&&["top","right","bottom","left"].map((W)=>r("div",{class:`node-port node-port-${W}`,onPointerDown:(ye)=>{if(ye.button!==0)return;ye.stopPropagation(),ye.preventDefault(),ye.currentTarget.setPointerCapture(ye.pointerId);let He=e.position.x+e.size.width/2,R=e.position.y+e.size.height/2,ne=e.size.width/2,Ce=e.size.height/2,Te,fe;switch(W){case"top":Te=He,fe=R-Ce;break;case"bottom":Te=He,fe=R+Ce;break;case"left":Te=He-ne,fe=R;break;case"right":Te=He+ne,fe=R;break}At.value={fromId:e.id,fromX:Te,fromY:fe,cursorX:Te,cursorY:fe}}},W,!1,void 0,this))]},void 0,!0,void 0,this)}function Kd({node:e}){let t=typeof e.data.boardId==="string"?e.data.boardId:"",n=Ge.value.find((o)=>o.id===t);return r("div",{class:"board-node",children:[r("div",{class:"board-node-content",children:[r("div",{class:"board-node-label",children:"Linked board"},void 0,!1,void 0,this),r("strong",{class:"board-node-title",children:n?.name??"Missing board"},void 0,!1,void 0,this),r("div",{class:"board-node-meta",children:n?`${n.nodeCount} nodes${n.pin?" · pinned, so it travels with you":""}`:t||"No target id"},void 0,!1,void 0,this),n?.summary&&r("p",{class:"board-node-summary",children:n.summary},void 0,!1,void 0,this),!!n?.pinnedTitles?.length&&r("p",{class:"board-node-meta",children:["Pinned: ",n.pinnedTitles.map((o)=>o.title).join(", ")]},void 0,!0,void 0,this),!!n?.backlinks?.length&&r("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),r("button",{class:"board-node-open",type:"button",disabled:!n,onClick:()=>n&&void Mn(n.id),children:[n?"Open board":"Target unavailable",n&&r(ri,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function QC(){let e=Yn(),t=[...et.value.values()],n=D(null);if(q(()=>{let s=n.current;if(!s)return;let a=new ResizeObserver(()=>void Jr());return a.observe(s),()=>a.disconnect()},[e?.id,t.length>0]),!e||t.length===0)return null;let o=[...new Set(t.map(Gn))],i=Io.value?.boardId===e.id?Io.value.kind:null;return r("div",{ref:n,class:"relation-legend","aria-label":"Relation legend",onPointerDown:(s)=>s.stopPropagation(),children:[r("select",{"aria-label":"Filter board relations",value:i??"",onChange:(s)=>{let a=s.currentTarget.value;Io.value=a?{boardId:e.id,kind:a}:null},children:[r("option",{value:"",children:"All relations"},void 0,!1,void 0,this),o.map((s)=>r("option",{value:s,children:[s," · ",t.filter((a)=>Gn(a)===s).length]},s,!0,void 0,this))]},void 0,!0,void 0,this),o.map((s)=>{let a=mo({kind:s},e.relationVocabulary);return r("button",{type:"button","aria-pressed":i===s,style:{"--relation-ink":`var(--c-rel-${a.ink})`},onClick:()=>{Io.value=i===s?null:{boardId:e.id,kind:s}},children:[r("span",{class:"relation-swatch","aria-hidden":"true"},void 0,!1,void 0,this),s," ",r("span",{class:"relation-count",children:t.filter((l)=>Gn(l)===s).length},void 0,!1,void 0,this)]},s,!0,void 0,this)})]},void 0,!0,void 0,this)}function eT(){let e=mi.value?.label;return e&&e!==da?e:"the agent"}var pg=ie(null);function ug(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":` · ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function dg(e){return e.actor==="agent"?Nr(e):"you"}function q$(e,t){if(e.changedBy?.actor!=="agent"&&e.changedBy?.actor!=="human")return null;let n=dg(e.changedBy),i=!!e.createdBy&&dg(e.createdBy)!==n?`${n==="you"?"You":n} relabelled it${ug(e.changedAt)} (drawn by ${e.createdBy?dg(e.createdBy):""}${ug(e.createdAt)})`:`${n==="you"?"You drew it":`Drawn by ${n}`}${ug(e.createdAt??e.changedAt)}`;return t?`${i} · not seen by ${eT()} yet`:i}function tT(){let e=pg.value;if(!e||e.view!==Ee.value||!et.value.has(e.edgeId))return null;return r("span",{class:"toolbar-tooltip edge-hint",role:"tooltip","data-testid":"edge-hint",style:{left:`${e.x}px`,top:`${e.y}px`},children:r("span",{class:"toolbar-tooltip-label",children:e.text},void 0,!1,void 0,this)},void 0,!1,void 0,this)}var G$="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";function K$(e){if(!Number.isFinite(e)||e<=0)return 1;return e<1?1/e:1}function V$(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.style&&mo(e,Yn()?.relationVocabulary).kind==="related")return`${2*t} ${5*t}`;if(e.type==="references"&&!e.style)return n;return}function Vd(e,t){let n=e.position.x+e.size.width/2,o=e.position.y+e.size.height/2,i=t.position.x+t.size.width/2,s=t.position.y+t.size.height/2,a=i-n,l=s-o,c=e.size.width/2,u=e.size.height/2,d=Math.abs(l/(a||0.001)),p=u/(c||0.001);if(d>p){let m=l>0?1:-1;return{x:n+u/d*(a>0?1:-1),y:o+u*m,side:m>0?"bottom":"top"}}let f=a>0?1:-1;return{x:n+c*f,y:o+d*c*(l>0?1:-1),side:f>0?"right":"left"}}function Xd(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 X$(e,t,n,o,i,s,a,l){return{x:0.125*e+0.375*n+0.375*i+0.125*a,y:0.125*t+0.375*o+0.375*s+0.125*l}}function J$({edge:e,fromNode:t,toNode:n,start:o,end:i,focused:s,dimmed:a,selected:l,scale:c,part:u}){let d=i.x-o.x,p=i.y-o.y,f=Math.sqrt(d*d+p*p),m=Math.min(Math.max(f*0.35,32),160),h=Xd(o,m),g=Xd(i,m),v=`M ${o.x} ${o.y} C ${h.x} ${h.y}, ${g.x} ${g.y}, ${i.x} ${i.y}`,b=mo(e,Yn()?.relationVocabulary),x=`var(--c-rel-${b.ink})`,C=b.directed,y=V$(e,c),k=Math.min(c,2.2),_=Ee.value.scale,I=dC(e),w=e.label??e.kind,P=!!w&&_>=0.35,L=P?9:5,N=P?(w?.length??0)*7:0,Y=`not seen by ${eT()}`,B=12+Y.length*6.2+4,J=L*2+N+(I.notSeen?(N?12:0)+B:0),X=I.notSeen&&_>=0.6&&f>=(J+60)*k,V=I.notSeen?(N?12:0)+(X?B:12):0,ee=L*2+N+V,he=-ee/2+L,A=he+N+(N?12:0),M=P||I.notSeen?X$(o.x,o.y,h.x,h.y,g.x,g.y,i.x,i.y):null,O=`edge-path-${e.id}`,Pe=(Ae)=>{Ae.stopPropagation(),br.value=e.id},Fe=(Ae,ve)=>{let z=[`${String(t.data.title??t.id)} → ${String(n.data.title??n.id)}`,ha(e),q$(e,I.notSeen)].filter(Boolean).join(`
386
+ `),re=Ae.getBoundingClientRect();pg.value={x:ve?.x??re.left+re.width/2,y:(ve?.y??re.bottom)+8,text:z,edgeId:e.id,view:Ee.value}},De=()=>{pg.value=null};if(u==="pill-hits"){if(!M)return null;return r("rect",{class:"edge-pill-hit","data-testid":"edge-pill-hit","data-edge-id":e.id,x:M.x-ee/2*k,y:M.y-10*k,width:ee*k,height:20*k,rx:10*k,fill:"transparent",onClick:Pe,onPointerEnter:(Ae)=>Fe(Ae.currentTarget),onPointerLeave:De},void 0,!1,void 0,this)}if(u==="pills"){if(!M)return null;return r("g",{transform:`translate(${M.x}, ${M.y})`,class:"edge-pill","data-testid":"edge-pill",opacity:a&&!l?0.35:1,children:[r("rect",{class:"edge-label-bg",x:-ee/2*k,y:-10*k,width:ee*k,height:20*k,rx:10*k},void 0,!1,void 0,this),P&&r("text",{class:"edge-label",x:(he+N/2)*k,"text-anchor":"middle","dominant-baseline":"central",fill:x,children:w},void 0,!1,void 0,this),I.notSeen&&r("g",{class:"edge-link-mark is-not-seen","data-testid":"edge-link-mark",children:[N>0&&r("line",{x1:(A-6)*k,x2:(A-6)*k,y1:-6*k,y2:6*k,stroke:"var(--c-line)","stroke-width":k},void 0,!1,void 0,this),r("path",{transform:`translate(${A*k}, ${-5*k}) scale(${0.4166666666666667*k})`,d:G$,fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},void 0,!1,void 0,this),X&&r("text",{class:"edge-label",x:(A+14)*k,"text-anchor":"start","dominant-baseline":"central",fill:"currentColor",children:Y},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}return r("g",{children:[r("path",{"data-edge-id":e.id,d:v,fill:"none",stroke:"transparent","stroke-width":12*c,style:{cursor:"pointer",pointerEvents:"stroke"},onClick:Pe,onPointerEnter:(Ae)=>Fe(Ae.currentTarget,{x:Ae.clientX,y:Ae.clientY}),onPointerLeave:De},void 0,!1,void 0,this),r("path",{id:O,d:v,class:l?"edge-line edge-selected":"edge-line",fill:"none",stroke:x,"stroke-width":(l?3:s?2.5:1.5)*c,"stroke-dasharray":y,"marker-end":C?"url(#edge-arrow)":void 0,opacity:l?1:a?0.2:s?1:0.85,style:{color:x}},void 0,!1,void 0,this),e.animated&&r("circle",{r:3*c,fill:x,opacity:"0.9",children:r("animateMotion",{dur:"2s",repeatCount:"indefinite",children:r("mpath",{href:`#${O}`},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 Jd({nodes:e,edges:t,part:n}){let o=e.value,i=Array.from(t.value.values()),s=cg.value,a=s!==null,l=wr.value,c=l!==null,u=K$(Ee.value.scale),d=new Map,p=new Map;for(let y of i){if(y.toBoardId)continue;let k=Fs(y.from),_=Fs(y.to);if(!k||!_||k.id===_.id)continue;let I=Vd(k,_),w=Vd(_,k);d.set(y.id,{start:I,end:w});for(let[P,L,N]of[[I,k,_],[w,_,k]]){let Y=`${L.id}:${P.side}`,B=P.side==="left"||P.side==="right",J=p.get(Y)??[];J.push({anchor:P,node:L,order:B?N.position.y:N.position.x,id:y.id}),p.set(Y,J)}}for(let y of p.values()){if(y.length<2)continue;y.sort((k,_)=>k.order-_.order||k.id.localeCompare(_.id)),y.forEach(({anchor:k,node:_},I)=>{let w=(I+1)/(y.length+1);if(k.side==="left"||k.side==="right")k.y=_.position.y+_.size.height*w;else k.x=_.position.x+_.size.width*w})}if(i.length===0&&(n!=="lines"||!At.value))return null;let f=96,m=Array.from(o.values());if(m.length===0)return null;let h=Math.min(...m.map((y)=>y.position.x))-f,g=Math.min(...m.map((y)=>y.position.y))-f,v=Math.max(...m.map((y)=>y.position.x+y.size.width))+f,b=Math.max(...m.map((y)=>y.position.y+y.size.height))+f,x=Math.max(1,v-h),C=Math.max(1,b-g);return r("svg",{"aria-label":n==="lines"?"Canvas connections":void 0,"aria-hidden":n!=="lines"?"true":void 0,role:n==="lines"?"img":void 0,viewBox:`${h} ${g} ${x} ${C}`,width:x,height:C,style:{position:"absolute",top:`${g}px`,left:`${h}px`,zIndex:n==="pills"?1:n==="pill-hits"?"calc(var(--node-port-z, -1) - 1)":"var(--edge-line-z, -5)",pointerEvents:"none",overflow:"visible","--edge-chrome-scale":u.toFixed(3),"--edge-label-scale":Math.min(u,2.2).toFixed(3)},children:[n==="lines"&&r("title",{children:"Canvas connections"},void 0,!1,void 0,this),r("defs",{children:r("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:r("path",{d:"M 0 1 L 10 5 L 0 9 z",fill:"context-stroke",opacity:"0.75"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),i.map((y)=>{if(y.toBoardId)return null;let k=Fs(y.from),_=Fs(y.to),I=d.get(y.id);if(!k||!_||!I)return null;let w=a&&(y.from===s||y.to===s),P=c&&!(l.has(y.from)||l.has(y.to)),L=Vl.value;return r(J$,{edge:y,fromNode:k,toNode:_,start:I.start,end:I.end,focused:w,dimmed:L!==null&&!L.links.has(y.id)||P,selected:br.value===y.id,scale:u,part:n},y.id,!1,void 0,this)}),n==="lines"&&At.value&&(()=>{let y=At.value,k=Fs(y.fromId),_={position:{x:y.cursorX,y:y.cursorY},size:{width:1,height:1}},I;if(k){let w=Vd(k,_),P=Vd(_,k),L=P.x-w.x,N=P.y-w.y,Y=Math.sqrt(L*L+N*N),B=Math.min(Math.max(Y*0.35,32),160),J=Xd(w,B),X=Xd(P,B);I=`M ${w.x} ${w.y} C ${J.x} ${J.y}, ${X.x} ${X.y}, ${P.x} ${P.y}`}else{let w=y.cursorX-y.fromX,P=y.cursorY-y.fromY,L=Math.sqrt(w*w+P*P),N=Math.min(L*0.25,80),Y=w/(L||1),B=P/(L||1);I=`M ${y.fromX} ${y.fromY} C ${y.fromX+Y*N} ${y.fromY+B*N}, ${y.cursorX-Y*N} ${y.cursorY-B*N}, ${y.cursorX} ${y.cursorY}`}return r("g",{children:[r("path",{d:I,fill:"none",stroke:"var(--c-accent)","stroke-width":6*u,opacity:"0.1",style:{filter:"blur(3px)"}},void 0,!1,void 0,this),r("path",{d:I,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),r("circle",{cx:y.cursorX,cy:y.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 Y$(e){let[t,...n]=e;if(!t)return"";return n.reduce((o,i)=>`${o} L ${i.x} ${i.y}`,`M ${t.x} ${t.y}`)}function fg({annotations:e}){if(e.length===0)return null;return r("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 r("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 r("path",{d:Y$(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 Q$(e){switch(e.type){case"markdown":return r(Qu,{node:e},void 0,!1,void 0,this);case"mcp-app":return r(di,{node:e},void 0,!1,void 0,this);case"webpage":return r(Ad,{node:e},void 0,!1,void 0,this);case"json-render":return r(di,{node:e},void 0,!1,void 0,this);case"graph":return r(di,{node:e},void 0,!1,void 0,this);case"board":return r(Kd,{node:e},void 0,!1,void 0,this);case"prompt":return r(Rd,{node:e},void 0,!1,void 0,this);case"response":return r(Pd,{node:e},void 0,!1,void 0,this);case"status":return r(Id,{node:e},void 0,!1,void 0,this);case"context":return r($u,{node:e},void 0,!1,void 0,this);case"ledger":return r(Bu,{node:e},void 0,!1,void 0,this);case"trace":return r(Nd,{node:e},void 0,!1,void 0,this);case"file":return r(Du,{node:e},void 0,!1,void 0,this);case"diff":return r(Lu,{node:e},void 0,!1,void 0,this);case"mermaid":return r(ad,{node:e},void 0,!1,void 0,this);case"image":return r(Ed,{node:e},void 0,!1,void 0,this);case"html":return r(Hl,{node:e},void 0,!1,void 0,this);case"group":return r(W_,{node:e},void 0,!1,void 0,this);default:return r("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}class iT extends Br{shouldComponentUpdate(e){return e.node!==this.props.node||e.onContextMenu!==this.props.onContextMenu}render(){let{node:e,onContextMenu:t}=this.props;return r(YC,{node:e,onContextMenu:t,children:Q$(e)},void 0,!1,void 0,this)}}function eL(e,t,n){let o=n.x-t.x,i=n.y-t.y,s=o*o+i*i;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)*i)/s));return Math.hypot(e.x-(t.x+a*o),e.y-(t.y+a*i))}function tL(e,t,n){for(let o=e.length-1;o>=0;o--){let i=e[o];if(!i)continue;let s=n+i.width;if(t.x<i.bounds.x-s||t.x>i.bounds.x+i.bounds.width+s||t.y<i.bounds.y-s||t.y>i.bounds.y+i.bounds.height+s)continue;if(i.type==="text")return i;for(let a=1;a<i.points.length;a++){let l=i.points[a-1],c=i.points[a];if(l&&c&&eL(t,l,c)<=n+i.width/2)return i}}return null}var mg="currentColor",nT=4,oT=24,nL=14,rT={width:520,height:420};function oL(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 gg(e){let t=e.trim();if(!t)return[];let n=t.includes(`
387
+ `)?t.split(/\r?\n/):t.split(/\s+/),o=new Set,i=[];for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let l=oL(a);if(!l||o.has(l))continue;o.add(l),i.push(l)}return i}function rL(e){let t=gg(e.getData("text/uri-list"));if(t.length>0)return t;return gg(e.getData("text/plain"))}function iL(e){if(!e)return!1;return e.types.includes("text/uri-list")||e.types.includes("text/plain")}function hg(e){if(!(e instanceof HTMLElement))return!1;return Boolean(e.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}function sL(e,t,n=new Set){let o=[],i=0;for(let s of e){if(n.has(s.id))continue;if(t&&s.id===t)continue;if(s.type==="group")o.splice(i++,0,s);else o.push(s)}return o}function sT({onNodeContextMenu:e,onEdgeContextMenu:t,onCanvasContextMenu:n,annotationMode:o=!1,annotationTool:i=null}){let s=Ee.value,a=D(!1),l=D(null),c=D(!1),u=D([]),[d,p]=E(null),[f,m]=E(null),[h,g]=E(null),v=D(null),[b,x]=E(!1),C=D(0),y=D(null),k=D(null);q(()=>{let z=null,re=sn(()=>{Ee.value;let Ne=k.current;if(!Ne)return;if(Ne.style.willChange="transform",z)clearTimeout(z);z=setTimeout(()=>{Ne.style.willChange="auto"},180)});return()=>{if(z)clearTimeout(z);re()}},[]);let _=Ru({viewport:Ee,disabled:o,onBackgroundContextMenu:n,onEdgeContextMenu:t,onViewportChange:(z)=>{if(a.current||o)return;co(),Jk(z)},onViewportCommit:(z)=>{if(a.current||o)return;co(),mm(z)}}),I=oe((z)=>{v.current=z,g(z)},[]),w=oe(async(z,re,Ne)=>{if(z.length===0)return;let{width:ke,height:ae}=rT,Se=24,de=Math.ceil(Math.sqrt(z.length)),Ue=Math.ceil(z.length/de),xe=de*ke+Math.max(0,de-1)*Se,qe=Ue*ae+Math.max(0,Ue-1)*Se;for(let W=0;W<z.length;W++){let ye=W%de,He=Math.floor(W/de),R=re-xe/2+ye*(ke+Se),ne=Ne-qe/2+He*(ae+Se);await No({type:"webpage",content:z[W],x:R,y:ne,width:ke,height:ae})}},[]),P=oe((z)=>{let re=_.current;if(!re)return;if(i==="eraser"){if((z.target instanceof Element?z.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;z.preventDefault(),z.stopPropagation();let Ue=re.getBoundingClientRect(),xe=Ee.value,qe={x:(z.clientX-Ue.left-xe.x)/xe.scale,y:(z.clientY-Ue.top-xe.y)/xe.scale},W=tL(Array.from(Os.value.values()),qe,nL/xe.scale);if(W)Xk(W.id);return}if(i==="text"){if((z.target instanceof Element?z.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;z.preventDefault(),z.stopPropagation(),gt.value=null,$n();let Ue=re.getBoundingClientRect(),xe=Ee.value;I({x:(z.clientX-Ue.left-xe.x)/xe.scale,y:(z.clientY-Ue.top-xe.y)/xe.scale,value:""});return}if(i==="pen"){if((z.target instanceof Element?z.target:null)?.closest(".tool-rail, .top-bar, .snapshot-panel, .context-menu, .command-palette"))return;z.preventDefault(),z.stopPropagation(),gt.value=null,$n(),c.current=!0;let Ue=re.getBoundingClientRect(),xe=Ee.value,qe={x:(z.clientX-Ue.left-xe.x)/xe.scale,y:(z.clientY-Ue.top-xe.y)/xe.scale};u.current=[qe],m({id:"draft-annotation",type:"freehand",points:[qe],bounds:{x:0,y:0,width:0,height:0},color:mg,width:nT,createdAt:""}),re.setPointerCapture(z.pointerId);return}if(z.target!==re)return;if(Bs()||z.button===1||z.button===2){if(!z.shiftKey&&!y.current)gt.value=null,$n();return}z.preventDefault(),z.stopPropagation(),a.current=!0;let Ne=re.getBoundingClientRect(),ke=z.clientX-Ne.left,ae=z.clientY-Ne.top,Se={startX:ke,startY:ae,currentX:ke,currentY:ae};y.current=Se,p(Se),re.setPointerCapture(z.pointerId)},[i,_]);q(()=>sn(()=>{let z=Ee.value,re=l.current,Ne=_.current;if(!re||!Ne)return;let ke=Ne.getBoundingClientRect();uu({x:(re.x-ke.left-z.x)/z.scale,y:(re.y-ke.top-z.y)/z.scale})}),[]);let L=oe((z)=>{{let ke=_.current;if(ke){l.current={x:z.clientX,y:z.clientY};let ae=ke.getBoundingClientRect(),Se=Ee.value;uu({x:(z.clientX-ae.left-Se.x)/Se.scale,y:(z.clientY-ae.top-Se.y)/Se.scale})}}if(c.current){let ke=_.current;if(!ke)return;let ae=ke.getBoundingClientRect(),Se=Ee.value,de={x:(z.clientX-ae.left-Se.x)/Se.scale,y:(z.clientY-ae.top-Se.y)/Se.scale},Ue=u.current.at(-1);if(Ue&&Math.hypot(de.x-Ue.x,de.y-Ue.y)<2)return;u.current=[...u.current,de],m((xe)=>xe?{...xe,points:u.current}:null);return}if(!a.current||!y.current)return;let re=_.current?.getBoundingClientRect();if(!re)return;let Ne={...y.current,currentX:z.clientX-re.left,currentY:z.clientY-re.top};y.current=Ne,p(Ne)},[_]),N=oe((z)=>{if(c.current){c.current=!1;let de=u.current;if(u.current=[],m(null),de.length>=2)pm({points:de,color:mg,width:nT});let Ue=_.current;if(Ue?.hasPointerCapture(z.pointerId))Ue.releasePointerCapture(z.pointerId);return}let re=y.current;if(!a.current||!re)return;a.current=!1,y.current=null;let Ne=Math.min(re.startX,re.currentX),ke=Math.max(re.startX,re.currentX),ae=Math.min(re.startY,re.currentY),Se=Math.max(re.startY,re.currentY);if(ke-Ne<=5&&Se-ae<=5)gt.value=null,$n();if(ke-Ne>5||Se-ae>5){let de=Ee.value,Ue=(Ne-de.x)/de.scale,xe=(ke-de.x)/de.scale,qe=(ae-de.y)/de.scale,W=(Se-de.y)/de.scale,ye=[];for(let He of H.value.values()){let R=He.position.x,ne=He.position.y;if(R+He.size.width>Ue&&R<xe&&ne+He.size.height>qe&&ne<W)ye.push(He.id)}if(ye.length>0)Fk(ye)}p(null)},[]);q(()=>{if(o)return;if(!c.current&&!f&&!h)return;c.current=!1,u.current=[],m(null),I(null)},[o,f,I,h]);let Y=oe(()=>{let z=v.current;if(!z)return;let re=z.value.trim();if(I(null),!re)return;let Ne={x:z.x,y:z.y};pm({type:"text",points:[Ne],color:mg,width:oT,text:re})},[I]);q(()=>{if(i!=="text"&&h)I(null)},[i,I,h]),q(()=>{let z=(Se,de,Ue)=>{let xe=null;for(let qe of H.value.values()){if(qe.id===Ue||qe.type==="group")continue;if(Se>=qe.position.x&&Se<=qe.position.x+qe.size.width&&de>=qe.position.y&&de<=qe.position.y+qe.size.height)xe=qe.id}return xe};function re(Se){if(!At.value)return;let de=_.current;if(!de)return;let Ue=de.getBoundingClientRect(),xe=Ee.value,qe=(Se.clientX-Ue.left-xe.x)/xe.scale,W=(Se.clientY-Ue.top-xe.y)/xe.scale;At.value={...At.value,cursorX:qe,cursorY:W,targetId:z(qe,W,At.value.fromId)}}function Ne(){let Se=At.value;if(!Se)return;At.value=null;let de=Se.targetId;if(!de)return;if(Se.withLabel){On("Edge label","label text").then((Ue)=>{yr(Se.fromId,de,"relation",Ue??void 0)});return}yr(Se.fromId,de,"relation",void 0)}function ke(Se){let de=At.value;if(!de)return;if(Se.key==="Escape")Se.preventDefault(),At.value=null;else if(Se.key==="l"||Se.key==="L")Se.preventDefault(),At.value={...de,withLabel:!de.withLabel}}function ae(){At.value=null}return document.addEventListener("pointermove",re),document.addEventListener("pointerup",Ne),document.addEventListener("pointercancel",ae),document.addEventListener("keydown",ke),()=>{document.removeEventListener("pointermove",re),document.removeEventListener("pointerup",Ne),document.removeEventListener("pointercancel",ae),document.removeEventListener("keydown",ke)}},[_]);let B=oe((z)=>{if(o)return;let re=_.current;if(!re||z.target!==re||!n)return;let Ne=re.getBoundingClientRect(),ke=Ee.value,ae=(z.clientX-Ne.left-ke.x)/ke.scale,Se=(z.clientY-Ne.top-ke.y)/ke.scale;n(z,ae,Se)},[o,_,n]),J=oe((z)=>{z.preventDefault()},[]),X=oe((z)=>{if(hg(z.target instanceof Element?z.target:null))return;z.preventDefault()},[]),V=oe((z)=>{if(z.preventDefault(),C.current++,z.dataTransfer?.types.includes("Files")||iL(z.dataTransfer))x(!0)},[]),ee=oe((z)=>{if(z.preventDefault(),z.dataTransfer)z.dataTransfer.dropEffect="copy"},[]),he=oe((z)=>{if(z.preventDefault(),C.current--,C.current<=0)C.current=0,x(!1)},[]),A=oe(async(z)=>{z.preventDefault(),x(!1),C.current=0;let re=_.current;if(!re||!z.dataTransfer)return;let Ne=re.getBoundingClientRect(),ke=Ee.value,ae=(z.clientX-Ne.left-ke.x)/ke.scale,Se=(z.clientY-Ne.top-ke.y)/ke.scale,de=Array.from(z.dataTransfer.files);if(de.length===0){let Ue=rL(z.dataTransfer);await w(Ue,ae,Se);return}await ua(de,ae,Se)},[_,w]);q(()=>{let z=async(re)=>{if(re.defaultPrevented)return;if(hg(re.target instanceof Element?re.target:null))return;if(hg(document.activeElement))return;let Ne=re.clipboardData?.getData("text/plain")??"",ke=gg(Ne);if(ke.length===0)return;let ae=_.current;if(!ae)return;re.preventDefault();let Se=ae.getBoundingClientRect(),de=Ee.value,Ue=(Se.width/2-de.x)/de.scale,xe=(Se.height/2-de.y)/de.scale;await w(ke,Ue,xe)};return document.addEventListener("paste",z),()=>{document.removeEventListener("paste",z)}},[_,w]);let te=sL(H.value.values(),Bt.value,new Set(ll.value.keys())),M=te.reduce((z,re)=>Math.min(z,Math.floor(re.zIndex)),0),Pe=te.reduce((z,re)=>Math.max(z,Math.ceil(re.zIndex)),0)-M+3,Fe=Xo.value,De=Fe?H.value.get(Fe.groupId):void 0,Ae=Fe?H.value.get(Fe.nodeId):void 0,ve=null;if(d){let z=Math.min(d.startX,d.currentX),re=Math.min(d.startY,d.currentY),Ne=Math.abs(d.currentX-d.startX),ke=Math.abs(d.currentY-d.startY);ve={position:"absolute",left:`${z}px`,top:`${re}px`,width:`${Ne}px`,height:`${ke}px`,pointerEvents:"none"}}return r("div",{class:`canvas-viewport${Bs()?" pan-mode":""}`,ref:_,tabIndex:0,onPointerDown:P,onPointerMove:L,onPointerLeave:()=>{l.current=null,uu(null)},onPointerUp:N,onContextMenu:J,onDblClick:B,onDragStart:X,onDragEnter:V,onDragOver:ee,onDragLeave:he,onDrop:A,style:{width:"100%",height:"100%",position:"relative",overflow:"clip",cursor:i==="eraser"?"cell":i==="text"?"text":o||At.value||a.current||Wn.value==="connect"?"crosshair":Bs()?"grab":"default"},children:[r("div",{ref:k,class:"canvas-world",style:{transform:`matrix(${s.scale}, 0, 0, ${s.scale}, ${s.x}, ${s.y})`,transformOrigin:"0 0","--node-port-z":M-1,"--node-hit-offset":Pe,"--edge-line-z":M-Pe-1,position:"absolute",top:0,left:0},children:[r(MC,{},void 0,!1,void 0,this),r(oC,{},void 0,!1,void 0,this),r(lC,{},void 0,!1,void 0,this),r(cC,{},void 0,!1,void 0,this),r(Jd,{nodes:H,edges:et,part:"lines"},void 0,!1,void 0,this),r(Jd,{nodes:H,edges:et,part:"pills"},void 0,!1,void 0,this),r(Jd,{nodes:H,edges:et,part:"pill-hits"},void 0,!1,void 0,this),At.value&&r("div",{class:"edge-hint-pill","data-testid":"edge-hint",style:{left:`${At.value.cursorX+14}px`,top:`${At.value.cursorY+14}px`},children:[r("span",{class:"edge-hint-main",children:At.value.targetId?"release to connect":"drag onto a node"},void 0,!1,void 0,this),r("span",{class:"edge-hint-keys",children:["esc cancels · L labels",At.value.withLabel?" · label on":""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Fe&&De&&Ae&&r("div",{class:"drop-pill","data-testid":"drop-pill",style:{left:`${Ae.position.x}px`,top:`${Ae.position.y+Ae.size.height+10}px`},children:[r("span",{class:"drop-pill-text",children:Fe.mode==="add"?`release to add to ${String(De.data.title??"group")}`:`release to remove from ${String(De.data.title??"group")}`},void 0,!1,void 0,this),r("span",{class:"drop-pill-hint",children:Fe.mode==="add"?"esc keeps it out":"esc keeps it in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(fg,{annotations:Array.from(Os.value.values())},void 0,!1,void 0,this),f&&f.points.length>=2&&r(fg,{annotations:[f]},void 0,!1,void 0,this),te.map((z)=>r(iT,{node:z,onContextMenu:e},z.id,!1,void 0,this)),is.value&&r("svg",{class:"snap-guides-svg",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",overflow:"visible"},children:is.value.map((z,re)=>z.axis==="x"?r("line",{x1:z.pos,y1:z.from-20,x2:z.pos,y2:z.to+20,class:"snap-guide-line"},re,!1,void 0,this):r("line",{x1:z.from-20,y1:z.pos,x2:z.to+20,y2:z.pos,class:"snap-guide-line"},re,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&r("div",{class:`annotation-capture-layer${i==="eraser"?" erasing":""}${i==="text"?" text":""}`,"aria-hidden":"true"},void 0,!1,void 0,this),h&&r("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:`${oT*s.scale}px`},onInput:(z)=>I({...h,value:z.target.value}),onBlur:Y,onPointerDown:(z)=>z.stopPropagation(),onKeyDown:(z)=>{if(z.key==="Enter")z.preventDefault(),Y();if(z.key==="Escape")z.preventDefault(),I(null)}},void 0,!1,void 0,this),r(xC,{},void 0,!1,void 0,this),r(wC,{},void 0,!1,void 0,this),ve&&r("div",{class:"lasso-rect",style:ve},void 0,!1,void 0,this),b&&r("div",{class:"drop-zone-overlay",children:r("div",{class:"drop-zone-indicator",children:[r("div",{class:"drop-zone-icon",children:"+"},void 0,!1,void 0,this),r("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 Mr({label:e,value:t,options:n,onChange:o,className:i="",above:s=!1}){let[a,l]=E(!1),c=D(null),u=D(null),d=D(null),p=()=>{l(!1),u.current?.focus()};return Me(()=>{if(!a)return;(d.current?.querySelector('[aria-checked="true"]:not(:disabled)')??d.current?.querySelector("button:not(:disabled)"))?.focus();let m=(h)=>{if(h.target instanceof Node&&!c.current?.contains(h.target))l(!1)};return document.addEventListener("pointerdown",m),()=>document.removeEventListener("pointerdown",m)},[a]),r("div",{ref:c,class:`choice-menu ${i}`,onBlur:(f)=>{if(f.relatedTarget instanceof Node&&!c.current?.contains(f.relatedTarget))l(!1)},onKeyDown:(f)=>{if(f.key!=="Tab"&&(f.key!=="Escape"||a))f.stopPropagation();if(f.key==="Escape"&&a)f.preventDefault(),f.stopPropagation(),p();if(["ArrowDown","ArrowUp","Home","End"].includes(f.key)){if(f.preventDefault(),f.stopPropagation(),!a){l(!0);return}let m=[...d.current?.querySelectorAll("button:not(:disabled)")??[]];if(!m.length)return;let h=m.findIndex((v)=>v===document.activeElement),g=f.key==="Home"?0:f.key==="End"?m.length-1:(h+(f.key==="ArrowUp"?-1:1)+m.length)%m.length;m[g]?.focus()}},children:[r("button",{ref:u,type:"button",class:"choice-menu-trigger","aria-label":e,"aria-haspopup":"menu","aria-expanded":a,onClick:()=>l(!a),children:[r("span",{children:n.find((f)=>f.value===t)?.label??e},void 0,!1,void 0,this),r(js,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this),a&&r("div",{ref:d,role:"menu","aria-label":e,class:`toolbar-menu choice-menu-options${s?" opens-above":""}`,children:n.map((f)=>r("button",{type:"button",role:"menuitemradio",class:`toolbar-menu-item${f.value===t?" active":""}`,"aria-checked":f.value===t,disabled:f.disabled,tabIndex:-1,"data-value":f.value,onClick:()=>{o(f.value),p()},children:[r("span",{children:f.label},void 0,!1,void 0,this),f.value===t&&r("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},f.value,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Yd(e){let t=D(null);return Me(()=>{let n=t.current,o=n?.parentElement;if(!n||!o)return;let i=()=>o.style.setProperty(e,`${n.getBoundingClientRect().height}px`);i();let s=new ResizeObserver(i);return s.observe(n),()=>{s.disconnect(),o.style.removeProperty(e)}},[e]),t}function aT(){let e=Yd("--command-bar-height"),t=[...Di.value],n=H.value,[o,i]=E(""),[s,a]=E(!1),l=sC.value,[c,u]=E(null),d=l.length>=2,p=!d&&l.length===1&&l[0].steerable?l[0]:null,f=d?c?l.find((g)=>g.value===c&&g.steerable)??null:null:p,m=f?.value??null,h=async()=>{let g=o.trim();if(!xt.value||!g||s)return;a(!0);let v=await ma(g,m);if(a(!1),v)i("")};return r("div",{ref:e,class:"command-bar","data-testid":"command-bar",hidden:!xt.value,style:!xt.value?{display:"none"}:void 0,children:[t.length>0&&r("div",{class:"command-bar-chips","aria-label":"Pinned context",children:[t.map((g)=>{let v=n.get(g),b=typeof v?.data.title==="string"&&v.data.title.trim()?v.data.title:v?.type??g;return r("span",{class:"command-bar-chip","data-node-id":g,children:[r("span",{class:"command-bar-chip-label",children:b},void 0,!1,void 0,this),r(_e,{label:"Remove from context",side:"up",children:r("button",{type:"button",class:"command-bar-chip-unpin","aria-label":`Unpin ${b}`,onClick:()=>lo(g),children:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},g,!0,void 0,this)}),r("span",{class:"command-bar-chips-note",children:"in agent context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"command-bar-composer",children:[r(Zs,{size:15,class:"command-bar-icon"},void 0,!1,void 0,this),d&&r(Mr,{className:"command-bar-target",label:"Steer which agent",value:m??"",above:!0,onChange:(g)=>u(g||null),options:[{value:"",label:"All agents"},...l.map((g)=>{let v=g.pendingSteers&&g.pendingSteers>0?` · ${g.pendingSteers} queued`:"",b=g.polling?" · polling":"";return{value:g.value,disabled:!g.steerable,label:g.attached?`${g.label}${b}${v}`:g.steerable?`${g.label} · writer${b}${v}`:`${g.label} · no inbox`}})]},void 0,!1,void 0,this),r("input",{class:"command-bar-input",type:"text",value:o,placeholder:`Steer ${f?.label??"the agent"}, or ${Ft("K")} to search the board…`,"aria-label":"Steer the agent",disabled:s,onInput:(g)=>i(g.target.value),onKeyDown:(g)=>{if(g.key==="Enter")g.preventDefault(),h()}},void 0,!1,void 0,this),r("button",{type:"button",class:"command-bar-send",disabled:s||!o.trim(),onClick:()=>void h(),children:s?"Sending…":"Send"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function yg(e){let t=Math.max(0,Math.floor((Date.now()-new Date(e).getTime())/60000));if(t<1)return"just now";if(t<60)return`${t}m`;let n=Math.floor(t/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function Qd(e){let t=yg(e);return t==="just now"?t:`${t} ago`}var vg=ie(null),tp=ie(new Map);function bg(e){return e>=1000?`${(e/1000).toFixed(1)}k`:`${Math.round(e)}`}function Jl(e){return bg(e/4)}var ep=null,lT=0;function zr(e=250){if(ep)clearTimeout(ep);ep=setTimeout(()=>{ep=null,aL()},e)}async function aL(){let e=++lT,t=se.value,n=()=>e===lT&&t===se.value,o=await pe("fetchBriefSize","/api/canvas/context",null,{headers:{"x-pmx-proxied-read":"1"}});if(!n())return;if(o?.entries)vg.value={chars:JSON.stringify(o).length};let i=Ge.value.filter((a)=>a.pin);if(i.length===0){if(n())tp.value=new Map;return}let s=await pe("fetchBoardReadStatus",`/api/canvas/ax/context-status?boards=${i.map((a)=>encodeURIComponent(a.id)).join(",")}`,null);if(n())tp.value=new Map(i.map((a)=>[a.id,s?.boards?.[a.id]??null]))}function uT(){let e=Di.value.size;if(e===0||qr.value)return null;return r("div",{class:"context-pin-bar",role:"region","aria-label":"Pinned context",children:[r(uo,{size:14},void 0,!1,void 0,this),r("span",{children:[wg(e,"node")," in context"]},void 0,!0,void 0,this),r(_e,{label:"Clear all context pins",side:"up",align:"end",children:r("button",{type:"button","aria-label":"Clear all context pins",onClick:cm,children:r(Tt,{size:12},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 wg(e,t){return`${e} ${t}${e===1?"":"s"}`}function xg(e){let t=H.value.get(e);return typeof t?.data.title==="string"&&t.data.title?t.data.title:e}function dT(){let[e,t]=E(!1),n=D(null),o=D(null),i=se.value;q(()=>{if(!e)return;zr();let v=(x)=>{if(x.key!=="Escape")return;t(!1),o.current?.focus()},b=(x)=>{if(n.current&&!n.current.contains(x.target))t(!1)};return window.addEventListener("keydown",v),window.addEventListener("pointerdown",b),()=>{window.removeEventListener("keydown",v),window.removeEventListener("pointerdown",b)}},[e]);let s=ut.value;if(!i&&!s)return null;let a=s?[]:[...Di.value],l=s?[]:[...ro.value.entries()],c=Ge.value.filter((v)=>v.pin&&(s||v.id!==i)),u=a.length===0&&c.length===0,d=[...a.map((v)=>hi.value[v]?.pinnedBy),...c.map((v)=>v.pin?.pinnedBy)],p=!u&&d.every((v)=>v?.actor==="agent"),f=vg.value,m=f?`≈ ${Jl(f.chars)} tokens`:"",h=mi.value,g=[];if(a.length)g.push({text:wg(a.length,"card")});if(l.length)g.push({text:`${l.length} near`,kind:"near"});if(c.length)g.push({text:wg(c.length,"board")});if(p){let v=d.find((b)=>b?.actor==="agent");g.push({text:`by ${v?Nr(v):"agent"}`,kind:"agent"})}return r("div",{class:"context-chip-wrap",ref:n,children:[r("button",{ref:o,type:"button",class:`context-chip${u?" is-empty":""}${e?" is-open":""}`,"aria-expanded":e,"aria-haspopup":"dialog","data-testid":"context-chip",onClick:()=>t(!e),children:[r("span",{class:"context-chip-pin",children:[r(uo,{size:13},void 0,!1,void 0,this),p&&r("span",{class:"context-chip-agent-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u?r("span",{children:"Nothing in context"},void 0,!1,void 0,this):r(be,{children:[r("span",{class:"context-chip-wide",children:g.map((v,b)=>r("span",{class:v.kind?`is-${v.kind}`:void 0,children:[b>0?" · ":"",v.text]},v.text,!0,void 0,this))},void 0,!1,void 0,this),r("span",{class:"context-chip-narrow",children:[a.length+c.length," in context"]},void 0,!0,void 0,this),m&&r("span",{class:"context-chip-cost","data-testid":"token-cost",children:m},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e&&r("div",{class:"context-panel",role:"dialog","aria-label":"In the agent's context",children:[r("div",{class:"context-panel-head",children:[r("span",{class:"context-panel-title",children:"In the agent’s context"},void 0,!1,void 0,this),m&&r("span",{class:"context-panel-mono",children:m},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u?r("p",{class:"context-panel-cap",children:"Nothing is pinned. Pin a card or a board and the agent gets it first; it can still find and pull anything else on the board."},void 0,!1,void 0,this):r(be,{children:[r("p",{class:"context-panel-cap",children:["What the canvas sends the agent costs ",m||"a few tokens",".",h?.contextUsage?` ${h.label}’s whole context holds ${bg(h.contextUsage.used)} tokens.`:""]},void 0,!0,void 0,this),r("div",{class:"context-panel-section",children:[r("span",{children:["Cards on this board · ",a.length]},void 0,!0,void 0,this),a.length>0&&r("button",{type:"button",class:"context-panel-link",onClick:()=>cm(),children:"Clear all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("ul",{class:"context-panel-list",children:a.map((v)=>{let b=H.value.get(v),x=Dd(v,b?.contentRevision??0),C=x.kind==="read"&&Bd(v,b?.linksRevision??0),y=hi.value[v]?.pinnedBy.actor==="agent";return r("li",{class:"context-panel-row",children:[r("span",{class:"context-panel-pin",children:[r(uo,{size:9},void 0,!1,void 0,this),y&&r("span",{class:"context-chip-agent-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"context-panel-name",children:xg(v)},void 0,!1,void 0,this),C?r("span",{class:"context-tag is-links",children:[r("svg",{viewBox:"0 0 24 24",width:"10",height:"10","aria-hidden":"true",children:r("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"},void 0,!1,void 0,this)},void 0,!1,void 0,this),"links changed"]},void 0,!0,void 0,this):r(cT,{state:x.kind,at:x.kind==="not-read"?null:x.at},void 0,!1,void 0,this),r("button",{type:"button",class:"context-panel-x","aria-label":`Unpin ${xg(v)}`,onClick:()=>lo(v),children:"×"},void 0,!1,void 0,this)]},v,!0,void 0,this)})},void 0,!1,void 0,this),l.length>0&&r(be,{children:[r("div",{class:"context-panel-section",children:[r("span",{children:["Near · ",l.length]},void 0,!0,void 0,this),r("span",{class:"context-panel-cap-inline",children:["derived · ",r("span",{class:"context-panel-wide",children:"sent as "},void 0,!1,void 0,this),"title + summary"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("ul",{class:"context-panel-list",children:l.map(([v,b])=>r("li",{class:"context-panel-row is-near",children:[r("span",{class:"context-panel-near-ring","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"context-panel-name is-soft",children:xg(v)},void 0,!1,void 0,this),r("span",{class:"context-panel-cap-inline",children:["near ",b[0]?.pinTitle]},void 0,!0,void 0,this),r("button",{type:"button",class:"context-panel-promote",onClick:()=>lo(v),children:"Pin"},void 0,!1,void 0,this)]},v,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c.length>0&&r(be,{children:[r("div",{class:"context-panel-section",children:[r("span",{children:["Boards · ",c.length]},void 0,!0,void 0,this),r("span",{class:"context-panel-cap-inline",children:"sent as a map"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("ul",{class:"context-panel-list",children:c.map((v)=>{let b=tp.value.get(v.id);return r("li",{class:"context-panel-row",children:[r("svg",{class:"context-panel-board",viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",children:r("path",{d:"M4 4h16v16H4zM9 9h6v6H9z"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"context-panel-name",children:v.name},void 0,!1,void 0,this),r(cT,{state:b?"read":"not-read",at:b?.lastReadAt??null},void 0,!1,void 0,this),r("span",{class:"context-panel-cap-inline",children:"map"},void 0,!1,void 0,this),r("button",{type:"button",class:"context-panel-x","aria-label":`Unpin ${v.name}`,onClick:()=>void $s(v.id,!1),children:"×"},void 0,!1,void 0,this)]},v.id,!0,void 0,this)})},void 0,!1,void 0,this),r("p",{class:"context-panel-cap",children:"A pinned board travels as a map: its folder, README summary, each pinned card’s title and summary, and its links and backlinks. The agent pulls a card or the whole board in full when it decides it needs to."},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 cT({state:e,at:t}){let[n,o,i]=e==="changed"?["is-changed",gi.warn,"changed"]:e==="read"&&t?["is-read",gi.eye,`read ${yg(t)}`]:["is-not-read",gi.eyeOff,"not read yet"];return r("span",{class:`context-tag ${n}`,children:[r("svg",{viewBox:"0 0 24 24",width:"11",height:"11","aria-hidden":"true",children:r("path",{d:o},void 0,!1,void 0,this)},void 0,!1,void 0,this),i]},void 0,!0,void 0,this)}var kg=Ve(()=>{if(ao.value==="disconnected")return"reconnecting";if(ao.value==="connected"&&!cn.value&&Zi.value>1)return"resyncing";return null});function pT(){let e=kg.value;if(!e)return null;if(e==="reconnecting"){let t=Wi.value,n=qi.value;return r("div",{class:"connection-banner is-reconnecting",role:"status","data-testid":"connection-banner",children:[r("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"↻"},void 0,!1,void 0,this),r("span",{class:"connection-banner-text",children:[r("b",{children:"Reconnecting…"},void 0,!1,void 0,this)," live updates are paused; retry refused saves after reconnect. The board may be stale."]},void 0,!0,void 0,this),r("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 r("div",{class:"connection-banner is-resyncing",role:"status","data-testid":"connection-banner",children:[r("span",{class:"connection-banner-glyph","aria-hidden":"true",children:"⟳"},void 0,!1,void 0,this),r("span",{class:"connection-banner-text",children:[r("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),r("span",{class:"connection-banner-progress","aria-hidden":"true",children:r("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 lL={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 Eo(e){if(e.x!==void 0&&e.y!==void 0)return No(e);let t=lL[e.type]??{width:360,height:200},n=e.width??t.width,o=e.height??t.height,i=Zr(),s=Ee.value,a=await No({...e,width:n,height:o,x:Math.round((i.x-s.x)/s.scale-n/2),y:Math.round((i.y-s.y)/s.scale-o/2)});if(a.ok&&a.id)$t(a.id);return a}var np=!1,fT=!1,ss=null,ba=null;function Sg(){return np}function op(){np=!1,fT=!0,mT()}function mT(){if(ss&&ba)ss.removeEventListener("change",ba);ss=null,ba=null}function cL(){if(typeof window>"u"||!window.location)return null;let e=new URLSearchParams(window.location.search).get("theme");if(e==="auto")return"auto";return El(e)?e:null}function hT(e){if(fT)return;let t=cL();if(!t)return;if(mT(),np=!0,t!=="auto"){e(t);return}ss=window.matchMedia("(prefers-color-scheme: light)"),ba=()=>{if(np&&ss)e(ss.matches?"daylight":"harbor")},ba(),ss.addEventListener("change",ba)}var uL='a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), summary, [tabindex]:not([tabindex="-1"])';function bn(e,t,n={}){let o=D(n.onEscape);o.current=n.onEscape,Me(()=>{if(!t)return;let i=e.current;if(!i)return;let s=document.activeElement,a=n.restoreTo,l=()=>Array.from(i.querySelectorAll(uL)).filter((p)=>{if(p.closest("[hidden], [inert]"))return!1;for(let f=p;f&&f!==i;f=f.parentElement){if(getComputedStyle(f).display==="none"||getComputedStyle(f).visibility==="hidden")return!1;if(f.matches("details:not([open])")&&!f.querySelector(":scope > summary")?.contains(p))return!1}return!0}),c=n.initial?.current??l()[0];if(c&&!i.contains(document.activeElement))c.focus();let u=(p)=>{if(p.key!=="Tab")return;let f=l();if(f.length===0)return;let m=f[0],h=f[f.length-1],g=document.activeElement;if(p.shiftKey&&(g===m||!i.contains(g)))p.preventDefault(),h.focus();else if(!p.shiftKey&&g===h)p.preventDefault(),m.focus()},d=(p)=>{if(p.key!=="Escape"||!o.current||i.contains(p.target))return;p.preventDefault(),p.stopPropagation(),o.current()};return i.addEventListener("keydown",u),window.addEventListener("keydown",d,!0),()=>{if(i.removeEventListener("keydown",u),window.removeEventListener("keydown",d,!0),a)requestAnimationFrame(()=>a()?.focus());else if(s&&document.contains(s)&&s!==document.body)s.focus()}},[e,t,n.initial,n.restoreTo])}function dL(e,t){let n=e.toLowerCase(),o=t.toLowerCase(),i=[],s=0,a=0,l=-1;for(let c=0;c<o.length&&s<n.length;c++)if(o[c]===n[s]){if(i.push(c),a+=l===c-1?10:1,c===0||o[c-1]===" "||o[c-1]==="-"||o[c-1]==="_")a+=5;l=c,s++}return{match:s===n.length,score:a,indices:i}}function pL(e,t){if(t.length===0)return e;let n=[],o=0;for(let i of t){if(i>o)n.push(e.slice(o,i));n.push(r("mark",{children:e[i]},i,!1,void 0,this)),o=i+1}if(o<e.length)n.push(e.slice(o));return n}var _g={md:"markdown",app:"mcp-app",web:"webpage",ui:"json-render",chart:"graph",ctx:"context",log:"ledger"};function fL(e){let t=e.toLowerCase().trim();if(t.startsWith("type:")){let n=t.slice(5).trim(),i=Object.keys(an).find((a)=>a.startsWith(n));if(i)return{typeFilter:i,remaining:""};let s=_g[n];if(s)return{typeFilter:s,remaining:""}}if(_g[t])return{typeFilter:_g[t],remaining:""};return{typeFilter:null,remaining:e}}function gT({onClose:e,onToggleMinimap:t}){let[n,o]=E(""),[i,s]=E(0),[a,l]=E([]),[c,u]=E("idle"),d=D(null),p=D(null),f=D(null);bn(f,!0,{initial:d}),q(()=>{setTimeout(()=>d.current?.focus(),30)},[]),q(()=>{let _=n.trim();if(_.length<2){l([]),u("idle");return}let I=!0;u("loading");let w=window.setTimeout(()=>void pe("paletteLibrarySearch",`/api/canvas/search?q=${encodeURIComponent(_)}&scope=library&limit=12`,null).then((P)=>{if(!I)return;if(!P){l([]),u("error");return}l(P.results??[]),u("idle")}),150);return()=>{I=!1,window.clearTimeout(w)}},[n]);let m=oe(()=>{let _=[];for(let w of H.value.values()){let P=w.data.title||an[w.type],L=w.data.content||w.data.path||"",N=w.type==="group"&&Array.isArray(w.data.children)?w.data.children.length:0;_.push({id:`node:${w.id}`,kind:"node",label:P,description:w.type==="group"?`group · ${N} node${N===1?"":"s"}`:L.length>60?`${an[w.type].toLowerCase()} · ${L.slice(0,60)}…`:L?`${an[w.type].toLowerCase()} · ${L}`:an[w.type].toLowerCase(),icon:Do(w.type),nodeType:w.type,action:()=>{$t(w.id),e()}})}let I=[{label:"New markdown note",shortcut:"M",icon:ni,iconTone:"accent",action:()=>{Eo({type:"markdown",title:"New note",width:520,height:360}),e()}},{label:"Link to board…",icon:Do("board"),iconTone:"accent",action:()=>{window.dispatchEvent(new CustomEvent("pmx-open-board-link")),e()}},...!xt.value||_o.value?[]:[{label:"Start agent session",icon:Zs,iconTone:"purple",action:()=>{vi(),e()}}],{label:"Fit view",shortcut:"F",icon:Nu,iconTone:"muted",action:()=>{Hs(Jt().width,Jt().height),e()}},{label:"Auto-arrange (grid)",icon:Tr,iconTone:"muted",action:()=>{Iu(),e()}},{label:"Auto-arrange (graph-aware)",icon:Tr,iconTone:"muted",action:()=>{Eu(),e()}},{label:"Toggle minimap",icon:mS,iconTone:"muted",action:()=>{t(),e()}},{label:"Toggle theme (Harbor/Daylight)",icon:hS,iconTone:"muted",action:()=>{let w=ta(Qt.value)==="dark"?"daylight":"harbor";op(),document.documentElement.setAttribute("data-theme",w),la(),Qt.value=w,hu(w),e()}}];for(let w of I)_.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:g}=fL(n),v=m(),b;if(!n.trim())b=v.map((_)=>({..._,score:0,indices:[]}));else{b=[];for(let _ of v){if(h){if(_.kind!=="node"||_.nodeType!==h)continue;if(!g){b.push({..._,score:0,indices:[]});continue}}let I=dL(g||n,_.label);if(I.match)b.push({..._,score:I.score,indices:I.indices})}b.sort((_,I)=>I.score-_.score)}for(let _ of a)b.push({id:`library:${_.boardId}:${_.cardId}`,kind:"library",label:_.title||_.boardTitle,description:`${_.boardTitle} · ${_.snippet}`,icon:Do("board"),score:0,indices:[],action:()=>{(async()=>{await zt(_),e()})()}});b=[...b.filter((_)=>_.kind==="action"),...b.filter((_)=>_.kind==="node"),...b.filter((_)=>_.kind==="library")];let x=b.findIndex((_)=>_.kind==="node"),C=b.findIndex((_)=>_.kind==="library");q(()=>{if(!n.trim()){wr.value=null;return}let _=new Set;for(let I of b)if(I.kind==="node")_.add(I.id.slice(5));wr.value=_.size>0?_:null},[n,b]),q(()=>()=>{wr.value=null},[]);let y=Math.min(i,Math.max(0,b.length-1)),k=oe((_)=>{if(_.key==="ArrowDown")_.preventDefault(),s((I)=>Math.min(I+1,b.length-1));else if(_.key==="ArrowUp")_.preventDefault(),s((I)=>Math.max(I-1,0));else if(_.key==="Enter"){if(_.preventDefault(),b[y])b[y].action()}else if(_.key==="Escape")_.preventDefault(),_.stopPropagation(),e()},[b,y,e]);return q(()=>{let _=p.current;if(!_)return;_.children[y]?.scrollIntoView({block:"nearest"})},[y]),q(()=>{s(0)},[n]),r("div",{class:"command-palette-backdrop",onMouseDown:e,children:r("div",{ref:f,class:"command-palette",role:"dialog","aria-modal":"true","aria-label":"Search and commands",onMouseDown:(_)=>_.stopPropagation(),children:[r("div",{class:"command-palette-search",children:[r("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:[r("circle",{cx:"7",cy:"7",r:"4.5"},void 0,!1,void 0,this),r("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),r("input",{ref:d,type:"text",class:"command-palette-input",value:n,onInput:(_)=>o(_.target.value),onKeyDown:k,placeholder:"Search nodes, run actions, jump to…","aria-label":"Search nodes, run actions, jump to"},void 0,!1,void 0,this),r("kbd",{class:"command-palette-esc",children:"esc"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"command-palette-results",ref:p,children:[c==="loading"&&r("div",{class:"command-palette-empty",role:"status",children:"Searching all boards…"},void 0,!1,void 0,this),c==="error"&&r("div",{class:"command-palette-empty",role:"alert",children:"Library search is unavailable."},void 0,!1,void 0,this),b.length===0&&c!=="loading"&&r("div",{class:"command-palette-empty",children:"No matching nodes, boards, or actions"},void 0,!1,void 0,this),b.map((_,I)=>{let w=_.icon,P=I===0&&_.kind==="action"?"Actions":I===x?"Jump to":I===C?"Across boards":null;return r("div",{class:"command-palette-row",children:[P&&r("div",{class:"command-palette-group",children:P},void 0,!1,void 0,this),r("button",{type:"button",class:`command-palette-item${I===y?" selected":""}`,onMouseEnter:()=>s(I),onClick:()=>_.action(),children:[r("span",{class:`command-palette-icon tone-${_.iconTone??"kind"}`,"aria-hidden":"true",children:r(w,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"command-palette-label",children:[_.indices.length>0?pL(_.label,_.indices):_.label,_.description&&r("span",{class:"command-palette-desc",children:[" — ",_.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_.shortcut&&r("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),r("div",{class:"command-palette-hint",children:[r("span",{children:"↑↓ navigate"},void 0,!1,void 0,this),r("span",{children:"↵ open"},void 0,!1,void 0,this),r("span",{children:"esc close"},void 0,!1,void 0,this),r("span",{children:"type: filter"},void 0,!1,void 0,this),r("span",{class:"command-palette-hint-spacer"},void 0,!1,void 0,this),r("span",{children:Ft("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 yT({onClose:e,sourceNodeId:t,wikiRef:n}){let o=D(null),i=D(null),s=D(se.value).current,a=D(t?H.value.get(t):void 0).current,[l,c]=E(null),[u,d]=E(""),[p,f]=E(""),[m,h]=E(!1);bn(o,!0,{initial:i}),q(()=>{let y=!1;if(t&&!n)pe("linkCardChoices","/api/canvas/memory-graph",null).then((k)=>{if(!y){if(c(k),!k)f("Could not load cards. Close and retry.")}});return()=>{y=!0}},[t,n]);let g=Ge.value.filter((y)=>y.id!==s&&y.name.toLowerCase().includes(u.trim().toLowerCase())),v=(l?.nodes??[]).filter((y)=>y.kind==="card"&&y.boardId!==s&&`${y.title} ${Ge.value.find((k)=>k.id===y.boardId)?.name??""}`.toLowerCase().includes(u.trim().toLowerCase())),b=async()=>{if(!n||!a||se.value!==s)return f("The source board changed. Reopen it before creating the link.");h(!0);let y=await pe("createWikiBoard","/api/canvas/boards",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n,expectedBoardId:s})});if(!y?.board)return h(!1),f("Could not create the board.");let k=await ln(a.id,{content:typeof a.data.content==="string"?a.data.content:"",expectedBoardId:s,expectedContentRevision:a.contentRevision??0});if(await sl(),h(!1),!k.ok)return f("Board created, but the source changed. Save its Markdown again to resolve the link.");e(),await zt({boardId:y.board.id})},x=async(y,k)=>{if(!t)return;h(!0);let _=await yr(t,k,"references",void 0,{toBoardId:y,expectedBoardId:s});if(h(!1),!_.ok)return f("Could not add the connection. Check the source board and target card, then retry.");e()},C=async(y)=>{let k=Ge.value.find((P)=>P.id===y);if(!k)return f("That board is no longer available.");let _=Zr(),I=Ee.value;if(!(await pe("createBoardLink","/api/canvas/node",{},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedBoardId:s,type:"board",title:k.name,x:Math.round((_.x-I.x)/I.scale-180),y:Math.round((_.y-I.y)/I.scale-100),width:360,height:200,data:{boardId:y}})})).ok)return f("Could not create the board link.");e()};return r("div",{class:"text-prompt-backdrop",onMouseDown:e,children:r("div",{ref:o,class:"text-prompt board-link-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-link-title",onMouseDown:(y)=>y.stopPropagation(),children:[r("h2",{id:"board-link-title",children:n?"Create unresolved board":t?"Connect to a card on another board":"Link to a board"},void 0,!1,void 0,this),n?r("p",{children:["Create “",n,"” and save this link to its board ID?"]},void 0,!0,void 0,this):r("input",{ref:i,type:"search",class:"text-prompt-input","aria-label":t?"Find a card to connect":"Find a board to link",placeholder:t?"Find a board or card…":"Find a board…",value:u,onInput:(y)=>d(y.currentTarget.value)},void 0,!1,void 0,this),p&&r("div",{role:"alert",class:"board-copy-error",children:p},void 0,!1,void 0,this),!n&&r("ul",{class:"board-link-results",children:[t?v.map((y)=>r("li",{children:r("button",{type:"button",disabled:m,onClick:()=>void x(y.boardId,y.cardId),children:[r("span",{children:y.title},void 0,!1,void 0,this),r("small",{children:Ge.value.find((k)=>k.id===y.boardId)?.name??y.boardId},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},y.key,!1,void 0,this)):g.map((y)=>r("li",{children:r("button",{type:"button",onClick:()=>void C(y.id),children:[r("span",{children:y.name},void 0,!1,void 0,this),r("small",{children:[y.nodeCount," nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},y.id,!1,void 0,this)),(t?v.length:g.length)===0&&r("li",{class:"board-copy-status",children:Ge.value.length<=1?"Create another board first, then link it here.":t&&!l?"Loading cards…":"No matches. Try another search."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"text-prompt-actions",children:[n&&r("button",{type:"button",disabled:m,onClick:()=>void b(),children:m?"Creating…":"Create board"},void 0,!1,void 0,this),r("button",{type:"button",onClick:e,children:"Cancel"},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 xa={decayType:"reality",rate:"medium",cadenceDays:90,triggers:[],revalidationMethod:""};function Yl({value:e,onChange:t}){return r("div",{class:"lifecycle-fields",children:[r("div",{class:"knowledge-field",children:[r("span",{children:"Why review?"},void 0,!1,void 0,this),r(Mr,{label:"Why review?",value:e.decayType,onChange:(n)=>t({...e,decayType:n}),options:[{value:"reality",label:"Reality · facts change"},{value:"decision",label:"Decision · superseded"},{value:"dependency",label:"Dependency · prerequisites change"},{value:"relevance",label:"Relevance · task changes"}]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"knowledge-field",children:[r("span",{children:"Review frequency"},void 0,!1,void 0,this),r(Mr,{label:"Review frequency",value:e.rate,onChange:(n)=>t({...e,rate:n}),options:[{value:"fast",label:"Fast · at use"},{value:"medium",label:"Medium · on a cadence"},{value:"slow",label:"Slow · on resume"},{value:"durable",label:"Durable · no passive expiry"}]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),e.rate==="medium"&&r("label",{children:["Cadence in days",r("input",{type:"number",min:"1",max:"36500",required:!0,value:e.cadenceDays??"",onInput:(n)=>t({...e,cadenceDays:n.currentTarget.value?Number(n.currentTarget.value):void 0})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("details",{class:"lifecycle-triggers",children:[r("summary",{children:"Additional review triggers"},void 0,!1,void 0,this),r("label",{children:["Also review when · one trigger per line",r("textarea",{value:e.triggers.join(`
388
388
  `),onInput:(n)=>t({...e,triggers:n.currentTarget.value.split(`
389
- `)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Source changes, contradictions and superseding decisions are observed through explicit relations. Other triggers describe what the reviewer should check."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["How to check",r("input",{required:!0,pattern:".*\\S.*",value:e.revalidationMethod,onInput:(n)=>t({...e,revalidationMethod:n.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Ql=(e)=>({...e,triggers:e.triggers.map((t)=>t.trim()).filter(Boolean)});function vT(){let e=Ct.value;if(!e||ut.value||se.value!==e.boardId||wt!==e.incarnation||!H.value.has(e.nodeId))return null;return r(mL,{target:e},`${e.boardId}:${e.nodeId}:${e.incarnation}`,!1,void 0,this)}function mL({target:e}){let t=Oe.value,n=D(null),o=D(0),[i,s]=E(null),[a,l]=E(!1),[c,u]=E(ba),[d,p]=E("retain"),[f,m]=E(""),[h,g]=E(!1),[v,b]=E(!1),[x,C]=E(""),[y,k]=E(!1),[_,I]=E(!1),w=H.value.get(e.nodeId),P=nh(e.boardId,e.nodeId),L=Jn(e.nodeId)??i?.qualification,N=`/api/canvas/node/${encodeURIComponent(e.nodeId)}`,Y=()=>se.value===e.boardId&&wt===e.incarnation,B=()=>Oe.value&&Y()&&Ct.value===e,J=async()=>{if(!B())return;let A=tn,te=++o.current,M=await de("lifecycle",`${N}/lifecycle?board=${encodeURIComponent(e.boardId)}`,null);if(!B()||A!==tn||te!==o.current)return;if(M?.ok!==!0){C("Could not load lifecycle. Retry before reviewing.");return}s(M),I(!1),C(""),l(M.lifecycleSource==="card"),u(M.lifecycle??ba),m(""),g(!1)};q(()=>{let A=document.activeElement,te=n.current;if(Oe.value)te?.querySelector("button")?.focus({preventScroll:!0}),$t(e.nodeId,{recordHistory:!1});return()=>{if(te?.contains(document.activeElement)&&Y()&&A instanceof HTMLElement&&A.isConnected)A.focus({preventScroll:!0})}},[]),Me(()=>{if(!t&&n.current?.contains(document.activeElement))document.querySelector('button[aria-label="Settings"]')?.focus({preventScroll:!0})},[t]),q(()=>{if(!t)return;if(Kt(),!i||_)J()},[t]);let X=async(A,te,M)=>{if(!B()||v||_)return!1;b(!0),C("");let O=await de("lifecycleWrite",`${N}${A}`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...te,expectedBoardId:e.boardId})});if(!Y())return b(!1),!1;if(!O?.ok)return b(!1),C("Not saved. The card or its sources may have changed. Reload and check the current evidence before retrying."),!1;if(M?.(),Ct.value!==e)return Kt(),b(!1),!1;return I(!0),await J(),await Kt(),b(!1),Y()&&Ct.value===e},V=async(A,te)=>{if(!i)return!1;if(te&&["retain","revise","externalize"].includes(A)&&(!f.trim()||nh(e.boardId,e.nodeId)||w?.contentRevision!==i.contentRevision||x))return!1;return X("/review",{outcome:A,evidence:f,applied:te,expectedContentRevision:i.contentRevision,expectedSources:i.qualification.observations},()=>{if(k(te&&A==="retire"),te&&A==="retire")Is.value=e;m(""),g(!1)})},ee=w?.data.provenance,he=(A)=>A?new Date(A).toLocaleString():"Unknown";return r("div",{class:"lifecycle-dock",hidden:!t,style:t?void 0:{display:"none"},onKeyDown:(A)=>{if(!B())return;if(A.stopPropagation(),A.key==="Escape")A.preventDefault(),Ct.value=null},children:r("div",{ref:n,class:"knowledge-dialog lifecycle-dialog",role:"dialog","aria-label":"Review card",children:[r("header",{children:[r("h2",{children:["Review card · ",String(w?.data.title??"Card")]},void 0,!0,void 0,this),r("button",{type:"button","aria-label":"Close review",onClick:()=>{if(!B())return;Ct.value=null},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x&&r("p",{role:"alert",children:x},void 0,!1,void 0,this),!i&&x&&r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!v)J()},children:"Reload and recheck"},void 0,!1,void 0,this),Oi.value&&r("p",{role:"status",children:"Live qualification unavailable. Last loaded evidence is shown."},void 0,!1,void 0,this),!i?r("p",{children:"Loading review…"},void 0,!1,void 0,this):r(be,{children:[i.retired?r("div",{class:"lifecycle-review",children:[r("p",{children:"This card is retired. Restoring it does not mark it checked."},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v||_,onClick:()=>void X("/lifecycle/restore",{evidence:"Restored by the human reviewer."}),children:"Restore card"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r("h3",{children:"Why review?"},void 0,!1,void 0,this),L?.due?r("p",{class:"lifecycle-warning",children:["⧗"," ",L.reasons.some((A)=>A.startsWith("Content changed"))?"This card changed since its last check.":"This card needs a fresh check."]},void 0,!0,void 0,this):r("p",{children:["Last checked: ",he(i.lastValidation?.when)]},void 0,!0,void 0,this),L?.reasons.length?r("p",{children:L.reasons.join(" ")},void 0,!1,void 0,this):null,(L?.sources??i.qualification.sources).map((A)=>r("div",{class:"lifecycle-warning",children:["⧗ Source needs a check: ",A.title,!A.unavailable&&r("button",{type:"button",onClick:()=>{if(!B())return;Ct.value=null,zt(A)},children:"Open source →"},void 0,!1,void 0,this)]},`${A.boardId}:${A.cardId}`,!0,void 0,this)),r("form",{class:"lifecycle-quick-review",noValidate:!0,onSubmit:(A)=>{A.preventDefault(),V("retain",!0).then((te)=>{if(te&&B())Ct.value=null})},children:[r("p",{children:"Check the card and its sources before confirming."},void 0,!1,void 0,this),P&&r("p",{role:"status",children:"Save the card's edits, then reload and recheck before validating."},void 0,!1,void 0,this),r("label",{children:["What did you check?",r("textarea",{required:!0,rows:2,placeholder:"A short note or source link",value:f,onInput:(A)=>m(A.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"lifecycle-review-actions",children:[r("button",{type:"submit","aria-disabled":v||_||!!x||P||!f.trim()||w?.contentRevision!==i.contentRevision,children:"Checked, still correct"},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!B()||v)return;Ct.value=null},children:"Not now"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(x||w?.contentRevision!==i.contentRevision)&&r("div",{role:"status",children:[r("p",{children:"Reload, check the current card and sources, then write a fresh note."},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!v)J()},children:"Reload and recheck"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("details",{class:"lifecycle-advanced",children:[r("summary",{children:"Settings and history"},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!v)J()},children:"Reload lifecycle and source revisions"},void 0,!1,void 0,this),r("p",{class:"lifecycle-category",children:[i.category?`${i.category.glyph} ${i.category.name} · from ${i.categorySourceFolder}`:"No inherited category"," ","· category belongs to the folder"]},void 0,!0,void 0,this),r("form",{onSubmit:(A)=>{A.preventDefault(),X("/lifecycle",{lifecycleOverride:a?Ql(c):null})},children:[r("label",{children:[r("input",{type:"checkbox",checked:a,onChange:(A)=>l(A.currentTarget.checked)},void 0,!1,void 0,this)," ","Set a card lifecycle override"]},void 0,!0,void 0,this),a?r(Yl,{value:c,onChange:u},void 0,!1,void 0,this):r("p",{children:["Inherit from ",i.lifecycleSourceFolder??"the folder"," · ",i.lifecycle?.rate??"unknown"]},void 0,!0,void 0,this),r("button",{type:"submit","aria-disabled":v||_,children:"Save lifecycle"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"lifecycle-clocks",children:[r("div",{class:"is-read",children:[r("span",{children:"Read by agent"},void 0,!1,void 0,this),r("strong",{children:he(i.qualification.lastReadAt)},void 0,!1,void 0,this),r("small",{children:"Delivery only, not validation"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{children:[r("span",{children:"Content changed"},void 0,!1,void 0,this),r("strong",{children:he(i.qualification.contentChangedAt)},void 0,!1,void 0,this),r("small",{children:["Revision ",i.contentRevision]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{children:[r("span",{children:"Last validated"},void 0,!1,void 0,this),r("strong",{children:he(i.lastValidation?.when)},void 0,!1,void 0,this),r("small",{children:i.lastValidation?.evidence??"No evidence-backed validation"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{children:[r("span",{children:"Task relevance"},void 0,!1,void 0,this),r("strong",{children:i.qualification.relevance==="card-pinned"?"Card pinned":i.qualification.relevance==="board-pinned"?"Board pinned":"Not explicitly selected"},void 0,!1,void 0,this),r("small",{children:"Curation, not a truth claim"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Reading, refreshing and regeneration never count as validating."},void 0,!1,void 0,this),L?.due&&r("p",{class:"lifecycle-warning",children:["⧗ review due · ",L.reasons.join(" ")]},void 0,!0,void 0,this),(L?.sources??i.qualification.sources).map((A)=>r("div",{class:"lifecycle-warning",children:["⧗ ",A.title," · ",A.reasons.join(" "),A.observedAt&&r("span",{children:[" · observed ",he(A.observedAt)]},void 0,!0,void 0,this),A.observedRevision!==void 0&&r("span",{children:[" · source revision ",A.observedRevision]},void 0,!0,void 0,this),!A.unavailable&&r("button",{type:"button",onClick:()=>{if(!B())return;Ct.value=null,zt(A)},children:"Open source →"},void 0,!1,void 0,this)]},`${A.boardId}:${A.cardId}`,!0,void 0,this)),w?.contentRevision!==i.contentRevision&&r("p",{role:"alert",children:"Content changed while this review was open. Reload and check it before applying."},void 0,!1,void 0,this),i.retired?r("div",{class:"lifecycle-review",children:[r("p",{role:"status",children:"Retired from active context. Content and history remain."},void 0,!1,void 0,this),r("label",{children:["Restoration note",r("input",{value:f,onInput:(A)=>m(A.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button","aria-disabled":v||_,onClick:()=>void X("/lifecycle/restore",{evidence:f||"Restored by the human reviewer."}).then((A)=>{if(A)k(!1)}),children:y?"Undo retirement":"Restore to active context"},void 0,!1,void 0,this),r("p",{children:"Restore is recorded and does not validate."},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("form",{class:"lifecycle-review",onSubmit:(A)=>{A.preventDefault(),V(d,h)},children:[r("label",{children:["Outcome",r("select",{value:d,onChange:(A)=>p(A.currentTarget.value),children:[r("option",{value:"retain",children:"Retain"},void 0,!1,void 0,this),r("option",{value:"revise",children:"Revise"},void 0,!1,void 0,this),r("option",{value:"externalize",children:"Externalize"},void 0,!1,void 0,this),r("option",{value:"retire",children:"Retire from active context"},void 0,!1,void 0,this),r("option",{value:"unresolved",children:"Unresolved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Uses the check note above. Applied retain, revise and externalize require evidence."},void 0,!1,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:h,onChange:(A)=>g(A.currentTarget.checked)},void 0,!1,void 0,this)," ","I applied this outcome and checked the content and sources"]},void 0,!0,void 0,this),r("p",{children:"Revise and externalize record work already performed. They do not edit or execute anything."},void 0,!1,void 0,this),r("button",{type:"submit","aria-disabled":v||_||h&&["retain","revise","externalize"].includes(d)&&(!f.trim()||P||!!x||w?.contentRevision!==i.contentRevision),children:"Record review"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),ee?.recipe&&r("section",{children:[r("h3",{children:"Recipe"},void 0,!1,void 0,this),r("p",{children:[ee.recipe.tool," · ",ee.recipe.prompt]},void 0,!0,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:async()=>{if(!B()||v)return;b(!0);let A=await fa(`Refresh this board using the recorded recipe for ${e.boardId}/${e.nodeId}. Review the recipe before running it. Tool: ${ee.recipe.tool}
389
+ `)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Source changes, contradictions and superseding decisions are observed through explicit relations. Other triggers describe what the reviewer should check."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["How to check",r("input",{required:!0,pattern:".*\\S.*",value:e.revalidationMethod,onInput:(n)=>t({...e,revalidationMethod:n.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Ql=(e)=>({...e,triggers:e.triggers.map((t)=>t.trim()).filter(Boolean)});function Ho(e){if(e.defaultPrevented||!(e.target instanceof Element))return;let t=e.target.closest("button"),n=e.currentTarget;if(t?.type!=="submit"||t.form!==n||t.matches(":disabled"))return;if(e.preventDefault(),!n.noValidate&&!t.formNoValidate&&!n.reportValidity())return;n.dispatchEvent(new SubmitEvent("submit",{bubbles:!0,cancelable:!0,submitter:t}))}function vT(){let e=Ct.value;if(!e||ut.value||se.value!==e.boardId||wt!==e.incarnation||!H.value.has(e.nodeId))return null;return r(mL,{target:e},`${e.boardId}:${e.nodeId}:${e.incarnation}`,!1,void 0,this)}function mL({target:e}){let t=Oe.value,n=D(null),o=D(0),[i,s]=E(null),[a,l]=E(!1),[c,u]=E(xa),[d,p]=E("retain"),[f,m]=E(""),[h,g]=E(!1),[v,b]=E(!1),[x,C]=E(""),[y,k]=E(!1),[_,I]=E(!1),w=H.value.get(e.nodeId),P=ih(e.boardId,e.nodeId),L=Jn(e.nodeId)??i?.qualification,N=`/api/canvas/node/${encodeURIComponent(e.nodeId)}`,Y=()=>se.value===e.boardId&&wt===e.incarnation,B=()=>Oe.value&&Y()&&Ct.value===e,J=async()=>{if(!B())return;let A=tn,te=++o.current,M=await pe("lifecycle",`${N}/lifecycle?board=${encodeURIComponent(e.boardId)}`,null);if(!B()||A!==tn||te!==o.current)return;if(M?.ok!==!0){C("Could not load lifecycle. Retry before reviewing.");return}s(M),I(!1),C(""),l(M.lifecycleSource==="card"),u(M.lifecycle??xa),m(""),g(!1)};q(()=>{let A=document.activeElement,te=n.current;if(Oe.value)te?.querySelector("button")?.focus({preventScroll:!0}),$t(e.nodeId,{recordHistory:!1});return()=>{if(te?.contains(document.activeElement)&&Y()&&A instanceof HTMLElement&&A.isConnected)A.focus({preventScroll:!0})}},[]),Me(()=>{if(!t&&n.current?.contains(document.activeElement))document.querySelector('button[aria-label="Settings"]')?.focus({preventScroll:!0})},[t]),q(()=>{if(!t)return;if(Kt(),!i||_)J()},[t]);let X=async(A,te,M)=>{if(!B()||v||_)return!1;b(!0),C("");let O=await pe("lifecycleWrite",`${N}${A}`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...te,expectedBoardId:e.boardId})});if(!Y())return b(!1),!1;if(!O?.ok)return b(!1),C("Not saved. The card or its sources may have changed. Reload and check the current evidence before retrying."),!1;if(M?.(),Ct.value!==e)return Kt(),b(!1),!1;return I(!0),await J(),await Kt(),b(!1),Y()&&Ct.value===e},V=async(A,te)=>{if(!i)return!1;if(te&&["retain","revise","externalize"].includes(A)&&(!f.trim()||ih(e.boardId,e.nodeId)||w?.contentRevision!==i.contentRevision||x))return!1;return X("/review",{outcome:A,evidence:f,applied:te,expectedContentRevision:i.contentRevision,expectedSources:i.qualification.observations},()=>{if(k(te&&A==="retire"),te&&A==="retire")Is.value=e;m(""),g(!1)})},ee=w?.data.provenance,he=(A)=>A?new Date(A).toLocaleString():"Unknown";return r("div",{class:"lifecycle-dock",hidden:!t,style:t?void 0:{display:"none"},onKeyDown:(A)=>{if(!B())return;if(A.stopPropagation(),A.key==="Escape")A.preventDefault(),Ct.value=null},children:r("div",{ref:n,class:"knowledge-dialog lifecycle-dialog",role:"dialog","aria-label":"Review card",children:[r("header",{children:[r("h2",{children:["Review card · ",String(w?.data.title??"Card")]},void 0,!0,void 0,this),r("button",{type:"button","aria-label":"Close review",onClick:()=>{if(!B())return;Ct.value=null},children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x&&r("p",{role:"alert",children:x},void 0,!1,void 0,this),!i&&x&&r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!v)J()},children:"Reload and recheck"},void 0,!1,void 0,this),Oi.value&&r("p",{role:"status",children:"Live qualification unavailable. Last loaded evidence is shown."},void 0,!1,void 0,this),!i?r("p",{children:"Loading review…"},void 0,!1,void 0,this):r(be,{children:[i.retired?r("div",{class:"lifecycle-review",children:[r("p",{children:"This card is retired. Restoring it does not mark it checked."},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v||_,onClick:()=>void X("/lifecycle/restore",{evidence:"Restored by the human reviewer."}),children:"Restore card"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r("h3",{children:"Why review?"},void 0,!1,void 0,this),L?.due?r("p",{class:"lifecycle-warning",children:["⧗"," ",L.reasons.some((A)=>A.startsWith("Content changed"))?"This card changed since its last check.":"This card needs a fresh check."]},void 0,!0,void 0,this):r("p",{children:["Last checked: ",he(i.lastValidation?.when)]},void 0,!0,void 0,this),L?.reasons.length?r("p",{children:L.reasons.join(" ")},void 0,!1,void 0,this):null,(L?.sources??i.qualification.sources).map((A)=>r("div",{class:"lifecycle-warning",children:["⧗ Source needs a check: ",A.title,!A.unavailable&&r("button",{type:"button",onClick:()=>{if(!B())return;Ct.value=null,zt(A)},children:"Open source →"},void 0,!1,void 0,this)]},`${A.boardId}:${A.cardId}`,!0,void 0,this)),r("form",{class:"lifecycle-quick-review",noValidate:!0,onClick:Ho,onSubmit:(A)=>{A.preventDefault(),V("retain",!0).then((te)=>{if(te&&B())Ct.value=null})},children:[r("p",{children:"Check the card and its sources before confirming."},void 0,!1,void 0,this),P&&r("p",{role:"status",children:"Save the card's edits, then reload and recheck before validating."},void 0,!1,void 0,this),r("label",{children:["What did you check?",r("textarea",{required:!0,rows:2,placeholder:"A short note or source link",value:f,onInput:(A)=>m(A.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"lifecycle-review-actions",children:[r("button",{type:"submit","aria-disabled":v||_||!!x||P||!f.trim()||w?.contentRevision!==i.contentRevision,children:"Checked, still correct"},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!B()||v)return;Ct.value=null},children:"Not now"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(x||w?.contentRevision!==i.contentRevision)&&r("div",{role:"status",children:[r("p",{children:"Reload, check the current card and sources, then write a fresh note."},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!v)J()},children:"Reload and recheck"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("details",{class:"lifecycle-advanced",children:[r("summary",{children:"Settings and history"},void 0,!1,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:()=>{if(!v)J()},children:"Reload lifecycle and source revisions"},void 0,!1,void 0,this),r("p",{class:"lifecycle-category",children:[i.category?`${i.category.glyph} ${i.category.name} · from ${i.categorySourceFolder}`:"No inherited category"," ","· category belongs to the folder"]},void 0,!0,void 0,this),r("form",{onClick:Ho,onSubmit:(A)=>{A.preventDefault(),X("/lifecycle",{lifecycleOverride:a?Ql(c):null})},children:[r("label",{children:[r("input",{type:"checkbox",checked:a,onChange:(A)=>l(A.currentTarget.checked)},void 0,!1,void 0,this)," ","Set a card lifecycle override"]},void 0,!0,void 0,this),a?r(Yl,{value:c,onChange:u},void 0,!1,void 0,this):r("p",{children:["Inherit from ",i.lifecycleSourceFolder??"the folder"," · ",i.lifecycle?.rate??"unknown"]},void 0,!0,void 0,this),r("button",{type:"submit","aria-disabled":v||_,children:"Save lifecycle"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"lifecycle-clocks",children:[r("div",{class:"is-read",children:[r("span",{children:"Read by agent"},void 0,!1,void 0,this),r("strong",{children:he(i.qualification.lastReadAt)},void 0,!1,void 0,this),r("small",{children:"Delivery only, not validation"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{children:[r("span",{children:"Content changed"},void 0,!1,void 0,this),r("strong",{children:he(i.qualification.contentChangedAt)},void 0,!1,void 0,this),r("small",{children:["Revision ",i.contentRevision]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{children:[r("span",{children:"Last validated"},void 0,!1,void 0,this),r("strong",{children:he(i.lastValidation?.when)},void 0,!1,void 0,this),r("small",{children:i.lastValidation?.evidence??"No evidence-backed validation"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{children:[r("span",{children:"Task relevance"},void 0,!1,void 0,this),r("strong",{children:i.qualification.relevance==="card-pinned"?"Card pinned":i.qualification.relevance==="board-pinned"?"Board pinned":"Not explicitly selected"},void 0,!1,void 0,this),r("small",{children:"Curation, not a truth claim"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Reading, refreshing and regeneration never count as validating."},void 0,!1,void 0,this),L?.due&&r("p",{class:"lifecycle-warning",children:["⧗ review due · ",L.reasons.join(" ")]},void 0,!0,void 0,this),(L?.sources??i.qualification.sources).map((A)=>r("div",{class:"lifecycle-warning",children:["⧗ ",A.title," · ",A.reasons.join(" "),A.observedAt&&r("span",{children:[" · observed ",he(A.observedAt)]},void 0,!0,void 0,this),A.observedRevision!==void 0&&r("span",{children:[" · source revision ",A.observedRevision]},void 0,!0,void 0,this),!A.unavailable&&r("button",{type:"button",onClick:()=>{if(!B())return;Ct.value=null,zt(A)},children:"Open source →"},void 0,!1,void 0,this)]},`${A.boardId}:${A.cardId}`,!0,void 0,this)),w?.contentRevision!==i.contentRevision&&r("p",{role:"alert",children:"Content changed while this review was open. Reload and check it before applying."},void 0,!1,void 0,this),i.retired?r("div",{class:"lifecycle-review",children:[r("p",{role:"status",children:"Retired from active context. Content and history remain."},void 0,!1,void 0,this),r("label",{children:["Restoration note",r("input",{value:f,onInput:(A)=>m(A.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button","aria-disabled":v||_,onClick:()=>void X("/lifecycle/restore",{evidence:f||"Restored by the human reviewer."}).then((A)=>{if(A)k(!1)}),children:y?"Undo retirement":"Restore to active context"},void 0,!1,void 0,this),r("p",{children:"Restore is recorded and does not validate."},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("form",{class:"lifecycle-review",onClick:Ho,onSubmit:(A)=>{A.preventDefault(),V(d,h)},children:[r("label",{children:["Outcome",r("select",{value:d,onChange:(A)=>p(A.currentTarget.value),children:[r("option",{value:"retain",children:"Retain"},void 0,!1,void 0,this),r("option",{value:"revise",children:"Revise"},void 0,!1,void 0,this),r("option",{value:"externalize",children:"Externalize"},void 0,!1,void 0,this),r("option",{value:"retire",children:"Retire from active context"},void 0,!1,void 0,this),r("option",{value:"unresolved",children:"Unresolved"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Uses the check note above. Applied retain, revise and externalize require evidence."},void 0,!1,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:h,onChange:(A)=>g(A.currentTarget.checked)},void 0,!1,void 0,this)," ","I applied this outcome and checked the content and sources"]},void 0,!0,void 0,this),r("p",{children:"Revise and externalize record work already performed. They do not edit or execute anything."},void 0,!1,void 0,this),r("button",{type:"submit","aria-disabled":v||_||h&&["retain","revise","externalize"].includes(d)&&(!f.trim()||P||!!x||w?.contentRevision!==i.contentRevision),children:"Record review"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),ee?.recipe&&r("section",{children:[r("h3",{children:"Recipe"},void 0,!1,void 0,this),r("p",{children:[ee.recipe.tool," · ",ee.recipe.prompt]},void 0,!0,void 0,this),r("button",{type:"button","aria-disabled":v,onClick:async()=>{if(!B()||v)return;b(!0);let A=await ma(`Refresh this board using the recorded recipe for ${e.boardId}/${e.nodeId}. Review the recipe before running it. Tool: ${ee.recipe.tool}
390
390
  Input: ${JSON.stringify(ee.recipe.input??null)}
391
391
  Prompt: ${ee.recipe.prompt}
392
- Regeneration is not validation. Preserve source observations and report evidence separately.`);b(!1),C(A?"Recipe request sent. No tool was executed by Canvas.":"Could not send the request. No tool was executed.")},children:"Ask agent to refresh this board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("section",{children:[r("h3",{children:"Review history"},void 0,!1,void 0,this),i.records.length===0&&r("p",{children:"No reviews recorded."},void 0,!1,void 0,this),[...i.records].reverse().map((A)=>r("div",{class:"lifecycle-history",children:[r("strong",{children:[A.outcome,!A.applied?" · not applied":""]},void 0,!0,void 0,this),r("span",{children:[he(A.when)," · ",A.who.actor," · ",A.who.source]},void 0,!0,void 0,this),r("p",{children:A.evidence||"No evidence"},void 0,!1,void 0,this)]},A.id,!0,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)},void 0,!1,void 0,this)}function bT(){let[e,t]=E(null),n=oe((a,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"node",x:a.clientX,y:a.clientY,nodeId:l})},[]),o=oe((a,l,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"canvas",x:a.clientX,y:a.clientY,canvasX:l,canvasY:c})},[]),i=oe((a,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"edge",x:a.clientX,y:a.clientY,edgeId:l})},[]),s=oe(()=>t(null),[]);return Me(()=>{if(!e)return;let a=()=>t(null),l=(c)=>{if(c.key==="Escape")t(null)};return document.addEventListener("click",a),document.addEventListener("keydown",l),()=>{document.removeEventListener("click",a),document.removeEventListener("keydown",l)}},[e]),{menu:e,openNodeMenu:n,openCanvasMenu:o,openEdgeMenu:i,closeMenu:s}}var hL="#4bbcFF",gL=[{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 xT({menu:e,onClose:t}){let n;if(e.kind==="node"){let l=H.value.get(e.nodeId);if(!l)return null;n=kL(l)}else if(e.kind==="edge"){let l=e.edgeId,c=et.value.get(l),u=wt;n=[{label:"Relation kind…",render:()=>r("label",{class:"relation-kind-control",children:["Kind"," ",r("select",{"aria-label":"Relation kind",value:c?Gn(c):"",onChange:(d)=>{let p=d.currentTarget.value;if(p==="__custom__")t(),On("Relation kind","An open kind, such as supports").then((f)=>{if(f?.trim()&&u===wt)Fi(l,{kind:f.trim()})});else Fi(l,{kind:p})},children:[[...new Set([...(Yn()?.relationVocabulary??Kl).map((d)=>d.kind),...c?[Gn(c)]:[]])].map((d)=>r("option",{value:d,children:d},d,!1,void 0,this)),r("option",{value:"__custom__",children:"Custom kind…"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},{label:c?.reason?"Edit why…":"Add why…",action:()=>{On("Why this relation exists","One sentence explaining the link",{initial:c?.reason??"",allowEmpty:!0,confirm:"Save"}).then((d)=>{if(d!==null&&u===wt)Fi(l,{reason:d})})}},{label:c?.label?`Edit label “${c.label.slice(0,18)}${c.label.length>18?"…":""}”`:"Add label…",action:()=>{On("Edge label (empty clears it)","label text",{initial:c?.label??"",allowEmpty:!0,confirm:"Save"}).then((d)=>{if(d===null||u!==wt)return;Fi(l,{label:d})})}},{separator:!0},...["flow","depends-on","relation","references"].map((d)=>({label:`${c?.type===d?"✓":" "} ${d}`,action:()=>void Fi(l,{type:d})})),{separator:!0},...["solid","dashed","dotted"].map((d)=>({label:`${(c?.style??"solid")===d?"✓":" "} ${d}`,action:()=>void Fi(l,{style:d})})),{separator:!0},{label:"Delete edge",danger:!0,action:()=>void xu(l)}]}else n=wL(e.canvasX,e.canvasY);let o=new Map,i=n.some((l)=>l.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-i));return r("div",{class:"context-menu",style:{position:"fixed",left:`${s}px`,top:`${a}px`,zIndex:1e4},onPointerDown:(l)=>l.stopPropagation(),onClick:(l)=>l.stopPropagation(),children:n.map((l)=>{let c=l.separator?"separator":l.render?"custom":`${l.label??"item"}:${l.shortcut??""}`,u=(o.get(c)??0)+1;o.set(c,u);let d=`${c}:${u}`;if(l.separator)return r("div",{class:"context-menu-separator"},d,!1,void 0,this);if(l.render)return r("div",{class:"context-menu-custom",children:l.render(t)},d,!1,void 0,this);return r("button",{type:"button",class:`context-menu-item${l.danger?" is-danger":""}`,onClick:()=>{l.action?.(),t()},children:[r("span",{class:"context-menu-label",children:l.label},void 0,!1,void 0,this),l.shortcut&&r("span",{class:"context-menu-shortcut",children:l.shortcut},void 0,!1,void 0,this)]},d,!0,void 0,this)})},void 0,!1,void 0,this)}function yL(e){return(typeof e.data.path==="string"?e.data.path.trim():"")||null}function op(e){let t=e.trim().toLowerCase(),n=t.match(/^#([0-9a-f]{3})$/);if(n){let[o,i,s]=n[1].split("");return`#${o}${o}${i}${i}${s}${s}`}return t}function wT(e){if(typeof e.data.color!=="string"||!e.data.color.trim())return null;return op(e.data.color)}function vL(e){let t=wT(e);return t&&/^#[0-9a-f]{6}$/.test(t)?t:op(hL)}function Sg(e,t){let n=t?op(t):null;un(e.id,{data:{...e.data,color:n}}),ln(e.id,{data:{color:n}})}function bL(e,t){let n=wT(e);return r("div",{class:"context-menu-section",children:[r("div",{class:"context-menu-section-header",children:[r("span",{class:"context-menu-section-label",children:"Group color"},void 0,!1,void 0,this),r("button",{type:"button",class:"context-menu-reset",onClick:()=>{Sg(e,null),t()},children:"Theme default"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"context-menu-color-grid",children:gL.map((o)=>{let i=op(o.value);return r("button",{type:"button",class:`context-menu-color-swatch${n===i?" active":""}`,"aria-label":`Set group color to ${o.label}`,style:{"--swatch-color":o.value},onClick:()=>{Sg(e,o.value),t()},children:[r("span",{class:"context-menu-color-dot",style:{"--swatch-color":o.value}},void 0,!1,void 0,this),r("span",{children:o.label},void 0,!1,void 0,this)]},o.value,!0,void 0,this)})},void 0,!1,void 0,this),r("label",{class:"context-menu-color-custom",children:[r("span",{children:"Custom"},void 0,!1,void 0,this),r("input",{type:"color",class:"context-menu-color-input","aria-label":"Custom group color",value:vL(e),onClick:(o)=>o.stopPropagation(),onInput:(o)=>{Sg(e,o.currentTarget.value),t()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Cg(e,t,n,o){return{x:e-n/2,y:t-o/2}}function xL(e,t){return e.trim().replace(/[?#].*$/,"").split("/").filter(Boolean).at(-1)||t}async function _g(e){let t=await On(e.promptLabel,e.placeholder??"");if(!t)return;let n=t.trim();if(!n)return;let o=Cg(e.canvasX,e.canvasY,e.width,e.height);if(!(await No({type:e.type,...e.type!=="webpage"?{title:xL(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 wL(e,t){return[{label:"New note",action:()=>{let i=Cg(e,t,520,360);No({type:"markdown",title:"New note",x:i.x,y:i.y,width:520,height:360})}},{label:"Open webpage...",action:()=>{_g({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:()=>{_g({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:()=>{_g({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 i=Cg(e,t,600,400);Ns({title:"Group",x:i.x,y:i.y,width:600,height:400})}}]}function kL(e){let t=[],n=yL(e);if(Oe.value)t.push({label:"Review",action:()=>Es(e.id)});if(t.push({label:"Focus",action:()=>$t(e.id)}),t.push({label:"Rename…",action:()=>{On("Rename node","Node title",{initial:typeof e.data.title==="string"?e.data.title:"",confirm:"Save"}).then((c)=>{if(!c?.trim())return;ln(e.id,{title:c.trim()})})}}),qa.has(e.type))t.push({label:"Expand",shortcut:"⤢",action:()=>xo(e.id)});if(t.push({label:e.collapsed?"Expand":"Collapse",action:()=>Hi(e.id)}),nd(e))t.push({label:"Open in new tab",action:()=>void od(e)});let o=kt.value.has(e.id);t.push({label:o?"Unpin from context":"Pin as context",action:()=>lo(e.id)}),t.push({label:e.pinned?"Unlock position":"Lock position (no auto-arrange)",action:()=>{let c=!e.pinned;un(e.id,{pinned:c}),ln(e.id,{pinned:c}),dn()}});let i=cl.value;if(i&&i.from!==e.id){let c=H.value.get(i.from),u=c?(c.data.title||c.id).slice(0,20):i.from;t.push({label:`Connect from "${u}"`,action:()=>{yr(i.from,e.id,"relation"),cl.value=null}})}t.push({label:i?"Connect from here (replace)":"Connect from here",action:()=>{cl.value={from:e.id}}}),t.push({label:"Connect to a card on another board…",action:()=>window.dispatchEvent(new CustomEvent("pmx-open-board-link",{detail:{sourceNodeId:e.id}}))});let s=Array.from(et.value.values()).filter((c)=>c.from===e.id||!c.toBoardId&&c.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 c=e.data.chartConfig.title||"chart";t.push({label:"Copy chart data",action:()=>{navigator.clipboard.writeText(JSON.stringify(e.data.chartConfig,null,2))}})}else{let c=e.data.url;if(t.push({label:"Open in browser",action:()=>{if(c)window.open(c,"_blank")}}),t.push({label:"Focus in TUI",action:()=>dk("mcp-app-focus",{url:c})}),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 c=typeof e.data.url==="string"?e.data.url:"";t.push({label:"Refresh webpage",action:()=>{yu(e.id)}}),t.push({label:"Open in browser",action:()=>{if(c)window.open(c,"_blank","noopener")}}),t.push({label:"Copy URL",action:()=>{if(c)navigator.clipboard.writeText(c)}})}if(e.type==="group"){let c=e.data.children??[];if(t.push({separator:!0}),t.push({render:(u)=>bL(e,u)}),c.length>0)t.push({label:`Ungroup (${c.length} node${c.length!==1?"s":""})`,action:()=>{ei(e.id),Ms(e.id)}})}let a=typeof e.data.parentGroup==="string"?e.data.parentGroup:null,l=a?H.value.get(a):void 0;if(l&&l.type==="group"){let c=typeof l.data.title==="string"&&l.data.title?l.data.title:"frame",u=Array.isArray(l.data.children)?l.data.children.filter((d)=>d!==e.id):[];t.push({label:`Remove from “${c}”`,action:()=>{bu(l.id,u)}})}return t.push({separator:!0}),t.push({label:e.type==="group"?"Delete frame (children stay)":"Delete",danger:!0,action:()=>{Xr(e.id)}}),t}function kT({onClose:e}){let t=D(null),[n,o]=E("Bug report"),[i,s]=E(""),[a,l]=E("");return bn(t,!0),r("div",{class:"text-prompt-backdrop feedback-backdrop",onPointerDown:e,children:r("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:(c)=>c.stopPropagation(),onKeyDown:(c)=>{if(c.stopPropagation(),c.key==="Escape")c.preventDefault(),e()},children:[r("div",{id:"feedback-title",class:"text-prompt-title",children:"Bug and feedback"},void 0,!1,void 0,this),r("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),r("div",{class:"feedback-field",children:[r("span",{children:"Feedback type"},void 0,!1,void 0,this),r(Mr,{label:"Feedback type",value:n,onChange:o,options:["Bug report","Feature request","General feedback"].map((c)=>({value:c,label:c}))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Title",r("input",{class:"text-prompt-input",name:"title",required:!0,maxLength:120,value:i,onInput:(c)=>s(c.currentTarget.value),placeholder:"A short summary"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Description",r("textarea",{class:"text-prompt-input",required:!0,maxLength:1200,rows:6,value:a,onInput:(c)=>l(c.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),r("input",{type:"hidden",name:"body",value:`## ${n}
392
+ Regeneration is not validation. Preserve source observations and report evidence separately.`);b(!1),C(A?"Recipe request sent. No tool was executed by Canvas.":"Could not send the request. No tool was executed.")},children:"Ask agent to refresh this board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("section",{children:[r("h3",{children:"Review history"},void 0,!1,void 0,this),i.records.length===0&&r("p",{children:"No reviews recorded."},void 0,!1,void 0,this),[...i.records].reverse().map((A)=>r("div",{class:"lifecycle-history",children:[r("strong",{children:[A.outcome,!A.applied?" · not applied":""]},void 0,!0,void 0,this),r("span",{children:[he(A.when)," · ",A.who.actor," · ",A.who.source]},void 0,!0,void 0,this),r("p",{children:A.evidence||"No evidence"},void 0,!1,void 0,this)]},A.id,!0,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)},void 0,!1,void 0,this)}function bT(){let[e,t]=E(null),n=oe((a,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"node",x:a.clientX,y:a.clientY,nodeId:l})},[]),o=oe((a,l,c)=>{a.preventDefault(),a.stopPropagation(),t({kind:"canvas",x:a.clientX,y:a.clientY,canvasX:l,canvasY:c})},[]),i=oe((a,l)=>{a.preventDefault(),a.stopPropagation(),t({kind:"edge",x:a.clientX,y:a.clientY,edgeId:l})},[]),s=oe(()=>t(null),[]);return Me(()=>{if(!e)return;let a=()=>t(null),l=(c)=>{if(c.key==="Escape")t(null)};return document.addEventListener("click",a),document.addEventListener("keydown",l),()=>{document.removeEventListener("click",a),document.removeEventListener("keydown",l)}},[e]),{menu:e,openNodeMenu:n,openCanvasMenu:o,openEdgeMenu:i,closeMenu:s}}var hL="#4bbcFF",gL=[{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 xT({menu:e,onClose:t}){let n;if(e.kind==="node"){let l=H.value.get(e.nodeId);if(!l)return null;n=kL(l)}else if(e.kind==="edge"){let l=e.edgeId,c=et.value.get(l),u=wt;n=[{label:"Relation kind…",render:()=>r("label",{class:"relation-kind-control",children:["Kind"," ",r("select",{"aria-label":"Relation kind",value:c?Gn(c):"",onChange:(d)=>{let p=d.currentTarget.value;if(p==="__custom__")t(),On("Relation kind","An open kind, such as supports").then((f)=>{if(f?.trim()&&u===wt)Fi(l,{kind:f.trim()})});else Fi(l,{kind:p})},children:[[...new Set([...(Yn()?.relationVocabulary??Kl).map((d)=>d.kind),...c?[Gn(c)]:[]])].map((d)=>r("option",{value:d,children:d},d,!1,void 0,this)),r("option",{value:"__custom__",children:"Custom kind…"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},{label:c?.reason?"Edit why…":"Add why…",action:()=>{On("Why this relation exists","One sentence explaining the link",{initial:c?.reason??"",allowEmpty:!0,confirm:"Save"}).then((d)=>{if(d!==null&&u===wt)Fi(l,{reason:d})})}},{label:c?.label?`Edit label “${c.label.slice(0,18)}${c.label.length>18?"…":""}”`:"Add label…",action:()=>{On("Edge label (empty clears it)","label text",{initial:c?.label??"",allowEmpty:!0,confirm:"Save"}).then((d)=>{if(d===null||u!==wt)return;Fi(l,{label:d})})}},{separator:!0},...["flow","depends-on","relation","references"].map((d)=>({label:`${c?.type===d?"✓":" "} ${d}`,action:()=>void Fi(l,{type:d})})),{separator:!0},...["solid","dashed","dotted"].map((d)=>({label:`${(c?.style??"solid")===d?"✓":" "} ${d}`,action:()=>void Fi(l,{style:d})})),{separator:!0},{label:"Delete edge",danger:!0,action:()=>void wu(l)}]}else n=wL(e.canvasX,e.canvasY);let o=new Map,i=n.some((l)=>l.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-i));return r("div",{class:"context-menu",style:{position:"fixed",left:`${s}px`,top:`${a}px`,zIndex:1e4},onPointerDown:(l)=>l.stopPropagation(),onClick:(l)=>l.stopPropagation(),children:n.map((l)=>{let c=l.separator?"separator":l.render?"custom":`${l.label??"item"}:${l.shortcut??""}`,u=(o.get(c)??0)+1;o.set(c,u);let d=`${c}:${u}`;if(l.separator)return r("div",{class:"context-menu-separator"},d,!1,void 0,this);if(l.render)return r("div",{class:"context-menu-custom",children:l.render(t)},d,!1,void 0,this);return r("button",{type:"button",class:`context-menu-item${l.danger?" is-danger":""}`,onClick:()=>{l.action?.(),t()},children:[r("span",{class:"context-menu-label",children:l.label},void 0,!1,void 0,this),l.shortcut&&r("span",{class:"context-menu-shortcut",children:l.shortcut},void 0,!1,void 0,this)]},d,!0,void 0,this)})},void 0,!1,void 0,this)}function yL(e){return(typeof e.data.path==="string"?e.data.path.trim():"")||null}function rp(e){let t=e.trim().toLowerCase(),n=t.match(/^#([0-9a-f]{3})$/);if(n){let[o,i,s]=n[1].split("");return`#${o}${o}${i}${i}${s}${s}`}return t}function wT(e){if(typeof e.data.color!=="string"||!e.data.color.trim())return null;return rp(e.data.color)}function vL(e){let t=wT(e);return t&&/^#[0-9a-f]{6}$/.test(t)?t:rp(hL)}function Cg(e,t){let n=t?rp(t):null;un(e.id,{data:{...e.data,color:n}}),ln(e.id,{data:{color:n}})}function bL(e,t){let n=wT(e);return r("div",{class:"context-menu-section",children:[r("div",{class:"context-menu-section-header",children:[r("span",{class:"context-menu-section-label",children:"Group color"},void 0,!1,void 0,this),r("button",{type:"button",class:"context-menu-reset",onClick:()=>{Cg(e,null),t()},children:"Theme default"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"context-menu-color-grid",children:gL.map((o)=>{let i=rp(o.value);return r("button",{type:"button",class:`context-menu-color-swatch${n===i?" active":""}`,"aria-label":`Set group color to ${o.label}`,style:{"--swatch-color":o.value},onClick:()=>{Cg(e,o.value),t()},children:[r("span",{class:"context-menu-color-dot",style:{"--swatch-color":o.value}},void 0,!1,void 0,this),r("span",{children:o.label},void 0,!1,void 0,this)]},o.value,!0,void 0,this)})},void 0,!1,void 0,this),r("label",{class:"context-menu-color-custom",children:[r("span",{children:"Custom"},void 0,!1,void 0,this),r("input",{type:"color",class:"context-menu-color-input","aria-label":"Custom group color",value:vL(e),onClick:(o)=>o.stopPropagation(),onInput:(o)=>{Cg(e,o.currentTarget.value),t()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Ig(e,t,n,o){return{x:e-n/2,y:t-o/2}}function xL(e,t){return e.trim().replace(/[?#].*$/,"").split("/").filter(Boolean).at(-1)||t}async function Tg(e){let t=await On(e.promptLabel,e.placeholder??"");if(!t)return;let n=t.trim();if(!n)return;let o=Ig(e.canvasX,e.canvasY,e.width,e.height);if(!(await No({type:e.type,...e.type!=="webpage"?{title:xL(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 wL(e,t){return[{label:"New note",action:()=>{let i=Ig(e,t,520,360);No({type:"markdown",title:"New note",x:i.x,y:i.y,width:520,height:360})}},{label:"Open webpage...",action:()=>{Tg({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:()=>{Tg({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:()=>{Tg({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 i=Ig(e,t,600,400);Ns({title:"Group",x:i.x,y:i.y,width:600,height:400})}}]}function kL(e){let t=[],n=yL(e);if(Oe.value)t.push({label:"Review",action:()=>Es(e.id)});if(t.push({label:"Focus",action:()=>$t(e.id)}),t.push({label:"Rename…",action:()=>{On("Rename node","Node title",{initial:typeof e.data.title==="string"?e.data.title:"",confirm:"Save"}).then((c)=>{if(!c?.trim())return;ln(e.id,{title:c.trim()})})}}),Ga.has(e.type))t.push({label:"Expand",shortcut:"⤢",action:()=>xo(e.id)});if(t.push({label:e.collapsed?"Expand":"Collapse",action:()=>Hi(e.id)}),od(e))t.push({label:"Open in new tab",action:()=>void rd(e)});let o=kt.value.has(e.id);t.push({label:o?"Unpin from context":"Pin as context",action:()=>lo(e.id)}),t.push({label:e.pinned?"Unlock position":"Lock position (no auto-arrange)",action:()=>{let c=!e.pinned;un(e.id,{pinned:c}),ln(e.id,{pinned:c}),dn()}});let i=ul.value;if(i&&i.from!==e.id){let c=H.value.get(i.from),u=c?(c.data.title||c.id).slice(0,20):i.from;t.push({label:`Connect from "${u}"`,action:()=>{yr(i.from,e.id,"relation"),ul.value=null}})}t.push({label:i?"Connect from here (replace)":"Connect from here",action:()=>{ul.value={from:e.id}}}),t.push({label:"Connect to a card on another board…",action:()=>window.dispatchEvent(new CustomEvent("pmx-open-board-link",{detail:{sourceNodeId:e.id}}))});let s=Array.from(et.value.values()).filter((c)=>c.from===e.id||!c.toBoardId&&c.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 c=e.data.chartConfig.title||"chart";t.push({label:"Copy chart data",action:()=>{navigator.clipboard.writeText(JSON.stringify(e.data.chartConfig,null,2))}})}else{let c=e.data.url;if(t.push({label:"Open in browser",action:()=>{if(c)window.open(c,"_blank")}}),t.push({label:"Focus in TUI",action:()=>fk("mcp-app-focus",{url:c})}),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 c=typeof e.data.url==="string"?e.data.url:"";t.push({label:"Refresh webpage",action:()=>{yu(e.id)}}),t.push({label:"Open in browser",action:()=>{if(c)window.open(c,"_blank","noopener")}}),t.push({label:"Copy URL",action:()=>{if(c)navigator.clipboard.writeText(c)}})}if(e.type==="group"){let c=e.data.children??[];if(t.push({separator:!0}),t.push({render:(u)=>bL(e,u)}),c.length>0)t.push({label:`Ungroup (${c.length} node${c.length!==1?"s":""})`,action:()=>{ei(e.id),Ms(e.id)}})}let a=typeof e.data.parentGroup==="string"?e.data.parentGroup:null,l=a?H.value.get(a):void 0;if(l&&l.type==="group"){let c=typeof l.data.title==="string"&&l.data.title?l.data.title:"frame",u=Array.isArray(l.data.children)?l.data.children.filter((d)=>d!==e.id):[];t.push({label:`Remove from “${c}”`,action:()=>{xu(l.id,u)}})}return t.push({separator:!0}),t.push({label:e.type==="group"?"Delete frame (children stay)":"Delete",danger:!0,action:()=>{Xr(e.id)}}),t}function kT({onClose:e}){let t=D(null),[n,o]=E("Bug report"),[i,s]=E(""),[a,l]=E("");return bn(t,!0),r("div",{class:"text-prompt-backdrop feedback-backdrop",onPointerDown:e,children:r("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:(c)=>c.stopPropagation(),onKeyDown:(c)=>{if(c.stopPropagation(),c.key==="Escape")c.preventDefault(),e()},children:[r("div",{id:"feedback-title",class:"text-prompt-title",children:"Bug and feedback"},void 0,!1,void 0,this),r("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),r("div",{class:"feedback-field",children:[r("span",{children:"Feedback type"},void 0,!1,void 0,this),r(Mr,{label:"Feedback type",value:n,onChange:o,options:["Bug report","Feature request","General feedback"].map((c)=>({value:c,label:c}))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Title",r("input",{class:"text-prompt-input",name:"title",required:!0,maxLength:120,value:i,onInput:(c)=>s(c.currentTarget.value),placeholder:"A short summary"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Description",r("textarea",{class:"text-prompt-input",required:!0,maxLength:1200,rows:6,value:a,onInput:(c)=>l(c.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),r("input",{type:"hidden",name:"body",value:`## ${n}
393
393
 
394
- ${a.trim()}`},void 0,!1,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",onClick:e,children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"submit",class:"text-prompt-confirm",disabled:!i.trim()||!a.trim(),children:["Continue on GitHub ",r(ri,{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 ec(e,t){console.error(`[tool-rail] ${e} failed`,t)}function as(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"}};On(t[e].message,t[e].placeholder).then((n)=>{if(!n)return;Eo({type:e,content:n}).catch((o)=>ec(`create ${e}`,o))})}function to({label:e,shortcut:t,detail:n,ariaLabel:o,active:i,menuOpen:s,onClick:a,btnRef:l,children:c}){let[u,d]=E(null),p=(h)=>{let g=h.currentTarget.getBoundingClientRect();d({left:g.right+10,top:g.top+g.height/2})},f=()=>d(null),m=o??(t?`${e} (${t})`:n?`${e} (${n})`:e);return r(be,{children:[r("button",{ref:l,type:"button",class:`rail-btn${i?" active":""}`,"aria-label":m,"aria-pressed":i===void 0?void 0:i,onClick:(h)=>{f(),a(h)},onPointerEnter:p,onPointerLeave:f,onFocus:p,onBlur:f,children:c},void 0,!1,void 0,this),u&&!s&&r("span",{class:"toolbar-tooltip rail-tooltip",role:"tooltip","data-testid":"rail-tooltip",style:{left:`${u.left}px`,top:`${u.top}px`},children:[r("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),(t||n)&&r("span",{class:"toolbar-tooltip-meta",children:[t&&r("kbd",{class:"toolbar-tooltip-shortcut",children:t},void 0,!1,void 0,this),n&&r("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 rr({label:e,description:t,hint:n,beta:o,toggle:i=o,checked:s,disabled:a,onClick:l}){let c=by(),[u,d]=E(null),p=(m)=>d(m.currentTarget.getBoundingClientRect()),f=()=>d(null);return r(be,{children:[r("button",{type:"button",role:s===void 0?"menuitem":"menuitemcheckbox","aria-label":o?`${e} (Beta)`:e,"aria-checked":s,"aria-describedby":u?c:void 0,class:"toolbar-menu-item","aria-disabled":a||void 0,onPointerEnter:p,onPointerLeave:f,onFocus:p,onBlur:f,onClick:()=>{if(a)return;f(),l()},children:[r("span",{class:"settings-item-label",children:[e," ",o&&r("span",{class:"beta-tag",children:"Beta"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i?r("span",{class:`settings-switch${s?" is-on":""}`,"aria-hidden":"true"},void 0,!1,void 0,this):n?r("span",{class:"toolbar-menu-hint",children:n},void 0,!1,void 0,this):null]},void 0,!0,void 0,this),u&&r(Zs,{children:r("span",{id:c,class:"toolbar-tooltip settings-tooltip",role:"tooltip",ref:(m)=>{if(!m)return;let h=window.innerWidth-u.right>=m.offsetWidth+20;m.style.left=`${h?u.right+10:Math.max(12,Math.min(u.left,window.innerWidth-m.offsetWidth-12))}px`,m.style.top=`${Math.max(12,Math.min(h?u.top:u.top-m.offsetHeight-8,window.innerHeight-m.offsetHeight-12))}px`},children:[r("span",{class:"toolbar-tooltip-label",children:[e,o?" (Beta)":""]},void 0,!0,void 0,this),r("span",{class:"toolbar-tooltip-body",children:t},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 ST({minimapVisible:e,onToggleMinimap:t,snapshotOpen:n,onToggleSnapshot:o,snapshotBtnRef:i,onOpenPalette:s,onOpenShortcuts:a,annotationTool:l,onSetAnnotationTool:c}){let u=Wn.value,d=Os.value,p=Array.from(H.value.values()).filter((V)=>V.type==="trace").length,f=et.value.size,[m,h]=E(!1),[g,v]=E(!1),[b,x]=E(!1),C=async(V)=>{if(g||!Wr.value)return;v(!0),x(!1);try{let ee=await de("saveWorkspaceSettings","/api/canvas/settings",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({[V]:!Wr.value[V]})});x(ee.ok!==!0)}finally{v(!1)}},[y,k]=E(null),[_,I]=E(null),w=D(null),P=D(null),L=(V)=>{if(y){k(null);return}let ee=V.currentTarget.getBoundingClientRect();I({bottom:ee.bottom,right:ee.right}),k("settings")},N=(V)=>()=>{k(null),i.current?.focus(),V()},Y=_?{position:"fixed",left:`${_.right+8}px`,bottom:`${Math.max(10,window.innerHeight-_.bottom)}px`,top:"auto",right:"auto"}:void 0;Me(()=>{if(!y)return;let V=(he)=>{if(w.current&&he.target instanceof Node&&!w.current.contains(he.target))k(null)},ee=(he)=>{if(he.key==="Escape")he.preventDefault(),he.stopPropagation(),k(null),i.current?.focus({preventScroll:!0})};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",ee,!0),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",ee,!0)}},[y]);let B=(V)=>{np(),document.documentElement.setAttribute("data-theme",V),aa(),Qt.value=V,hu(V),k(null)},J=uh(Qt.value),X=(V,ee={})=>{Gt(`/api/workbench/intent?_ts=${Date.now()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:V,payload:ee})}).catch((he)=>ec("sendIntent",he))};return r(be,{children:[r("div",{class:"tool-rail",ref:w,role:"toolbar","aria-label":"Canvas tools","aria-orientation":"vertical",children:[r(to,{label:"Home",ariaLabel:"PMX Canvas — Home",onClick:()=>{k(null),Mn(null).catch((V)=>ec("openHome",V))},children:r("span",{class:"rail-brand",children:r(Mu,{size:22},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),!ut.value&&r(be,{children:[r("div",{class:"rail-divider"},void 0,!1,void 0,this),r(to,{label:"Select",shortcut:"V",active:u==="select",onClick:()=>Wn.value="select",children:r(xS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Pan",shortcut:"Space",active:u==="pan",onClick:()=>Wn.value="pan",children:r(wS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Connect",shortcut:"C",active:u==="connect",onClick:()=>Wn.value="connect",children:r("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:[r("circle",{cx:"4",cy:"4",r:"2"},void 0,!1,void 0,this),r("circle",{cx:"12",cy:"12",r:"2"},void 0,!1,void 0,this),r("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),r("div",{class:"rail-divider"},void 0,!1,void 0,this),r(to,{label:"Markdown note",shortcut:"M",onClick:()=>void Eo({type:"markdown",title:"New note",width:520,height:360}).catch((V)=>ec("create markdown",V)),children:r(ni,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{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:()=>P.current?.click(),children:r(pS,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("input",{ref:P,type:"file",hidden:!0,multiple:!0,"aria-label":"Attach files",onChange:(V)=>{let ee=Jt(),he=Te.value;ca(Array.from(V.currentTarget.files??[]),(ee.width/2-he.x)/he.scale,(ee.height/2-he.y)/he.scale),V.currentTarget.value=""}},void 0,!1,void 0,this),r(to,{label:"Webpage",shortcut:"W",onClick:()=>as("webpage"),children:r(Hs,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Group",shortcut:"G",onClick:()=>void Eo({type:"group",title:"Group"}).catch((V)=>ec("create group",V)),children:r(xm,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Draw",shortcut:"A",active:l==="pen",onClick:()=>c(l==="pen"?null:"pen"),children:r(yS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Text note",active:l==="text",onClick:()=>c(l==="text"?null:"text"),children:r(bS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Eraser",active:l==="eraser",onClick:()=>c(l==="eraser"?null:"eraser"),children:r(vS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"rail-divider"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!ut.value&&r(to,{label:"Search & commands",shortcut:Ft("K"),onClick:s,children:r(Nu,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),!ut.value&&r(to,{label:"Arrange",detail:f>0?"graph-aware":"grid",onClick:()=>f>0?Iu():Tu(),children:r(Tr,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"rail-spacer"},void 0,!1,void 0,this),r("span",{class:"toolbar-menu-anchor",children:[r(to,{label:"Settings",detail:"Appearance, board tools, beta features, and feedback",ariaLabel:"Settings",menuOpen:y!==null,active:y!==null||n,onClick:L,btnRef:i,children:r("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:r("path",{d:"M4 7h9M17 7h3M4 17h3M11 17h9M13 7a2 2 0 1 0 4 0a2 2 0 1 0-4 0M7 17a2 2 0 1 0 4 0a2 2 0 1 0-4 0"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),y==="settings"&&r("div",{class:"toolbar-menu rail-settings-menu",style:Y,role:"menu","aria-label":"Settings",children:[r(rr,{label:"Theme",description:"Choose the canvas appearance. Your choice is saved with the board.",hint:`${Qs[J].label} ›`,onClick:()=>k("theme")},void 0,!1,void 0,this),!ut.value&&r(be,{children:[r(rr,{label:"Snapshots",description:"Save a board checkpoint, compare changes, or restore an earlier version.",onClick:N(o)},void 0,!1,void 0,this),r(rr,{label:"Minimap",description:"Show a small overview of the board. Drag its viewport to move around the canvas.",checked:e,hint:e?"On":"Off",onClick:N(t)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(rr,{label:"Keyboard shortcuts",description:"See shortcuts for creating cards, selecting, navigating, and editing the canvas.",hint:"?",onClick:N(a)},void 0,!1,void 0,this),r("div",{class:"toolbar-menu-divider",role:"separator"},void 0,!1,void 0,this),r("span",{class:"settings-caption",children:"Beta features · workspace-wide · off by default"},void 0,!1,void 0,this),r(rr,{label:"Agent sessions",beta:!0,checked:xt.value,disabled:!Wr.value||g,description:"Show session chips, tasks, timeline, steering composer, and receipts. Turning off hides these without ending attached agents. Approvals and edit protections remain available. Saved for this workspace.",onClick:()=>void C("agentSessions")},void 0,!1,void 0,this),r(rr,{label:"Knowledge lifecycle",beta:!0,checked:Oe.value,disabled:!Wr.value||g,description:"This turns on context lifecycle, where boards and cards decay over time as their relevance fades. Includes Review, review policies, categories, and due or retired indicators. Turning off hides lifecycle tools without deleting their data or drafts. Saved for this workspace.",onClick:()=>void C("knowledgeLifecycle")},void 0,!1,void 0,this),b&&r("p",{class:"settings-error",role:"alert",children:"Could not save settings. Try again."},void 0,!1,void 0,this),!xt.value&&(pa.value.length>0||Co.value.length>0||os.value.length>0||To.value)&&r(rr,{label:"Agent controls",description:"Review pending approvals, inspect or clear the write scope, or end an existing attachment without enabling the session beta.",onClick:N(()=>eo.value=!0)},void 0,!1,void 0,this),r("div",{class:"toolbar-menu-divider",role:"separator"},void 0,!1,void 0,this),!tt()&&!ut.value&&r(be,{children:[r(rr,{label:"Trace",description:"Show execution traces sent by connected tools. Turning off keeps existing traces. This does not start an agent.",toggle:!0,checked:d,onClick:()=>X("trace-toggle",{enabled:!d})},void 0,!1,void 0,this),(d||p>0)&&r(rr,{label:"Clear trace",description:"Remove recorded execution traces from this board without changing whether trace capture is enabled.",onClick:N(()=>X("trace-clear"))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(rr,{label:"Send feedback",description:"Report a problem or suggestion. Review the feedback before sending.",onClick:N(()=>h(!0))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y==="theme"&&r("div",{class:"toolbar-menu",style:Y,role:"menu","aria-label":"Theme",children:[r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>k("settings"),children:r("span",{children:"‹ Settings"},void 0,!1,void 0,this)},void 0,!1,void 0,this),ch.map((V)=>r("button",{type:"button",role:"menuitemradio","aria-checked":J===V,class:`toolbar-menu-item${J===V?" active":""}`,onClick:()=>B(V),children:[r("span",{class:"theme-swatch",style:{background:Qs[V].swatchBg},children:r("span",{class:"theme-swatch-dot",style:{background:Qs[V].swatchAccent}},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{children:Qs[V].label},void 0,!1,void 0,this),J===V&&r("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},V,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m&&r(kT,{onClose:()=>h(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _T({onOpenPalette:e}){let t=D(null),n=()=>{Eo({type:"markdown",title:"New note",width:520,height:360}).catch(()=>{})},o=async(i)=>{if(!i||i.length===0)return;let s=Zr(),a=Te.value;await ca(Array.from(i),(s.x-a.x)/a.scale,(s.y-a.y)/a.scale)};return r("div",{class:"empty-state","data-testid":"empty-state",children:[r("svg",{class:"empty-state-mark",width:"52",height:"52",viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",children:[r("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7"},void 0,!1,void 0,this),r("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),r("div",{class:"empty-state-title",children:"What would you like to work on?"},void 0,!1,void 0,this),r("div",{class:"empty-state-grid",children:[r("button",{type:"button",class:"empty-state-action",onClick:()=>t.current?.click(),children:[r("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:[r("path",{d:"M8 10 V2 M8 2 L5 5 M8 2 L11 5"},void 0,!1,void 0,this),r("path",{d:"M2 10 V13 H14 V10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"empty-state-action-label",children:["Drop files here",r("span",{class:"empty-state-action-description",children:"Bring in the material you want to work with."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"empty-state-action-hint",children:"or pick"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"empty-state-action",onClick:()=>as("webpage"),children:[r(Hs,{size:16,class:"tone-ok"},void 0,!1,void 0,this),r("span",{class:"empty-state-action-label",children:["Paste a link",r("span",{class:"empty-state-action-description",children:"Add a source, reference, or inspiration."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("kbd",{children:Ft("V")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"empty-state-action",onClick:n,children:[r(ni,{size:16,class:"tone-accent"},void 0,!1,void 0,this),r("span",{class:"empty-state-action-label",children:["Start a note",r("span",{class:"empty-state-action-description",children:"Write down an idea, then ask your agent to help you develop it."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("kbd",{children:"M"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"empty-state-agent",children:[r("div",{class:"empty-state-agent-title",children:"Or start with your agent"},void 0,!1,void 0,this),r("div",{class:"empty-state-sub",children:"Give your agent a task and ask it to work on this board."},void 0,!1,void 0,this),xt.value&&r("button",{type:"button",class:"empty-state-action is-agent",onClick:()=>void vi(),children:[r(js,{size:16,class:"tone-purple"},void 0,!1,void 0,this),r("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),r("button",{type:"button",class:"empty-state-hint",onClick:e,children:["? shortcuts · ",Ft("K")," palette"]},void 0,!0,void 0,this),r("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:(i)=>{let s=i.currentTarget;o(s.files).finally(()=>{s.value=""})}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ir(e){let t=e.target instanceof HTMLElement?e.target:null;return e.key==="Escape"&&!e.defaultPrevented&&!t?.closest('input, textarea, [contenteditable="true"]')&&!document.querySelector('[role="dialog"], [role="menu"], .context-menu, .shortcut-overlay-backdrop')}var CT="From old snapshots";function rp(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 tc(e){return e.split("/").map((t,n,o)=>o.slice(0,n+1).join("/"))}function TT({board:e,folders:t,onClose:n}){let o=D(null),[i,s]=E(e.folder??""),[a,l]=E(""),[c,u]=E(!1),[d,p]=E("");bn(o,!0),q(()=>{let h=(g)=>{if(g.key!=="Escape")return;if(g.preventDefault(),g.stopPropagation(),!c)n()};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[c,n]);let f=a.trim()?[i,a.trim()].filter(Boolean).join("/"):i,m=async()=>{let h;try{if(a.includes("/"))throw Error("Use one folder name; choose its parent above.");h=rp(f)}catch(g){p(g instanceof Error?g.message:String(g));return}if(u(!0),p(""),await vr(e.id,{folder:h}),Ge.value.find((g)=>g.id===e.id)?.folder===h)n();else p("Could not move this board. Try again.");u(!1)};return r("div",{class:"text-prompt-backdrop",onPointerDown:()=>!c&&n(),children:r("div",{ref:o,class:"text-prompt home-folder-dialog",role:"dialog","aria-modal":"true","aria-label":`Move ${e.name}`,onPointerDown:(h)=>h.stopPropagation(),children:[r("div",{class:"text-prompt-title",children:["Move “",e.name,"”"]},void 0,!0,void 0,this),r("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),r("fieldset",{class:"home-folder-options",disabled:c,children:[r("legend",{children:"Destination folder"},void 0,!1,void 0,this),["",...t].map((h)=>r("label",{class:"home-folder-option",style:{paddingLeft:`${8+Math.min(h.split("/").length-1,5)*14}px`},children:[r("input",{type:"radio",name:"folder-destination",value:h,checked:i===h,onChange:()=>{s(h),p("")}},void 0,!1,void 0,this),r("span",{children:h||"Home (no folder)"},void 0,!1,void 0,this)]},h,!0,void 0,this))]},void 0,!0,void 0,this),r("label",{class:"home-folder-new",children:["New folder inside ",i||"Home"," ",r("span",{class:"home-folder-hint",children:"(optional)"},void 0,!1,void 0,this),r("input",{class:"text-prompt-input","aria-label":"New folder name",placeholder:"e.g. Decisions",maxLength:60,value:a,disabled:c,onInput:(h)=>{l(h.currentTarget.value),p("")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-folder-hint",children:["Move to: ",r("strong",{children:f||"Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d&&r("p",{role:"alert",children:d},void 0,!1,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",disabled:c,onClick:n,children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"button",class:"text-prompt-confirm",disabled:c||f===(e.folder??""),onClick:()=>void m(),children:c?"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 IT({board:e,onClose:t}){let n=D(null),o=D(null),[i,s]=E(null),[a,l]=E(new Set),[c,u]=E(`${e.name} copy`),[d,p]=E(!0),[f,m]=E(!0),[h,g]=E(!1),[v,b]=E(""),[x,C]=E(!1);return bn(n,!0,{initial:o}),q(()=>{let k=!0;return Ak(e.id).then((_)=>{if(!k)return;if(!_||!Array.isArray(_.cards))return b("Could not load reusable cards. Try again.");s(_),l(new Set(_.cards.filter((I)=>I.reusable).map((I)=>I.id)))}),()=>{k=!1}},[e.id]),r("div",{class:"text-prompt-backdrop",onMouseDown:t,children:r("div",{ref:n,class:"text-prompt board-copy-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-copy-title",onMouseDown:(k)=>k.stopPropagation(),children:r("form",{onSubmit:async(k)=>{if(k.preventDefault(),!c.trim()||!i)return;C(!0),b("");let _=await Rk({sourceBoardId:e.id,name:c.trim(),...e.folder?{folder:e.folder}:{},nodeIds:[...a],includeReadme:d,includeStructure:f});if(C(!1),!_)return b("Could not create the board. Try a different name.");if(h)await Mn(_.id);t()},children:[r("h2",{id:"board-copy-title",children:["Create from ",e.name]},void 0,!0,void 0,this),r("label",{class:"board-copy-field",children:["Board name",r("input",{ref:o,class:"text-prompt-input",value:c,onInput:(k)=>u(k.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!i&&!v&&r("div",{class:"board-copy-status",role:"status",children:"Loading reusable cards…"},void 0,!1,void 0,this),v&&r("div",{class:"board-copy-error",role:"alert",children:v},void 0,!1,void 0,this),i&&r("fieldset",{class:"board-copy-cards",children:[r("legend",{children:"Cards to copy"},void 0,!1,void 0,this),i.cards.filter((k)=>k.reusable).length===0?r("div",{class:"board-copy-status",children:"No reusable cards on this board."},void 0,!1,void 0,this):i.cards.filter((k)=>k.reusable).map((k)=>r("label",{class:"board-copy-card",children:[r("input",{type:"checkbox",checked:a.has(k.id),onChange:(_)=>{let I=new Set(a);_.currentTarget.checked?I.add(k.id):I.delete(k.id),l(I)}},void 0,!1,void 0,this),r("span",{children:[r("strong",{children:k.title||"Untitled card"},void 0,!1,void 0,this),r("small",{children:k.type},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k.id,!0,void 0,this))]},void 0,!0,void 0,this),r("div",{class:"board-copy-options",children:[r("label",{children:[r("input",{type:"checkbox",checked:f,onChange:(k)=>m(k.currentTarget.checked)},void 0,!1,void 0,this)," ","Preserve groups and connections"]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:d,disabled:!i?.readmeNodeId,onChange:(k)=>p(k.currentTarget.checked)},void 0,!1,void 0,this)," ","Include README"]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:h,onChange:(k)=>g(k.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),r("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),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",onClick:t,children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"submit",disabled:!i||!c.trim()||x,children:x?"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 ip({children:e,initiallyCollapsed:t=!1,reveal:n=0}){let o=D(null),[i,s]=E(280),[a,l]=E(400),[c,u]=E(t),d=D(null);return Me(()=>{if(n)u(!1)},[n]),Me(()=>{let p=o.current.closest(".home-memory"),f=p.querySelector(".home-memory-stage"),m=p.closest(".canvas-region"),h=p.querySelector(".home-memory-toolbar"),g=p.querySelector(".home-memory-legend"),v=()=>{m?.style.setProperty("--home-memory-content-top",`${f.getBoundingClientRect().top-(m?.getBoundingClientRect().top??0)}px`),l(Math.max(120,p.clientHeight-h.offsetHeight-g.offsetHeight-160))},b=new ResizeObserver(v);for(let x of[p,f,h,g])b.observe(x);return v(),()=>{b.disconnect(),m?.style.removeProperty("--home-memory-content-top")}},[]),r("div",{ref:o,class:`home-memory-inspector${c?" is-collapsed":""}`,style:c?void 0:{height:Math.min(i,a)},children:[!c&&r("div",{class:"home-memory-inspector-resize",role:"separator",tabIndex:0,"aria-label":"Resize relation details","aria-orientation":"horizontal","aria-controls":"home-memory-details","aria-valuemin":120,"aria-valuemax":a,"aria-valuenow":Math.min(i,a),onKeyDown:(p)=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(p.key))return;p.preventDefault(),s(p.key==="Home"?120:p.key==="End"?a:Math.max(120,Math.min(a,Math.min(i,a)+(p.key==="ArrowUp"?32:-32))))},onPointerDown:(p)=>{if(p.button!==0)return;p.preventDefault(),d.current={id:p.pointerId,y:p.clientY,height:Math.min(i,a)},p.currentTarget.focus({preventScroll:!0}),p.currentTarget.setPointerCapture(p.pointerId)},onPointerMove:(p)=>{let f=d.current;if(f?.id===p.pointerId)s(Math.max(120,Math.min(a,f.height+f.y-p.clientY)))},onPointerUp:()=>{d.current=null},onPointerCancel:()=>{if(d.current)s(d.current.height);d.current=null}},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button home-memory-inspector-toggle","aria-expanded":!c,"aria-controls":"home-memory-details",onClick:()=>u(!c),children:c?"Expand details":"Collapse details"},void 0,!1,void 0,this),r("div",{id:"home-memory-details",children:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var go={width:220,height:92};function ET(e,t){let n=e.filter((f)=>f.kind==="board"),o=new Map,i=[],s=new Set,a=new Set;for(let f of n){let m=(f.folder??"").split("/");m.forEach((h,g)=>{a.add(m.slice(0,g+1).join("/"))})}let l=(f,m)=>(f.folder??"")===m||!!m&&!!f.folder?.startsWith(`${m}/`),c=(f,m,h,g)=>{let v=n.filter((B)=>l(B,f)),b=t.has(f),x={path:f,x:m,y:h,width:280,height:72,count:v.length,depth:g,collapsed:b};if(i.push(x),b){for(let B of v)s.add(B.key);return x}let C=v.filter((B)=>(B.folder??"")===f).sort((B,J)=>B.title.localeCompare(J.title)),y=Math.min(3,Math.max(1,Math.ceil(Math.sqrt(C.length))));C.forEach((B,J)=>{let X=B.position??{x:m+24+J%y*(go.width+28),y:h+52+Math.floor(J/y)*(go.height+28)};o.set(B.key,{x:X.x+go.width/2,y:X.y+go.height/2})});let k=h+52+Math.ceil(C.length/y)*(go.height+28),_=C.length?y*(go.width+28)+20:280,I=[...a].filter((B)=>B&&B.slice(0,B.lastIndexOf("/"))===f&&B.includes("/")).sort(),w=20,P=0;for(let B of I){if(w>650)w=20,k+=P+24,P=0;let J=c(B,m+w,k,g+1);w+=J.width+24,P=Math.max(P,J.height),_=Math.max(_,w)}k+=P+(I.length?20:0),x.width=_,x.height=Math.max(100,k-h+4);let L=v.flatMap((B)=>{let J=o.get(B.key);return J?[J]:[]}),N=Math.max(m+x.width,...L.map((B)=>B.x+go.width/2+20)),Y=Math.max(h+x.height,...L.map((B)=>B.y+go.height/2+20));return x.x=Math.min(m,...L.map((B)=>B.x-go.width/2-20)),x.y=Math.min(h,...L.map((B)=>B.y-go.height/2-48)),x.width=N-x.x,x.height=Y-x.y,x},u=32,d=32,p=0;for(let f of[...a].filter((m)=>!m.includes("/")).sort()){if(u>1100)u=32,d+=p+36,p=0;let m=c(f,u,d,0);u+=m.width+36,p=Math.max(p,m.height)}return{positions:o,regions:i,hidden:s}}function sp(e){let t=Ge.value,n=bo.value,[o,i]=E(null),[s,a]=E(!0),[l,c]=E(!1),u=D(()=>{});return q(()=>{let d=!1,p=!1,f=!1,m,h=()=>{if(f=!0,!p&&m===void 0)m=window.setTimeout(g,120)},g=async()=>{m=void 0,f=!1,p=!0,a(!0);let v=Sn,b=bo.peek(),x=Ge.peek(),C=await de("memoryGraph",`/api/canvas/memory-graph?projection=${e}`,null);if(d)return;if(p=!1,v!==Sn||b!==bo.peek()||x!==Ge.peek()){h();return}if(C&&Array.isArray(C.nodes)&&Array.isArray(C.edges))i(C),c(!1);else c(!0);if(a(!1),f)h()};return u.current=h,h(),()=>{d=!0,window.clearTimeout(m)}},[e]),q(()=>u.current(),[n,t]),{graph:o,loading:s,error:l,retry:()=>u.current()}}var AT={portal:"Portals",wiki:"Wiki links",card:"Card relations",previous:"Previous boards"};function RT(){let e=Ge.value,t=bo.value,{graph:n,loading:o,error:i,retry:s}=sp("boards"),[a,l]=E(""),[c,u]=E(!0),[d,p]=E(!1),[f,m]=E(!0),[h,g]=E(new Set),[v,b]=E(new Set),[x,C]=E(new Set),[y,k]=E(null),[_,I]=E(null),[w,P]=E(null),[L,N]=E({x:0,y:0}),[Y,B]=E(1),[J,X]=E({}),[V,ee]=E(!1),he=D(null),A=D(!0),te=D(!1),M=D(null);Me(()=>{ut.value=!0},[]),Me(()=>{if(!y)return;let R=(ne)=>{if(ir(ne))ne.preventDefault(),k(null)};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[y]),q(()=>{if(!y)return;let R=!1;P(null);let ne=Sn,Ce=bo.peek(),Ie=new URLSearchParams({focus:y,depth:"2"});return de("memoryGraph",`/api/canvas/memory-graph?${Ie}`,null).then((fe)=>{if(!R&&ne===Sn&&Ce===bo.peek())P({key:y,graph:fe&&Array.isArray(fe.nodes)&&Array.isArray(fe.edges)?fe:null})}),()=>{R=!0}},[y,n,t]);let O=Ke(()=>(n?.nodes??[]).filter((R)=>R.kind==="board").map((R)=>{let ne=e.find((Ce)=>Ce.id===R.boardId);return ne?{...R,title:ne.name,folder:ne.folder,inContext:!!ne.pin,nodeCount:ne.nodeCount,position:ne.mapPosition??void 0}:R}),[n,e]),Pe=Ke(()=>ET(O,x),[O,x]),Fe=new Map;for(let R of O){let ne=R.folder?.split("/")[0]??"";Fe.set(ne,(Fe.get(ne)??0)+1)}let De=O.filter((R)=>c&&(!d||R.inContext)&&(f||!!R.folder)&&!h.has(R.folder?.split("/")[0]??"")&&!Pe.hidden.has(R.key)&&`${R.title} ${R.summary} ${R.folder??""}`.toLocaleLowerCase().includes(a.trim().toLocaleLowerCase())),Ae=new Set(De.map((R)=>R.key)),ve=(R)=>J[R]??Pe.positions.get(R),z=O.find((R)=>R.key===y),re=O.find((R)=>R.key===(_??y)),Ne=new Map;for(let R of n?.edges??[]){if(R.kind==="member"||v.has(R.kind))continue;let ne=Mt({boardId:R.source.boardId}),Ce=Mt({boardId:R.target.boardId});if(!Ae.has(ne)||!R.missing&&(!Ae.has(Ce)||ne===Ce))continue;let Ie=JSON.stringify([ne,Ce,R.kind,R.relationKind,R.missing]),fe=Ne.get(Ie);if(fe)fe.edges.push(R);else Ne.set(Ie,{from:ne,to:Ce,edges:[R]})}let ke=new Set(re?[re.key]:[]);for(let{from:R,to:ne}of Ne.values())if(re&&(R===re.key||ne===re.key))ke.add(R),ke.add(ne);let ae=(R)=>new Set((n?.edges??[]).filter((ne)=>ne.kind!=="member"&&(ne.source.boardId===R.boardId||ne.target.boardId===R.boardId)).map((ne)=>ne.source.boardId===R.boardId?ne.target.boardId:ne.source.boardId).filter((ne)=>ne!==R.boardId)).size,Se=()=>{let R=he.current;if(!R?.clientWidth||!R.clientHeight)return;let ne=De.flatMap((Ye)=>{let Lt=ve(Ye.key);return Lt?[{x:Lt.x-110,y:Lt.y-46},{x:Lt.x+110,y:Lt.y+46}]:[]});for(let Ye of Pe.regions){if(h.has(Ye.path.split("/")[0]??"")||!f&&!Ye.path)continue;ne.push({x:Ye.x,y:Ye.y},{x:Ye.x+Ye.width,y:Ye.y+Ye.height})}if(!ne.length)return;let Ce=Math.min(...ne.map((Ye)=>Ye.x)),Ie=Math.min(...ne.map((Ye)=>Ye.y)),fe=Math.max(...ne.map((Ye)=>Ye.x))-Ce,it=Math.max(...ne.map((Ye)=>Ye.y))-Ie,Ht=Math.min(1.25,Math.max(0.08,Math.min((R.clientWidth-64)/Math.max(1,fe),(R.clientHeight-100)/Math.max(1,it))));B(Ht),N({x:(R.clientWidth-fe*Ht)/2-Ce*Ht,y:(R.clientHeight-it*Ht)/2-Ie*Ht-12})};q(()=>{A.current=!0},[x]),q(()=>{if(A.current&&n&&(De.length||Pe.regions.length)&&!M.current)A.current=!1,Se()},[n,x]);let pe=(R,ne)=>{let Ce=he.current;if(!Ce)return;let Ie=ne??{x:Ce.clientWidth/2,y:Ce.clientHeight/2},fe=Math.min(3,Math.max(0.08,R));N({x:Ie.x-(Ie.x-L.x)*fe/Y,y:Ie.y-(Ie.y-L.y)*fe/Y}),B(fe)},Ue=(R,ne=!1)=>{k(R.key);let Ce=ve(R.key),Ie=he.current;if(ne&&Ce&&Ie)N({x:Ie.clientWidth/2-Ce.x*Y,y:Ie.clientHeight/2-Ce.y*Y})},xe=(R)=>{let ne=M.current;if(M.current=null,!ne)return;if(te.current=ne.moved,!ne.key)return;let Ce=ne.key,Ie=()=>X((fe)=>{let it={...fe};return delete it[Ce],it});if(ne.boardId&&ne.moved&&!R){let fe=ne.current??ne.origin;vr(ne.boardId,{mapPosition:{x:fe.x-go.width/2,y:fe.y-go.height/2}}).finally(Ie)}else Ie()},qe=w?.key===y?w.graph:null,W=(qe?.edges??[]).filter((R)=>z&&R.kind!=="member"&&(R.source.boardId===z.boardId||R.target.boardId===z.boardId)),ye=e.find((R)=>R.id===z?.boardId),He=(R,ne,Ce,Ie)=>r("label",{class:"home-memory-check",children:[r("input",{type:"checkbox","aria-label":R,checked:Ce,onChange:Ie},void 0,!1,void 0,this),r("span",{children:R},void 0,!1,void 0,this),r("small",{children:ne},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("main",{class:`home-memory is-map${V?" sidebar-open":""}`,"aria-label":"Library Map",children:[r("div",{class:"home-memory-toolbar",children:[r("span",{children:[O.length," boards · ",e.reduce((R,ne)=>R+ne.nodeCount,0)," cards ·"," ",n?.edges.filter((R)=>R.kind!=="member").length??0," links"]},void 0,!0,void 0,this),r("span",{class:`home-memory-live${i?" is-error":""}`,role:"status",children:i?"Update failed":o?"Updating…":"Live"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button home-memory-sidebar-toggle","aria-expanded":V,onClick:()=>ee(!V),children:"Filters"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-body",children:[r("div",{class:"home-memory-stage",ref:he,"aria-label":"Pan the memory view",onWheel:(R)=>{R.preventDefault();let ne=R.currentTarget.getBoundingClientRect();pe(Y*Math.exp(-R.deltaY*0.0015),{x:R.clientX-ne.left,y:R.clientY-ne.top})},onPointerDown:(R)=>{if(R.button!==0||R.target.closest("button"))return;te.current=!1,M.current={id:R.pointerId,start:{x:R.clientX,y:R.clientY},origin:L,moved:!1},R.currentTarget.setPointerCapture(R.pointerId)},onPointerMove:(R)=>{let ne=M.current;if(!ne||ne.id!==R.pointerId)return;let Ce=R.clientX-ne.start.x,Ie=R.clientY-ne.start.y;if(Math.abs(Ce)+Math.abs(Ie)>4)ne.moved=!0;if(!ne.moved)return;let fe={x:ne.origin.x+Ce/(ne.key?Y:1),y:ne.origin.y+Ie/(ne.key?Y:1)};if(ne.current=fe,ne.key)X((it)=>({...it,[ne.key]:fe}));else N(fe)},onPointerUp:()=>xe(!1),onPointerCancel:()=>xe(!0),children:[r("div",{class:"home-memory-world",style:{transform:`translate(${L.x}px, ${L.y}px) scale(${Y})`,"--memory-zoom":Y},children:[Pe.regions.filter((R)=>!h.has(R.path.split("/")[0]??"")&&(f||R.path)).map((R)=>r("div",{class:`home-memory-region${R.depth?" is-nested":""}`,style:{left:R.x,top:R.y,width:R.width,height:R.height},children:r("button",{type:"button","aria-expanded":!R.collapsed,onClick:()=>C((ne)=>{let Ce=new Set(ne);if(Ce.has(R.path))Ce.delete(R.path);else Ce.add(R.path);return Ce}),children:[R.collapsed?"▸":"▾"," ",R.path.split("/").at(-1)||"Unfiled"," ",r("small",{children:[R.count," boards"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},R.path,!1,void 0,this)),r("svg",{class:"home-memory-links","aria-hidden":"true",children:[...Ne].map(([R,{from:ne,to:Ce,edges:Ie}])=>{let fe=Ie[0],it=ve(ne),Ht=ve(Ce);if(!it)return null;let Ye=Ht??{x:it.x+100,y:it.y-70},Lt=it.y+(Ye.y>it.y?46:-46),F=Ht?Ye.y+(Ye.y>it.y?-46:46):Ye.y,Ee=re&&(fe.source.boardId===re.boardId||fe.target.boardId===re.boardId),S=mo({kind:fe.relationKind,type:fe.type},e.find((ue)=>ue.id===fe.source.boardId)?.relationVocabulary),K=fe.missing?"var(--c-warn)":fe.kind==="card"?`var(--c-rel-${S.ink})`:void 0;return r("g",{"data-from":ne,"data-to":Ce,"data-count":Ie.length,style:K?{stroke:K}:void 0,class:`memory-edge edge-${fe.kind}${fe.missing?" is-missing":""}${Ee?" is-emphasized":re?" is-dimmed":""}`,children:[r("path",{d:`M ${it.x} ${Lt} C ${it.x} ${(Lt+F)/2}, ${Ye.x} ${(Lt+F)/2}, ${Ye.x} ${F}`},void 0,!1,void 0,this),Ie.length>1&&r("text",{x:(it.x+Ye.x)/2,y:(it.y+Ye.y)/2-6,children:[Ie.length," links"]},void 0,!0,void 0,this),fe.missing&&r("text",{x:Ye.x,y:Ye.y-5,children:["⚠ Missing ",fe.kind," link"]},void 0,!0,void 0,this)]},R,!0,void 0,this)})},void 0,!1,void 0,this),De.map((R,ne)=>{let Ce=ve(R.key);if(!Ce)return null;let Ie=e.find((fe)=>fe.id===R.boardId);return r("article",{"data-key":R.key,class:`home-memory-node is-board${R.inContext?" in-context":""}${y===R.key?" is-selected":""}${ke.has(R.key)?" is-emphasized":re?" is-dimmed":""}`,style:{left:Ce.x,top:Ce.y},onPointerEnter:()=>{if(!M.current)I(R.key)},onPointerLeave:()=>I(null),children:[r("button",{type:"button",class:"home-memory-select","aria-label":`board: ${R.title}`,"aria-pressed":y===R.key,onFocus:(fe)=>{if(!M.current&&fe.currentTarget.matches(":focus-visible"))Ue(R,!0)},onClick:()=>{if(!te.current)Ue(R);te.current=!1},onDblClick:()=>void zt(R),onPointerDown:(fe)=>{if(fe.button!==0)return;fe.stopPropagation(),te.current=!1,M.current={id:fe.pointerId,start:{x:fe.clientX,y:fe.clientY},origin:Ce,key:R.key,boardId:R.boardId,moved:!1},fe.currentTarget.setPointerCapture(fe.pointerId)},onKeyDown:(fe)=>{if(fe.key==="Enter")fe.preventDefault(),zt(R);if(fe.key.startsWith("Arrow")){fe.preventDefault();let it=(ne+(fe.key==="ArrowLeft"||fe.key==="ArrowUp"?-1:1)+De.length)%De.length,Ht=De[it];if(Ht)Ue(Ht,!0),he.current?.querySelectorAll(".home-memory-select")[it]?.focus({preventScroll:!0})}},children:[r("strong",{children:R.title},void 0,!1,void 0,this),r("span",{children:[R.nodeCount??0," cards · ",ae(R)," connected boards"]},void 0,!0,void 0,this),r("span",{class:"home-memory-summary",children:R.summary||"No summary yet"},void 0,!1,void 0,this),R.inContext&&r("span",{class:"home-memory-context",children:"⌖ In context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ie&&r(ho,{board:Ie},void 0,!1,void 0,this)]},R.key,!0,void 0,this)})]},void 0,!0,void 0,this),r("div",{class:"home-memory-zoom",children:[r("button",{type:"button",class:"home-button","aria-label":"Zoom out",onClick:()=>pe(Y/1.2),children:"−"},void 0,!1,void 0,this),r("span",{children:[Math.round(Y*100),"%"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button","aria-label":"Zoom in",onClick:()=>pe(Y*1.2),children:"+"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:Se,children:"Fit view"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(!n||!De.length||i)&&r("div",{class:"home-memory-status",role:"status",children:i?r(be,{children:["Memory update failed."," ",r("button",{type:"button",class:"home-button",onClick:s,children:"Retry"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):!n?"Loading memory…":Pe.hidden.size?"Folders collapsed. Expand a folder to see its boards.":"No matching nodes."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("aside",{class:"home-memory-sidebar","aria-label":"Map settings",children:[r("section",{children:[r("h2",{children:"Filters"},void 0,!1,void 0,this),r("label",{class:"home-memory-search",children:[r("span",{children:"Find boards and cards"},void 0,!1,void 0,this),r("input",{type:"search",value:a,placeholder:"Search boards and cards…",onInput:(R)=>l(R.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),He("Boards",O.length,c,()=>u(!c)),He("Only in context",O.filter((R)=>R.inContext).length,d,()=>p(!d)),He("Include unfiled",O.filter((R)=>!R.folder).length,f,()=>m(!f))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Groups · by folder"},void 0,!1,void 0,this),[...Fe].sort(([R],[ne])=>R.localeCompare(ne)).map(([R,ne])=>r("div",{children:He(R||"Unfiled",ne,!h.has(R),()=>g((Ce)=>{let Ie=new Set(Ce);if(Ie.has(R))Ie.delete(R);else Ie.add(R);return Ie}))},R,!1,void 0,this))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Links"},void 0,!1,void 0,this),Object.keys(AT).map((R)=>r("div",{class:`memory-legend-${R}`,children:He(AT[R],n?.edges.filter((ne)=>ne.kind===R).length??0,!v.has(R),()=>b((ne)=>{let Ce=new Set(ne);if(Ce.has(R))Ce.delete(R);else Ce.add(R);return Ce}))},R,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-legend","aria-label":"Legend",children:[r("span",{children:"▣ Board"},void 0,!1,void 0,this),r("span",{class:"memory-context-legend",children:"⌖ In context"},void 0,!1,void 0,this),r("span",{class:"memory-legend-portal",children:"━ Portal"},void 0,!1,void 0,this),r("span",{class:"memory-legend-wiki",children:"┄ Wiki"},void 0,!1,void 0,this),r("span",{class:"memory-legend-card",children:"━ Relation"},void 0,!1,void 0,this),r("span",{children:"Drag boards to save positions · drag background to pan · scroll to zoom"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(ip,{children:z?r("section",{class:"home-memory-details",role:"complementary","aria-label":"Selection details",children:[r("button",{type:"button",class:"home-memory-clear","aria-label":"Close details",onClick:()=>k(null),children:"×"},void 0,!1,void 0,this),r("div",{class:"home-memory-detail-header",children:[r("div",{class:"home-memory-selection-title",children:[r("h3",{children:[z.title," · ",W.length," connections"]},void 0,!0,void 0,this),r("p",{children:[z.folder||"Unfiled"," · board"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-actions",children:[r("button",{type:"button",class:"home-button is-primary",onClick:()=>void zt(z),children:"Open board"},void 0,!1,void 0,this),ye&&r(ho,{board:ye},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>void vr(z.boardId,{mapPosition:null}),children:"Reset position"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-detail-body",children:[r("p",{children:[z.nodeCount??0," cards · ",ae(z)," connected boards"]},void 0,!0,void 0,this),r("p",{children:z.summary||"No summary yet."},void 0,!1,void 0,this),r("p",{class:z.inContext?"memory-context-legend":"",children:z.inContext?"⌖ In context":"Not in context"},void 0,!1,void 0,this),r("details",{class:"home-memory-connections",open:!0,children:[r("summary",{children:"Connections"},void 0,!1,void 0,this),!qe&&r("p",{role:"status",children:w?.key===y?"Connections could not be loaded.":"Loading connections…"},void 0,!1,void 0,this),r("ul",{children:[W.map((R)=>{let ne=R.source.boardId===z.boardId,Ce=ne?R.target:R.source,Ie=qe?.nodes.find((fe)=>fe.key===Mt(Ce));return r("li",{children:[r("span",{children:[ne?"→":"←"," ",R.kind==="card"?ma({...R,kind:R.relationKind}):`${R.kind}${R.label?` · ${R.label}`:""}`]},void 0,!0,void 0,this),R.missing?r("span",{class:"home-memory-missing",children:["⚠ Missing target: ",Ce.boardId,Ce.cardId?` / ${Ce.cardId}`:""]},void 0,!0,void 0,this):r("button",{type:"button",class:"home-button",onClick:()=>void zt(Ce),children:Ie?.title??Ce.boardId},void 0,!1,void 0,this)]},R.id,!0,void 0,this)}),(qe?.unresolvedLinks??[]).filter((R)=>R.source.boardId===z.boardId).map((R)=>r("li",{class:"home-memory-missing",children:["⚠ Unresolved wiki: [[",R.ref,"]]"]},`${Mt(R.source)}:${R.ref}`,!0,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):r("div",{class:"home-memory-empty-details",children:[r("h3",{children:"Relations"},void 0,!1,void 0,this),r("p",{class:"home-memory-help",children:"Overview groups links between boards. Select a board to inspect connections. Double-click to open."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Je={width:220,height:96,gap:64},nc=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y),SL=(e,t)=>e.x>t.left&&e.x<t.right&&e.y>t.top&&e.y<t.bottom;function _L(e,t,n){let o=0,i=1;for(let[s,a,l,c]of[[e.x,t.x-e.x,n.left,n.right],[e.y,t.y-e.y,n.top,n.bottom]])if(!a){if(s<=l||s>=c)return!1}else{let u=(l-s)/a,d=(c-s)/a;o=Math.max(o,Math.min(u,d)),i=Math.min(i,Math.max(u,d))}return o<i&&i>0&&o<1}function PT(e,t){let o=[...e].map(([f,m])=>({key:f,left:m.x-Je.width/2-8,right:m.x+Je.width/2+8,top:m.y-Je.height/2-8,bottom:m.y+Je.height/2+8})),i=(f,m)=>!o.some((h)=>_L(f,m,h)),s=o.flatMap((f)=>[{x:f.left,y:f.top},{x:f.right,y:f.top},{x:f.right,y:f.bottom},{x:f.left,y:f.bottom}]).filter((f)=>!o.some((m)=>SL(f,m))),a=new Map,l=(f,m)=>[{x:f.x-Je.width/2,y:f.y+m*Je.height},{x:f.x+Je.width/2,y:f.y+m*Je.height},{x:f.x+m*Je.width,y:f.y-Je.height/2},{x:f.x+m*Je.width,y:f.y+Je.height/2}].map((h,g)=>({port:h,stub:{x:h.x+(g===0?-8:g===1?8:0),y:h.y+(g===2?-8:g===3?8:0)}})),c=new Map,u=[],d=new Map,p=new Map;for(let f of t){let m=JSON.stringify([f.from,f.to].sort());p.set(m,(p.get(m)??0)+1)}for(let f of t){let m=e.get(f.from),h=e.get(f.to),g=JSON.stringify([f.from,f.to].sort()),v=d.get(g)??0;d.set(g,v+1);let b=((v+1)/(p.get(g)+1)-0.5)*0.8,x=l(m,b),C=l(h,b),y,k=1/0;for(let P of x)for(let L of C){let N=nc(P.stub,L.stub);if(N&&N<k&&i(P.stub,L.stub))k=N,y=[P.port,P.stub,L.stub,L.port]}if(!y){let P=s.map(()=>1/0),L=s.map(()=>-1),N=s.map(()=>0),Y=new Set;for(let X=0;X<s.length;X++)for(let V=0;V<x.length;V++){let ee=nc(x[V].stub,s[X]);if(ee<P[X]&&i(x[V].stub,s[X]))P[X]=ee,N[X]=V}let B=-1,J=0;while(Y.size<s.length){let X=-1;for(let ee=0;ee<s.length;ee++)if(!Y.has(ee)&&(X<0||P[ee]<P[X]))X=ee;if(X<0||P[X]>=k||!Number.isFinite(P[X]))break;Y.add(X);for(let ee=0;ee<C.length;ee++){let he=P[X]+nc(s[X],C[ee].stub);if(he<k&&i(s[X],C[ee].stub))k=he,B=X,J=ee}let V=a.get(X);if(!V)V=s.flatMap((ee,he)=>he!==X&&i(s[X],ee)?[{index:he,length:nc(s[X],ee)}]:[]),a.set(X,V);for(let ee of V)if(P[X]+ee.length<P[ee.index])P[ee.index]=P[X]+ee.length,L[ee.index]=X,N[ee.index]=N[X]}if(B>=0){let X=[];for(let he=B;he>=0;he=L[he])X.unshift(s[he]);let V=x[N[B]],ee=C[J];y=[V.port,V.stub,...X,ee.stub,ee.port]}}if(!y)continue;let _=Math.max(24,f.label.length*3.6+6),I=y.slice(1).map((P,L)=>({first:y[L],point:P,length:nc(y[L],P)})).filter((P)=>P.length>0).sort((P,L)=>L.length-P.length),w;for(let P=16;f.label&&!w;P+=20)w=I.flatMap(({first:N,point:Y,length:B})=>[0.5,0.25,0.75].flatMap((J)=>[-P,P].map((X)=>{let V=N.x+(Y.x-N.x)*J-(Y.y-N.y)*X/B,ee=N.y+(Y.y-N.y)*J+(Y.x-N.x)*X/B;return{x:V,y:ee,left:V-_,right:V+_,top:ee-16,bottom:ee+8}}))).find((N)=>![...o,...u].some((Y)=>N.left<Y.right&&N.right>Y.left&&N.top<Y.bottom&&N.bottom>Y.top));if(w)u.push(w);c.set(f.id,{points:y,path:y.map((P,L)=>`${L?"L":"M"} ${P.x} ${P.y}`).join(" "),label:w})}return c}var ls=(e)=>e.kind==="overview"?"overview":JSON.stringify(e),CL=(e,t)=>JSON.stringify([e,t].sort());function NT(e){let t=new Map,n=new Map,o=[],i=e.filter((s)=>s.kind!=="member");for(let s of i){if(s.missing){o.push(s);continue}if(s.source.boardId===s.target.boardId){n.set(s.source.boardId,(n.get(s.source.boardId)??0)+1);continue}let a=CL(s.source.boardId,s.target.boardId),l=t.get(a);if(l)l.edges.push(s);else t.set(a,{boardId:s.source.boardId,peerId:s.target.boardId,edges:[s]})}return{evidence:i,pairs:t,internal:n,missing:o}}function ap(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return(t>>>0)/4294967296}function MT(e,t){let n=new Map(e.map((i)=>[i,new Map])),o=t.filter((i)=>i.from!==i.to&&n.has(i.from)&&n.has(i.to)).map((i)=>({ends:[i.from,i.to].sort(),weight:Math.max(0.1,i.weight??1)})).sort((i,s)=>i.ends[0].localeCompare(s.ends[0])||i.ends[1].localeCompare(s.ends[1])||i.weight-s.weight);for(let{ends:[i,s],weight:a}of o)n.get(i).set(s,(n.get(i).get(s)??0)+a),n.get(s).set(i,(n.get(s).get(i)??0)+a);return n}function zT(e,t,n,o){let i=t.get(e),s=[...o.values()].reduce((c,u)=>c+Math.sqrt(u),0),a=0,l=0;for(let c of n){if(c===e)continue;let u=t.get(c),d=i.x-u.x||(ap(e)-0.5)*0.01,p=i.y-u.y||(ap(`${e}:y`)-0.5)*0.01,f=Math.max(1,Math.hypot(d,p)),m=14000/(f*f),h=o.get(c)??0,g=h?(f-290)*0.006*Math.sqrt(h)/s:0;a+=d/f*(m-g),l+=p/f*(m-g);let v=Je.width+Je.gap,b=(Je.height+Je.gap)*Je.width/Je.height;if(Math.abs(d)<v&&Math.abs(p)<b)if(v-Math.abs(d)<b-Math.abs(p))a+=Math.sign(d)*(v-Math.abs(d))*0.2;else l+=Math.sign(p)*(b-Math.abs(p))*0.2}return{x:a,y:l}}function $T(e,t,n,o){let i=[...e.keys()].sort(),s=MT(i,t),a=Je.width/Je.height,l=new Map([...e].map(([u,d])=>[u,{x:d.x,y:d.y*a}])),c=0;for(let u of i){if(u===n)continue;let d=l.get(u),p=zT(u,l,i,s.get(u)),f=Math.min(1,24/Math.max(1,Math.hypot(p.x,p.y)))*o,m=p.x*f,h=p.y*f/a;e.set(u,{x:d.x+m,y:d.y/a+h}),c=Math.max(c,Math.hypot(m,h))}for(let[u,d]of i.entries())for(let p of i.slice(u+1)){let f=e.get(d),m=e.get(p),h=f.x-m.x,g=f.y-m.y,v=Je.width+Je.gap-Math.abs(h),b=Je.height+Je.gap-Math.abs(g);if(v<=0||b<=0)continue;let x=v<b?{x:(Math.sign(h)||-1)*v,y:0}:{x:0,y:(Math.sign(g)||-1)*b},C=p===n?1:0.5,y=d===n?1:0.5;if(d!==n)e.set(d,{x:f.x+x.x*C,y:f.y+x.y*C});if(p!==n)e.set(p,{x:m.x-x.x*y,y:m.y-x.y*y});c=Math.max(c,Math.hypot(x.x,x.y))}return c}function LT(e,t,n){let o=[...new Set(e.map((y)=>y.key))].sort();if(o.every((y)=>n.has(y)))return new Map(o.map((y)=>[y,n.get(y)]));let i=MT(o,t),s=[],a=new Set;for(let y of o){if(a.has(y))continue;let k=[y];a.add(y);for(let _ of k)for(let I of i.get(_).keys()){if(a.has(I))continue;a.add(I),k.push(I)}s.push(k.sort())}let l=new Map,c=Je.width/Je.height;for(let y of o){let k=n.get(y);if(k)l.set(y,{x:k.x,y:k.y*c})}for(let y of s){if(!y.some((k)=>l.has(k)))l.set(y[0],{x:0,y:0});while(y.some((k)=>!l.has(k)))for(let k of y){if(l.has(k))continue;let _=[...i.get(k).keys()].filter((I)=>l.has(I));if(!_.length)continue;l.set(k,{x:_.reduce((I,w)=>I+l.get(w).x,0)/_.length+(ap(k)-0.5)*240,y:_.reduce((I,w)=>I+l.get(w).y,0)/_.length+(ap(`${k}:y`)-0.5)*240})}for(let k=0;k<180;k++){let _=new Map;for(let I of y){if(n.has(I))continue;let w=l.get(I),{x:P,y:L}=zT(I,l,y,i.get(I)),N=Math.min(1,24/Math.max(1,Math.hypot(P,L)))*(1-k/200);_.set(I,{x:w.x+P*N,y:w.y+L*N})}for(let[I,w]of _)l.set(I,w)}}for(let[y,k]of l)l.set(y,n.get(y)??{x:k.x,y:k.y/c});let u=o.filter((y)=>n.has(y)).map((y)=>l.get(y)),d=Je.width+Je.gap,p=Je.height+Je.gap,f=(y,k)=>Math.abs(y.x-k.x)<d&&Math.abs(y.y-k.y)<p,m=0,h=0,g=0,v=0,b=Math.sqrt(o.length)*380,x=(y)=>y.some((k)=>n.has(k));s.sort((y,k)=>Number(x(k))-Number(x(y)));let C=!1;for(let y of s){let k=x(y);if(!k&&!C)m=u.length?Math.max(...u.map((w)=>w.x))+340:0,h=m,C=!0;let _=k?u:[],I=[];for(let w of y){if(n.has(w))continue;let P=l.get(w),L=P;if(_.some((N)=>f(L,N)))L=_.flatMap((Y)=>[{x:Y.x-d,y:P.y},{x:Y.x+d,y:P.y},{x:P.x,y:Y.y-p},{x:P.x,y:Y.y+p}]).filter((Y)=>!_.some((B)=>f(Y,B))).sort((Y,B)=>Math.hypot(Y.x-P.x,Y.y-P.y)-Math.hypot(B.x-P.x,B.y-P.y))[0];l.set(w,L),_.push(L),I.push(L)}if(!k&&I.length){let w=Math.min(...I.map((L)=>L.x)),P=Math.min(...I.map((L)=>L.y));for(let L of I)L.x+=h-w,L.y+=g-P;if(u.push(...I),h=Math.max(...I.map((L)=>L.x))+340,v=Math.max(v,Math.max(...I.map((L)=>L.y))-g+200),h-m>b)h=m,g+=v,v=0}}for(let[y,k]of l)if(!n.has(y))n.set(y,k);return l}var OT={portal:"Portals",wiki:"Wiki links",card:"Card relations",previous:"Previous boards"},Tg=(e)=>({scene:e,camera:null,query:"",context:!1,folders:new Set,hiddenLinks:new Set,inspection:null,limit:80});function DT(){let e=Ge.value,{graph:t,loading:n,error:o,retry:i}=sp("full"),[s,a]=E([Tg({kind:"overview"})]),l=s.at(-1),c=l.scene,u=ls(c),[d,p]=E(!1),[f,m]=E(0),[h,g]=E(0),[v,b]=E(null),[x,C]=E(""),[y,k]=E({width:0,height:0}),_=D(new Map),I=D(null),w=D(null),P=D(null),L=D(null),N=()=>{if(P.current!==null)cancelAnimationFrame(P.current);P.current=null,L.current=null},Y=D(!1),B=(S)=>a((K)=>[...K.slice(0,-1),{...K.at(-1),...S}]),J=()=>{a((S)=>S.length>1?S.slice(0,-1):S),p(!1),b(null),C("")},X=(S)=>{if(ls(S)===u){m((K)=>K+1);return}a((K)=>[...K,Tg(S)]),p(!1),b(null),C("")},V=(S)=>{let K=s.map((ue)=>ls(ue.scene)).lastIndexOf(ls(S));if(K>=0)a((ue)=>ue.slice(0,K+1));else X(S);p(!1)};Me(()=>{ut.value=!0},[]),Me(()=>{let S=I.current,K=()=>k({width:S.clientWidth,height:S.clientHeight}),ue=new ResizeObserver(K);return ue.observe(S),K(),()=>ue.disconnect()},[]),Me(()=>{let S=(K)=>{if(!ir(K))return;if(l.inspection||s.length>1)if(K.preventDefault(),l.inspection)B({inspection:null});else J()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[l.inspection,s.length]);let ee=Ke(()=>(t?.nodes??[]).map((S)=>{let K=e.find((ue)=>ue.id===S.boardId);return K?{...S,folder:K.folder,...S.kind==="board"?{title:K.name,nodeCount:K.nodeCount,inContext:!!K.pin}:{}}:S}),[t,e]),he=Ke(()=>new Map(ee.map((S)=>[S.key,S])),[ee]),A=Ke(()=>NT(t?.edges??[]),[t]),te=c.kind==="overview"?null:Mt(c),M=te?he.get(te):void 0,O=(S)=>e.find((K)=>K.id===S)?.name??S,Pe=(S)=>c.kind!=="overview"&&S.boardId===c.boardId,Fe=c.kind==="overview"?A.evidence:A.evidence.filter((S)=>c.kind==="board"?S.source.boardId===c.boardId||S.target.boardId===c.boardId:S.from===te||S.to===te),De=Ke(()=>{if(c.kind==="overview")return{nodes:ee.filter((ue)=>ue.kind==="board"),links:[...A.pairs].map(([ue,$e])=>({id:ue,from:Mt({boardId:$e.boardId}),to:Mt({boardId:$e.peerId}),edges:$e.edges,bundle:!0}))};let S=new Set;if(c.kind==="board"){for(let ue of ee)if(Pe(ue)&&ue.kind==="card")S.add(ue.key)}else if(te&&he.has(te))S.add(te);let K=new Map;for(let ue of Fe){if(ue.missing||!he.has(ue.from)||!he.has(ue.to))continue;let $e=c.kind==="board"&&ue.source.boardId!==c.boardId?Mt({boardId:ue.source.boardId}):ue.from,je=c.kind==="board"&&ue.target.boardId!==c.boardId?Mt({boardId:ue.target.boardId}):ue.to;S.add($e),S.add(je);let le=c.kind==="card"?ue.id:JSON.stringify([$e,je].sort()),we=K.get(le);if(we)we.edges.push(ue),we.bundle=!0;else K.set(le,{id:le,from:$e,to:je,edges:[ue],bundle:$e!==ue.from||je!==ue.to})}return{nodes:ee.filter((ue)=>S.has(ue.key)),links:[...K.values()]}},[ee,t,u]),Ae=new Map;for(let S of De.links)for(let K of[S.from,S.to])Ae.set(K,(Ae.get(K)??0)+S.edges.length);let ve=De.nodes.filter((S)=>Ae.has(S.key)||S.key===te),z=De.nodes.filter((S)=>!Ae.has(S.key)&&S.key!==te),re=(S)=>S.key===te||(!l.context||S.inContext)&&!l.folders.has(S.folder?.split("/")[0]??"")&&`${S.title} ${S.summary} ${O(S.boardId)} ${S.folder??""}`.toLocaleLowerCase().includes(l.query.trim().toLocaleLowerCase()),Ne=ve.filter(re).sort((S,K)=>Number(K.key===te)-Number(S.key===te)||(Ae.get(K.key)??0)-(Ae.get(S.key)??0)||S.key.localeCompare(K.key)),ke=Ne.slice(0,l.limit),ae=new Set(ke.map((S)=>S.key)),Se=z.filter(re),pe=De.links.map((S)=>({...S,edges:S.edges.filter((K)=>!l.hiddenLinks.has(K.kind))})).filter((S)=>S.edges.length&&ae.has(S.from)&&ae.has(S.to));q(()=>()=>{N(),Y.current||=!!w.current?.moved,w.current=null},[De,l.limit,l.query,l.context,l.folders,l.hiddenLinks]);let Ue=(S)=>{if(P.current!==null)return;let K=180,ue=()=>{let $e=w.current?.key===S,je=_.current.get(u);if(L.current)je.set(S,L.current);L.current=null;let le=new Map(ke.map((ge)=>[ge.key,je.get(ge.key)])),we=$T(le,pe.map((ge)=>({...ge,weight:ge.edges.length})),S,$e?1:K/180);for(let[ge,Le]of le)je.set(ge,Le);if(g((ge)=>ge+1),$e||--K>0&&we>0.02)P.current=requestAnimationFrame(ue);else P.current=null};P.current=requestAnimationFrame(ue)},xe=Ke(()=>{let S=_.current.get(u);if(!S)S=new Map,_.current.set(u,S);if(c.kind!=="card")return LT(ve,De.links.map((ge)=>({...ge,weight:ge.edges.length})),S);if(!S.has(te))S.set(te,{x:0,y:0});let K=Fe.filter((ge)=>ge.kind!=="card"||mo({kind:ge.relationKind,type:ge.type},e.find((Le)=>Le.id===ge.source.boardId)?.relationVocabulary).directed),ue=new Set(K.filter((ge)=>ge.to===te).map((ge)=>ge.from)),$e=new Set(K.filter((ge)=>ge.from===te).map((ge)=>ge.to)),je=ve.filter((ge)=>ge.key!==te).sort((ge,Le)=>ge.key.localeCompare(Le.key)),le=Je.width+Je.gap,we=Je.height+Je.gap;for(let ge of["incoming","outgoing","mutual"]){let Le=je.filter((on)=>(ue.has(on.key)&&!$e.has(on.key)?"incoming":$e.has(on.key)&&!ue.has(on.key)?"outgoing":"mutual")===ge),Rt=Le.filter((on)=>S.has(on.key)).map((on)=>S.get(on.key)),pt=S.get(te).y+we,pn=0;for(let[on,fs]of Le.entries())if(!S.has(fs.key)){let Pn=Rt.length?Math.max(...Rt.map((fn)=>ge==="mutual"?fn.x:fn.y))+(pn+1)*(ge==="mutual"?le:we):(on-(Le.length-1)/2)*(ge==="mutual"?le:we),xn=ge==="mutual"?{x:Pn,y:pt}:{x:ge==="incoming"?-360:360,y:Pn};while([...S.values()].some((fn)=>Math.abs(fn.x-xn.x)<le&&Math.abs(fn.y-xn.y)<we))xn.y+=we;S.set(fs.key,xn),pn++}}return new Map(S)},[De,u,h]),qe=(S)=>S.bundle?`${S.edges.length} links`:S.edges[0].kind==="card"?mo({kind:S.edges[0].relationKind,type:S.edges[0].type},e.find((K)=>K.id===S.edges[0].source.boardId)?.relationVocabulary).kind:S.edges[0].kind,W=Ke(()=>PT(new Map(ke.map((S)=>[S.key,xe.get(S.key)])),pe.map((S)=>({...S,label:S.edges.length>1||c.kind==="card"?qe(S):""})).sort((S,K)=>S.id.localeCompare(K.id))),[xe,De,l.limit,l.query,l.context,l.folders,l.hiddenLinks]),ye=l.camera??{x:0,y:0,scale:1},He=ke.filter((S)=>{let K=xe.get(S.key);return(K.x-Je.width/2)*ye.scale+ye.x<8||(K.x+Je.width/2)*ye.scale+ye.x>y.width-8||(K.y-Je.height/2)*ye.scale+ye.y<(c.kind==="card"?40:8)||(K.y+Je.height/2)*ye.scale+ye.y>y.height-64}).length,R=(S=!1)=>{let K=I.current;if(!K||!ke.length)return;let ue=c.kind==="card"?40:16,$e=K.clientHeight-ue-64-8,je=ke.flatMap((pt)=>{let pn=xe.get(pt.key);return[{x:pn.x-Je.width/2,y:pn.y-Je.height/2},{x:pn.x+Je.width/2,y:pn.y+Je.height/2}]});for(let pt of W.values())if(je.push(...pt.points),pt.label)je.push({x:pt.label.left,y:pt.label.top},{x:pt.label.right,y:pt.label.bottom});let le=Math.min(...je.map((pt)=>pt.x)),we=Math.min(...je.map((pt)=>pt.y)),ge=Math.max(...je.map((pt)=>pt.x))-le,Le=Math.max(...je.map((pt)=>pt.y))-we,Rt=Math.min(1,Math.max(S?1:0.005,Math.min((K.clientWidth-64)/ge,$e/Le)));B({camera:S&&c.kind==="card"?{x:K.clientWidth/2-xe.get(te).x,y:ue+$e/2-xe.get(te).y,scale:1}:{x:(K.clientWidth-ge*Rt)/2-le*Rt,y:ue+($e-Le*Rt)/2-we*Rt,scale:Rt}})};Me(()=>{if(t&&!l.camera&&ke.length)R(!0)},[t,u,l.camera]),q(()=>{if(!t||c.kind==="overview"||M)return;let S=he.has(Mt({boardId:c.boardId}));a((K)=>{let ue=K.filter((je)=>je.scene.kind==="overview"||he.has(Mt(je.scene))),$e=c.kind==="card"&&S?{kind:"board",boardId:c.boardId}:{kind:"overview"};return ls(ue.at(-1).scene)===ls($e)?ue:[...ue,Tg($e)]}),C("The focused endpoint was removed. Returned to its nearest available level.")},[t,te,M]);let ne=(S)=>{let K=xe.get(S.key),ue=I.current;if(!K||!ue)return;let $e=Math.max(1,ye.scale);B({camera:{x:ue.clientWidth/2-K.x*$e,y:ue.clientHeight/2-K.y*$e-20,scale:$e},limit:Math.max(l.limit,Ne.indexOf(S)+1)}),p(!1)},Ce=(S)=>{if(S.kind==="card"&&S.cardId)X({kind:"card",boardId:S.boardId,cardId:S.cardId});else X({kind:"board",boardId:S.boardId})},Ie=(S,K)=>{let ue=I.current;if(!ue)return;let $e=K??{x:ue.clientWidth/2,y:ue.clientHeight/2},je=Math.max(0.005,Math.min(3,S));B({camera:{x:$e.x-($e.x-ye.x)*je/ye.scale,y:$e.y-($e.y-ye.y)*je/ye.scale,scale:je}})},fe=De.links.find((S)=>S.id===l.inspection),it=fe?.edges??Fe,Ht=M?e.find((S)=>S.id===M.boardId):void 0,Ye=(S)=>{B({inspection:S.id}),m((K)=>K+1)},Lt=(S,K,ue)=>r("label",{class:"home-memory-check",children:[r("input",{type:"checkbox","aria-label":S,checked:K,onChange:ue},void 0,!1,void 0,this),r("span",{children:S},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F=c.kind!=="overview"&&!M,Ee=c.kind==="overview"?"Library":c.kind==="board"?O(c.boardId):M?.title??"Missing card";return r("main",{class:`home-memory graph-view${d?" sidebar-open":""}`,"aria-label":"Library Graph",style:{"--graph-node-width":`${Je.width}px`,"--graph-node-height":`${Je.height}px`},children:[r("div",{class:"home-memory-toolbar",children:[s.length>1&&r("button",{type:"button",class:"home-button",onClick:J,children:"Back"},void 0,!1,void 0,this),r("nav",{class:"graph-breadcrumb","aria-label":"Graph path",children:[r("button",{type:"button",class:"home-button",onClick:()=>V({kind:"overview"}),children:"Library"},void 0,!1,void 0,this),c.kind!=="overview"&&r(be,{children:[r("span",{children:"›"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>V({kind:"board",boardId:c.boardId}),children:O(c.boardId)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c.kind==="card"&&r(be,{children:[r("span",{children:"›"},void 0,!1,void 0,this),r("strong",{children:Ee},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("span",{children:[ke.length," of ",ve.length," connected drawn · ",He," partly/outside view ·"," ",ve.length-Ne.length," filtered · ",Math.max(0,Ne.length-ke.length)," hidden ·"," ",z.length," without links"]},void 0,!0,void 0,this),Ne.length>l.limit&&r("button",{type:"button",class:"home-button",onClick:()=>B({limit:l.limit+80}),children:"Show more connections"},void 0,!1,void 0,this),r("span",{class:`home-memory-live${o?" is-error":""}`,role:"status",children:o?"Update failed":n?"Updating…":"Live"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button home-memory-sidebar-toggle","aria-expanded":d,onClick:()=>p(!d),children:"Filters"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-body",children:[r("div",{class:"home-memory-stage",ref:I,"aria-label":"Pan the memory view",onWheel:(S)=>{S.preventDefault();let K=S.currentTarget.getBoundingClientRect();Ie(ye.scale*Math.exp(-S.deltaY*0.0015),{x:S.clientX-K.left,y:S.clientY-K.top})},onPointerDown:(S)=>{if(S.button!==0||S.target.closest('button, [role="button"]'))return;N(),Y.current=!1,w.current={id:S.pointerId,start:{x:S.clientX,y:S.clientY},origin:ye,moved:!1},S.currentTarget.setPointerCapture(S.pointerId)},onPointerMove:(S)=>{let K=w.current;if(!K||K.id!==S.pointerId||!(S.buttons&1))return;let ue=S.clientX-K.start.x,$e=S.clientY-K.start.y;if(Math.abs(ue)+Math.abs($e)>4)K.moved=!0;if(!K.moved)return;let je={x:K.origin.x+ue/(K.key?ye.scale:1),y:K.origin.y+$e/(K.key?ye.scale:1)};if(K.key)L.current=je,Ue(K.key);else B({camera:{...je,scale:ye.scale}})},onPointerUp:()=>{if(!w.current)return;Y.current=w.current.moved,w.current=null},onPointerCancel:()=>{let S=w.current;if(N(),S?.layout)_.current.set(u,S.layout),g((K)=>K+1);else if(S)B({camera:{...S.origin,scale:ye.scale}});Y.current=!!S?.moved,w.current=null},children:[c.kind==="card"&&r("div",{class:"graph-direction-caption",children:"Incoming starts left · outgoing starts right · drag to rearrange"},void 0,!1,void 0,this),r("div",{class:"home-memory-world",style:{transform:`translate(${ye.x}px, ${ye.y}px) scale(${ye.scale})`},children:[r("svg",{class:"home-memory-links graph-links","aria-label":"Graph connections",children:pe.map((S,K)=>{let ue=W.get(S.id);if(!ue)return null;let $e=S.edges[0],je=mo({kind:$e.relationKind,type:$e.type},e.find((Le)=>Le.id===$e.source.boardId)?.relationVocabulary),le=!S.bundle&&($e.kind!=="card"||je.directed),we=S.bundle?"var(--c-muted)":$e.kind==="card"?`var(--c-rel-${je.ink})`:$e.kind==="wiki"?"var(--c-rel-cites)":"var(--c-rel-derived)",ge=`${S.edges.length} ${S.bundle?"links":"link"} between ${he.get(S.from)?.title} and ${he.get(S.to)?.title}`;return r("g",{class:`graph-link${S.bundle?" is-bundle":" is-exact"}${S.from===v||S.to===v?" is-highlighted":""}${l.inspection===S.id?" is-selected":""}`,"data-from":S.from,"data-to":S.to,"data-count":S.edges.length,"data-link-id":S.id,role:"button",tabindex:0,"aria-label":`Inspect ${ge}`,style:{stroke:we},onClick:()=>Ye(S),onKeyDown:(Le)=>{if(Le.key==="Enter"||Le.key===" ")Le.preventDefault(),Ye(S)},children:[r("defs",{children:r("marker",{id:`graph-arrow-${K}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto",children:r("path",{d:"M 0 0 L 10 5 L 0 10 z",style:{fill:we,stroke:"none"}},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("path",{class:"graph-link-hit",d:ue.path},void 0,!1,void 0,this),r("path",{class:"graph-link-line",d:ue.path,"marker-end":le?`url(#graph-arrow-${K})`:void 0},void 0,!1,void 0,this),ue.label&&(S.edges.length>1||c.kind==="card")&&r("text",{x:ue.label.x,y:ue.label.y,children:qe(S)},void 0,!1,void 0,this)]},S.id,!0,void 0,this)})},void 0,!1,void 0,this),ke.map((S,K)=>{let ue=xe.get(S.key),$e=e.find((le)=>le.id===S.boardId),je=S.kind==="board"?S.inContext:!!$e?.pinnedTitles?.some((le)=>le.nodeId===S.cardId)||S.inContext&&!$e?.pin;return r("article",{"data-key":S.key,class:`graph-node is-${S.kind}${te===S.key?" is-selected":""}${je?" in-context":""}${c.kind!=="overview"&&!Pe(S)?" is-external":""}`,style:{left:ue.x,top:ue.y},onPointerEnter:()=>b(S.key),onPointerLeave:()=>b(null),children:r("button",{type:"button",class:"home-memory-select","aria-label":`${S.kind}: ${S.title}`,"aria-pressed":te===S.key,onClick:()=>{if(!Y.current)Ce(S);Y.current=!1},onPointerDown:(le)=>{if(le.button!==0)return;le.stopPropagation(),N(),Y.current=!1,w.current={id:le.pointerId,start:{x:le.clientX,y:le.clientY},origin:ue,key:S.key,layout:new Map(_.current.get(u)),moved:!1},le.currentTarget.setPointerCapture(le.pointerId)},onKeyDown:(le)=>{if(!le.key.startsWith("Arrow"))return;le.preventDefault();let we=(K+(le.key==="ArrowLeft"||le.key==="ArrowUp"?-1:1)+ke.length)%ke.length,ge=ke[we];if(ge)ne(ge),I.current?.querySelectorAll(".home-memory-select")[we]?.focus({preventScroll:!0})},children:[r("span",{class:"graph-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("strong",{children:S.title},void 0,!1,void 0,this),r("span",{children:S.kind==="board"?`${S.nodeCount??0} cards · ${A.internal.get(S.boardId)??0} internal`:`${O(S.boardId)} · ${S.type??"card"}`},void 0,!1,void 0,this),r("span",{class:je?"memory-context-legend":"",children:je?"⌖ In context":S.folder||"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},S.key,!1,void 0,this)})]},void 0,!0,void 0,this),r("div",{class:"home-memory-zoom",children:[r("button",{type:"button",class:"home-button","aria-label":"Zoom out",onClick:()=>Ie(ye.scale/1.2),children:"−"},void 0,!1,void 0,this),r("span",{children:[Math.round(ye.scale*100),"%"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button","aria-label":"Zoom in",onClick:()=>Ie(ye.scale*1.2),children:"+"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>R(),children:"Fit view"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(x||F||!t||!ke.length||o)&&r("div",{class:"home-memory-status",role:"status",children:x||(F?"This endpoint is no longer available. Use Back to return.":o?r(be,{children:["Memory update failed."," ",r("button",{type:"button",class:"home-button",onClick:i,children:"Retry"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):!t?"Loading memory…":Se.length?"No linked nodes in this view. Choose a node in No connections below.":"No matching nodes.")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("aside",{class:"home-memory-sidebar","aria-label":"Graph settings",children:[r("section",{children:[r("h2",{children:c.kind==="overview"?"Find boards":"Find cards and neighbors"},void 0,!1,void 0,this),r("label",{class:"home-memory-search",children:[r("span",{children:"Search graph"},void 0,!1,void 0,this),r("input",{type:"search",value:l.query,placeholder:"Search this graph…",onInput:(S)=>B({query:S.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),l.query&&r("ul",{class:"graph-search-results",children:[...ve,...z].filter(re).slice(0,30).map((S)=>r("li",{children:r("button",{type:"button",class:"home-button",onClick:()=>{if(Ae.has(S.key)||S.key===te)ne(S);else Ce(S)},children:S.title},void 0,!1,void 0,this)},S.key,!1,void 0,this))},void 0,!1,void 0,this),Lt("Only in context",l.context,()=>B({context:!l.context}))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Folders"},void 0,!1,void 0,this),[...new Set(De.nodes.map((S)=>S.folder?.split("/")[0]??""))].sort().map((S)=>r("div",{children:Lt(S||"Unfiled",!l.folders.has(S),()=>{let K=new Set(l.folders);if(K.has(S))K.delete(S);else K.add(S);B({folders:K})})},S,!1,void 0,this))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Links"},void 0,!1,void 0,this),Object.keys(OT).map((S)=>r("div",{children:Lt(OT[S],!l.hiddenLinks.has(S),()=>{let K=new Set(l.hiddenLinks);if(K.has(S))K.delete(S);else K.add(S);B({hiddenLinks:K})})},S,!1,void 0,this))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Library evidence"},void 0,!1,void 0,this),r("p",{class:"graph-accounting",children:[A.evidence.length," links ·"," ",[...A.pairs.values()].reduce((S,K)=>S+K.edges.length,0)," between boards ·"," ",[...A.internal.values()].reduce((S,K)=>S+K,0)," inside boards ·"," ",A.missing.length," missing"]},void 0,!0,void 0,this),r("p",{class:"home-memory-help",children:"Counts retain original evidence. Folder membership is not a relation. Filters change the drawing, not the totals."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Se.length>0&&r("details",{class:"graph-unlinked",open:!0,children:[r("summary",{children:["No connections (",Se.length,")"]},void 0,!0,void 0,this),r("div",{children:Se.map((S)=>r("button",{type:"button",class:"home-button graph-tray-node","aria-label":`${S.kind}: ${S.title}`,onClick:()=>Ce(S),children:[S.title,r("small",{children:S.kind==="board"?`${S.nodeCount??0} cards`:O(S.boardId)},void 0,!1,void 0,this)]},S.key,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-legend","aria-label":"Legend",children:[r("span",{children:"Click nodes to drill · drag nodes to rearrange · lines for evidence · drag background to pan · scroll to zoom · Fit shows extent · search reveals at readable size"},void 0,!1,void 0,this),r("span",{class:"memory-context-legend",children:"⌖ In context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(ip,{initiallyCollapsed:!0,reveal:f,children:M||fe?r("section",{class:"home-memory-details",role:"complementary","aria-label":"Selection details",children:[fe&&r("button",{type:"button",class:"home-memory-clear","aria-label":"Close details",onClick:()=>B({inspection:null}),children:"×"},void 0,!1,void 0,this),r("div",{class:"home-memory-detail-header",children:[r("div",{class:"home-memory-selection-title",children:[r("h3",{children:[fe?`${he.get(fe.from)?.title} ↔ ${he.get(fe.to)?.title}`:Ee," ·"," ",it.length," connections"]},void 0,!0,void 0,this),r("p",{children:fe?"Original evidence, not a new aggregate relation":`${M?.folder||"Unfiled"} / ${O(M.boardId)}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-actions",children:M&&r(be,{children:[r("button",{type:"button",class:"home-button is-primary",onClick:()=>void zt(M),children:["Open ",M.kind]},void 0,!0,void 0,this),Ht&&r(ho,{board:Ht},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-detail-body",children:[M&&r("p",{class:M.inContext?"memory-context-legend":"",children:[M.inContext?"⌖ In context":"Not in context",M.linksComplete===!1?" · Partial discovery":""]},void 0,!0,void 0,this),r("details",{class:"home-memory-connections",open:!0,children:[r("summary",{children:["Connections",fe?" within this pair":""]},void 0,!0,void 0,this),r("ul",{children:[it.map((S)=>{let K=c.kind==="card"?S.from===te:c.kind==="board"?S.source.boardId===c.boardId:!0,ue=K?S.target:S.source,$e=he.get(Mt(ue)),je=mo({kind:S.relationKind,type:S.type},e.find((we)=>we.id===S.source.boardId)?.relationVocabulary),le=S.kind!=="card"||je.directed;return r("li",{children:[r("span",{children:[le?K?"→":"←":"↔"," ",S.kind==="card"?ma({...S,kind:S.relationKind}):`${S.kind}${S.label?` · ${S.label}`:""}`]},void 0,!0,void 0,this),r("small",{children:[he.get(S.from)?.title??S.source.cardId??O(S.source.boardId)," ",le?"→":"↔"," ",he.get(S.to)?.title??S.target.cardId??O(S.target.boardId)," ·"," ",O(ue.boardId)]},void 0,!0,void 0,this),!$e||S.missing?r("span",{class:"home-memory-missing",children:["⚠ Missing target: ",ue.boardId,ue.cardId?` / ${ue.cardId}`:""]},void 0,!0,void 0,this):r("button",{type:"button",class:"home-button",onClick:()=>Ce($e),children:["Follow ",$e.title]},void 0,!0,void 0,this)]},S.id,!0,void 0,this)}),(t?.unresolvedLinks??[]).filter((S)=>c.kind==="board"?S.source.boardId===c.boardId:Mt(S.source)===te).map((S)=>r("li",{class:"home-memory-missing",children:["⚠ Unresolved wiki: [[",S.ref,"]]"]},`${Mt(S.source)}:${S.ref}`,!0,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):r("div",{class:"home-memory-empty-details",children:[r("h3",{children:"Connections"},void 0,!1,void 0,this),r("p",{class:"home-memory-help",children:"Click a board to explore, then a card to see its exact neighbors. Click a connection line to read the original evidence. Open content is always separate."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},"inspector",!1,void 0,this)]},void 0,!0,void 0,this)}function BT({folder:e,folders:t,onScopeChange:n}){let[o,i]=E(""),[s,a]=E(!1),[l,c]=E(null),[u,d]=E(""),p=Oe.value;q(()=>{if(p)Kt()},[p]),Me(()=>{let C=(y)=>{if(!Oe.value)return;if(!ir(y))return;y.preventDefault(),i(""),a(!1)};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[]);let f=Xn.value,m=(C)=>!e||C===e||!!C?.startsWith(`${e}/`),h=(f?.reviewCards??[]).filter((C)=>m(C.folder)),g=o.trim().toLocaleLowerCase(),v=h.filter((C)=>{let y=f?.cards[Mt(C)];return y&&(!s||y.sources.length>0)&&(!g||`${C.title} ${C.boardTitle} ${y.reasons.join(" ")} ${y.sources.map((k)=>k.title).join(" ")}`.toLocaleLowerCase().includes(g))}),b=new Set(Ge.value.filter((C)=>m(C.folder)).map((C)=>C.id)),x=Object.entries(f?.cards??{}).filter(([C,y])=>!y.retired&&y.unknown&&b.has(JSON.parse(C)[0])).length;if(!p)return null;return r("section",{class:"home-review-view","aria-label":"Card review queue",children:[r("div",{class:"home-main-head",children:[r("div",{class:"home-main-title",children:[r("h1",{class:"home-view-title",children:"Knowledge review"},void 0,!1,void 0,this),r("p",{children:e?`${e} and descendants`:"Whole library"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Review scope",r("select",{value:e,onChange:(C)=>n(C.currentTarget.value),children:[r("option",{value:"",children:"Whole library"},void 0,!1,void 0,this),t.map((C)=>r("option",{value:C,children:[C," and descendants"]},C,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-review-controls",children:[r("label",{children:["Find review cards",r("input",{type:"search",value:o,onInput:(C)=>i(C.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:s,onChange:(C)=>a(C.currentTarget.checked)},void 0,!1,void 0,this),"Source warnings only"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>void Kt(),children:"Refresh queue"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Oi.value&&r("p",{role:"status",children:"Queue unavailable. Retained results may be out of date. Refresh to retry."},void 0,!1,void 0,this),u&&r("p",{role:"alert",children:u},void 0,!1,void 0,this),!f?r("p",{children:"Loading review cards…"},void 0,!1,void 0,this):r(be,{children:[r("p",{class:"home-review-count",children:["Review needed: ",h.length," ",h.length===1?"card":"cards"," · Showing ",v.length]},void 0,!0,void 0,this),r("table",{class:"home-review-table",children:[r("thead",{children:r("tr",{children:[r("th",{children:"Card"},void 0,!1,void 0,this),r("th",{children:"Board"},void 0,!1,void 0,this),r("th",{children:"Why review"},void 0,!1,void 0,this),r("th",{children:"Last checked"},void 0,!1,void 0,this),r("th",{children:"Open"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r("tbody",{children:v.map((C)=>{let y=Mt(C),k=f.cards[y],_=[...k.reasons,...k.sources.map((I)=>`${I.title}: ${I.reasons.join(" ")||"Source needs review."}`)];return r("tr",{children:[r("td",{"data-label":"Card",children:C.title},void 0,!1,void 0,this),r("td",{"data-label":"Board",children:C.boardTitle},void 0,!1,void 0,this),r("td",{"data-label":"Why review",children:_.join(" ")||"A source needs review."},void 0,!1,void 0,this),r("td",{"data-label":"Last checked",children:k.lastValidatedAt?new Date(k.lastValidatedAt).toLocaleString():"Never checked"},void 0,!1,void 0,this),r("td",{children:r("button",{type:"button",class:"home-button",disabled:l===y,"aria-label":`Open review: ${C.title} on ${C.boardTitle}`,onClick:async()=>{if(!Oe.value)return;c(y),d("");let I=await zt(C,{review:!0});if(c(null),!I)d("Review did not open. The card may have moved or navigation was cancelled. Refresh and try again.")},children:"Open review"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},y,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v.length===0&&r("p",{children:"No actionable cards in these filters."},void 0,!1,void 0,this),r("p",{class:"home-review-neutral",children:["No review policy: ",x," ",x===1?"card":"cards",". Missing policy is neutral, not overdue. Explicit content or source warnings still enter the queue."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var TL=Pi({decayType:mn(["reality","decision","dependency","relevance"]),rate:mn(["fast","medium","slow","durable"]),triggers:We(U().trim().min(1)),revalidationMethod:U().trim().min(1),cadenceDays:Ze().int().min(1).max(36500).optional()}).refine((e)=>e.rate!=="medium"||e.cadenceDays!==void 0,{path:["cadenceDays"],message:"Medium lifecycle requires a cadence in days."}),FT=TL.safeExtend({id:U().trim().min(1),name:U().trim().min(1),glyph:U().trim().min(1)});var sr=(e,t,n,o,i,s)=>({id:e,name:t,glyph:n,decayType:o,rate:i,revalidationMethod:s,triggers:[],...i==="medium"?{cadenceDays:90}:{}}),HT=sr("research","Research","⌕","reality","medium","Check the sources and conflicting evidence."),UT=sr("metric","Metric","▥","reality","fast","Re-read the source dashboard and compare."),jT=sr("decision","Decision","⚑","decision","durable","Check for a superseding decision and changed dependencies."),ZT=sr("notes","Notes","✎","relevance","slow","Check relevance to the resumed task."),lp={"Org · team · personal":{categories:[sr("strategy","Strategy","◎","relevance","slow","Check the current goals and decisions."),sr("policy","Policy","◇","decision","slow","Check with the policy owner."),jT,HT,UT,ZT],folders:{Org:"strategy","Org/Policies":"policy",Team:"research","Team/Decisions":"decision","Team/Metrics":"metric",Personal:"notes"}},"Solo research":{categories:[sr("question","Question","?","relevance","slow","Check whether this question still matters."),sr("source","Source","▤","reality","medium","Re-read the original source."),sr("finding","Finding","◉","dependency","durable","Compare the supporting and contradicting evidence."),sr("note","Note","✎","relevance","slow","Check relevance to the resumed task.")],folders:{Projects:"question","Projects/Findings":"finding",Sources:"source",Notes:"note"}},"Product team":{categories:[HT,UT,jT,ZT],folders:{Discovery:"research","Discovery/Metrics":"metric",Delivery:"notes",Decisions:"decision"}},Empty:{categories:[],folders:{}}};function WT({folder:e,onClose:t}){let n=Oe.value,o=D(null),i=Xn.value,s=i?.folders.find((M)=>M.path===e),a=e?i?.resolvedFolders[e]:null,[l,c]=E(s?.categoryId??""),[u,d]=E(!!s?.lifecycleOverride),[p,f]=E(s?.lifecycleOverride??a?.lifecycle??ba),[m,h]=E(()=>i?.categories[0]?structuredClone(i.categories[0]):null),[g,v]=E(null),b=i?.categories.find((M)=>M.id===m?.id),x=i?.folders.filter((M)=>M.categoryId===m?.id)??[],[C,y]=E(!1),[k,_]=E(""),[I,w]=E(()=>JSON.stringify(m)),[P,L]=E("Basics"),[N,Y]=E(""),[B,J]=E(null),X=!e&&JSON.stringify(m)!==I,V=(M)=>{if(!Oe.value||C||B)return;if(X)J(()=>M);else M()},ee=()=>{if(!Oe.value)return;if(B)J(null);else if(g)v(null);else V(t)};bn(o,n,{onEscape:ee}),Me(()=>{if(!n&&o.current?.contains(document.activeElement))document.querySelector('button[aria-label="Settings"]')?.focus({preventScroll:!0})},[n]),q(()=>{if(n)Kt()},[n]);let he=(M)=>{let O=structuredClone(M);h(O),w(JSON.stringify(O)),L("Basics"),v(null),_("")},A=async(M,O)=>{if(!Oe.value)return!1;return(await de("knowledgeWrite",`/api/canvas/knowledge/${M}`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)}))?.ok===!0},te=async(M)=>{if(!Oe.value||C||!i)return;let O=tn;y(!0),_("");let Pe=!0,Fe=lp[M];for(let De of Fe.categories){if(!Oe.value||O!==tn){Pe=!1;break}if(!i.categories.some((Ae)=>Ae.id===De.id))Pe=await A("category",{category:De});if(!Pe)break}if(Pe)for(let[De,Ae]of Object.entries(Fe.folders)){if(!Oe.value||O!==tn){Pe=!1;break}if(!i.folders.some((ve)=>ve.path===De))Pe=await A("folder",{path:De,categoryId:Ae,lifecycleOverride:null});if(!Pe)break}await Kt(),y(!1),_(Pe?M==="Empty"?"No starter data added. Existing data is unchanged.":"Starter data added. Existing categories and folder settings were preserved.":"Template stopped at a failed save. Saved entries remain; retry adds only missing entries.")};return r("div",{class:"knowledge-backdrop",hidden:!n,style:n?void 0:{display:"none"},onKeyDown:(M)=>{if(M.key==="Escape")M.stopPropagation(),M.preventDefault(),ee()},children:r("div",{ref:o,class:`knowledge-dialog${e?"":" is-category-editor"}`,role:"dialog","aria-modal":"true","aria-label":e?"Folder settings":"Categories",children:[r("header",{children:[r("div",{class:"knowledge-dialog-title",children:[r("h2",{children:e?`${e.split("/").at(-1)} · Folder settings`:"Workspace categories"},void 0,!1,void 0,this),e&&r("span",{class:"knowledge-folder-path",children:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button","aria-label":"Close settings",disabled:C,onClick:()=>V(t),children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k&&r("p",{role:"status",children:k},void 0,!1,void 0,this),B&&r("div",{role:"group","aria-label":"Discard category changes",class:"category-discard",children:[r("p",{children:"Discard unsaved category changes?"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>J(null),children:"Keep editing"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>{if(!Oe.value)return;let M=B;J(null),w(JSON.stringify(m)),M()},children:"Discard changes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!i?r("p",{children:"Knowledge settings unavailable. Close and retry."},void 0,!1,void 0,this):e?r("form",{onSubmit:async(M)=>{if(M.preventDefault(),!Oe.value||C)return;let O=tn;y(!0);let Pe=await A("folder",{path:e,categoryId:l||null,lifecycleOverride:u?Ql(p):null});if(await Kt(),y(!1),Pe&&Oe.value&&O===tn)t();else if(!Pe)_("Folder settings were not saved. Retry.")},children:[r("div",{class:"knowledge-field",children:[r("span",{children:"Category"},void 0,!1,void 0,this),r(Mr,{label:"Category",value:l,onChange:c,options:[{value:"",label:"Use the parent’s"},...i.categories.map((M)=>({value:M.id,label:`${M.glyph} ${M.name}`}))]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:["Currently"," ",a?.category?`${a.category.glyph} ${a.category.name} · ${a.categorySourceFolder===e?"set here":`inherited from ${a.categorySourceFolder}`}`:"unknown",". Cards inherit their category; only lifecycle can be overridden."]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:u,onChange:(M)=>d(M.currentTarget.checked)},void 0,!1,void 0,this)," ","Override lifecycle for this folder"]},void 0,!0,void 0,this),u?r(Yl,{value:p,onChange:f},void 0,!1,void 0,this):r("p",{children:"Lifecycle comes from the selected category or parent. Unknown has no passive expiry."},void 0,!1,void 0,this),r("button",{type:"submit",disabled:C,children:"Save folder settings"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r("details",{class:"category-templates",children:[r("summary",{children:"Add from template"},void 0,!1,void 0,this),r("div",{class:"knowledge-presets",children:Object.entries(lp).map(([M,O])=>r("button",{type:"button",disabled:C||!!B,onClick:()=>V(()=>{if(X)h(b?structuredClone(b):null),w(JSON.stringify(b??null));te(M)}),children:[r("strong",{children:M},void 0,!1,void 0,this),r("span",{children:Object.keys(O.folders).join(" / ")||"No folders or categories"},void 0,!1,void 0,this)]},M,!0,void 0,this))},void 0,!1,void 0,this),r("p",{children:"Templates add missing data. They never replace your existing settings. Rename any category below."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"category-editor-columns",children:[r("section",{class:"category-list-panel",children:[r("h3",{children:[i.categories.length," categories"]},void 0,!0,void 0,this),r("label",{children:["Search categories",r("input",{type:"search",value:N,onInput:(M)=>Y(M.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",disabled:C,onClick:()=>V(()=>he({...ba,id:crypto.randomUUID(),name:"",glyph:"◇"})),children:"Add category"},void 0,!1,void 0,this),r("div",{class:"category-library",role:"group","aria-label":"Workspace categories",children:i.categories.filter((M)=>M.name.toLocaleLowerCase().includes(N.toLocaleLowerCase())).map((M)=>r("button",{type:"button",class:"category-choice",disabled:C,"aria-pressed":m?.id===M.id,onClick:()=>{if(m?.id!==M.id)V(()=>he(M))},children:[r("strong",{children:[M.glyph," ",M.name]},void 0,!0,void 0,this),r("span",{children:[M.decayType," · ",M.rate,M.rate==="medium"&&M.cadenceDays?` · ${M.cadenceDays} days`:""]},void 0,!0,void 0,this)]},M.id,!0,void 0,this))},void 0,!1,void 0,this),r("p",{children:"Folders with no category above them stay unknown. Categories carry no colour."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m&&r("form",{class:"category-inspector",noValidate:!0,onSubmit:async(M)=>{if(M.preventDefault(),!Oe.value||C)return;let O=tn,Pe=FT.safeParse({...m,...Ql(m)});if(!Pe.success){let Ae=String(Pe.error.issues[0].path[0]);L(["name","glyph","id"].includes(Ae)?"Basics":"Review policy"),_(Pe.error.issues[0].message),setTimeout(()=>{if(!Oe.value||O!==tn)return;let ve=Ae==="name"?"Name":Ae==="glyph"?"Glyph":Ae==="cadenceDays"?"Cadence in days":"How to check",z=o.current?.querySelectorAll("label");Array.from(z??[]).find((re)=>re.textContent?.trim().startsWith(ve))?.querySelector("input")?.focus()},0);return}y(!0);let Fe=await de("knowledgeWrite","/api/canvas/knowledge/category",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:Pe.data})}),De=Fe?.ok===!0;if(await Kt(),y(!1),!Oe.value||O!==tn)return;if(De){let Ae=Fe?.category??Pe.data;h(Ae),w(JSON.stringify(Ae))}_(De?"Category saved. Inheriting folders now use these defaults.":"Category was not saved. Retry.")},children:[r("h3",{children:b?"Edit category defaults":"New category"},void 0,!1,void 0,this),r("div",{role:"tablist","aria-label":"Category settings",class:"category-tabs",children:["Basics","Review policy","Usage"].map((M)=>r("button",{type:"button",role:"tab",id:`category-tab-${M.replace(" ","-")}`,"aria-controls":"category-tab-panel","aria-selected":P===M,onClick:()=>L(M),children:M},M,!1,void 0,this))},void 0,!1,void 0,this),r("fieldset",{disabled:C||!!B,id:"category-tab-panel",role:"tabpanel","aria-labelledby":`category-tab-${P.replace(" ","-")}`,class:"category-tab-content",children:[P==="Basics"&&r(be,{children:[r("label",{children:["Name",r("input",{required:!0,value:m.name,onInput:(M)=>h({...m,name:M.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Glyph",r("input",{required:!0,value:m.glyph,onInput:(M)=>h({...m,glyph:M.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"category-glyph-choices",role:"group","aria-label":"Glyph choices",children:[...new Set(Object.values(lp).flatMap((M)=>M.categories.map((O)=>O.glyph)))].map((M)=>r("button",{type:"button","aria-label":`Choose glyph ${M}`,"aria-pressed":m.glyph===M,onClick:()=>h({...m,glyph:M}),children:M},M,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P==="Review policy"&&r(Yl,{value:m,onChange:(M)=>h({...m,...M})},void 0,!1,void 0,this),P==="Usage"&&r(be,{children:[r("p",{children:"Folders inherit these defaults. Folder settings and card lifecycle overrides remain unchanged. Unknown has no passive expiry."},void 0,!1,void 0,this),x.length===0&&r("p",{children:"No folders assigned."},void 0,!1,void 0,this),b&&(x.length>0?r("p",{children:["Cannot delete: assigned to ",x.map((M)=>M.path).join(", "),". Reassign or clear those folder categories first. Empty folders also count."]},void 0,!0,void 0,this):g===b.id?r("div",{role:"group","aria-label":"Confirm category deletion",children:[r("p",{children:["Delete ",b.name,"? This removes the category from this workspace."]},void 0,!0,void 0,this),r("button",{type:"button",disabled:C,onClick:()=>v(null),children:"Cancel deletion"},void 0,!1,void 0,this),r("button",{type:"button",class:"is-danger",disabled:C,onClick:async()=>{if(!Oe.value||C)return;let M=tn;y(!0);let O=await de("knowledgeRemove",`/api/canvas/knowledge/category/${encodeURIComponent(b.id)}`,null,{method:"DELETE"});if(await Kt(),y(!1),!Oe.value||M!==tn)return;if(v(null),O?.ok===!0)h(null),w("null");_(O?.ok===!0?"Category deleted.":O?.error??"Category was not deleted. Retry.")},children:"Confirm deletion"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("button",{type:"button",class:"is-danger",disabled:C,onClick:()=>v(b.id),children:"Delete category"},void 0,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("footer",{class:"category-editor-footer",children:[r("button",{type:"button",disabled:C||!!B,onClick:()=>V(t),children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"submit",disabled:C||!!B,children:"Save category"},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)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function qT({onClose:e}){let t=D(null),n=Xn.value?.relationPresets,[o,i]=E(),s=o===void 0?n?.[0]??null:o,[a,l]=E(null),[c,u]=E(null),[d,p]=E(null),[f,m]=E(""),[h,g]=E(!1),[v,b]=E(""),[x,C]=E(!1),y=D(null);q(()=>{if(!d)return;let N=document.activeElement;return y.current?.querySelector("button")?.focus(),()=>{if(N instanceof HTMLElement&&N.isConnected)N.focus()}},[d]);let k=s,_=a!==null&&JSON.stringify(a)!==JSON.stringify(c),I=(N)=>{if(h)return;if(_)p(()=>N);else N()},w=()=>{if(d)p(null);else if(x)C(!1);else I(e)};bn(t,!0,{onEscape:w});let P=(N)=>{i(N?structuredClone(N):null),l(null),u(null),C(!1),b("")},L=(N,Y)=>{if(a)l({...a,vocabulary:a.vocabulary.map((B,J)=>J===N?{...B,...Y}:B)})};return r("div",{class:"knowledge-backdrop",onKeyDown:(N)=>{if(N.key==="Escape")N.preventDefault(),N.stopPropagation(),w()},children:r("div",{ref:t,class:"knowledge-dialog is-category-editor relation-presets-dialog",role:"dialog","aria-modal":"true","aria-label":"Workspace relation presets",children:[r("header",{children:[r("h2",{children:"Workspace relation presets"},void 0,!1,void 0,this),r("button",{type:"button",disabled:h||!!d,"aria-label":"Close relation presets",onClick:()=>I(e),children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Saved templates are shared across the workspace. Saving does not apply a preset to any board."},void 0,!1,void 0,this),v&&r("p",{role:"status",children:v},void 0,!1,void 0,this),d&&r("div",{ref:y,role:"alertdialog","aria-label":"Discard preset changes","aria-modal":"true",class:"relation-dirty-guard",children:[r("p",{children:"Discard unsaved preset changes?"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>p(null),children:"Keep editing"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>{let N=d;p(null),N()},children:"Discard changes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{inert:d?!0:void 0,children:!n?r("p",{children:"Relation presets unavailable. Close and retry."},void 0,!1,void 0,this):r("div",{class:"category-editor-columns",children:[r("section",{children:[r("h3",{children:[n.length," presets"]},void 0,!0,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>I(()=>{P(null);let N={id:crypto.randomUUID(),name:"",vocabulary:[]};u(structuredClone(N)),l(N)}),children:"Add preset"},void 0,!1,void 0,this),r("div",{class:"category-library",role:"group","aria-label":"Workspace relation presets",children:n.map((N)=>r("button",{type:"button",class:"category-choice",disabled:h,"aria-pressed":(a?.id??s?.id)===N.id,onClick:()=>I(()=>P(N)),children:[r("strong",{children:N.name},void 0,!1,void 0,this),r("span",{children:N.vocabulary.map((Y)=>Y.kind).join(" · ")||"No relation kinds"},void 0,!1,void 0,this)]},N.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("section",{class:"relation-preset-detail",children:a?r("form",{class:"relation-vocabulary",onSubmit:async(N)=>{if(N.preventDefault(),h)return;if(new Set(a.vocabulary.map((B)=>B.kind.trim())).size!==a.vocabulary.length){b("Give each relation kind a unique name.");return}g(!0);let Y=await de("relationPresetWrite","/api/canvas/knowledge/relation-preset",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({preset:a})});if(await Kt(),g(!1),Y?.ok)P(Y.preset);b(Y?.ok?"Preset saved for the workspace. Existing boards are unchanged.":"Preset was not saved. Retry.")},children:[r("h3",{children:s?"Customize shared preset":"New shared preset"},void 0,!1,void 0,this),r("label",{children:["Name",r("input",{required:!0,pattern:".*\\S.*",maxLength:80,disabled:h,value:a.name,onInput:(N)=>l({...a,name:N.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Kinds stay open. Choose meaning ink and direction, not pin, agent or warning colours."},void 0,!1,void 0,this),a.vocabulary.map((N,Y)=>r("div",{class:"vocabulary-row",children:[r("input",{required:!0,pattern:".*\\S.*","aria-label":`Kind ${Y+1}`,maxLength:80,disabled:h,value:N.kind,onInput:(B)=>L(Y,{kind:B.currentTarget.value})},void 0,!1,void 0,this),r("select",{"aria-label":`Ink ${Y+1}`,disabled:h,value:N.ink,onChange:(B)=>L(Y,{ink:B.currentTarget.value}),children:["supports","contradicts","cites","derived","informs","related"].map((B)=>r("option",{children:B},B,!1,void 0,this))},void 0,!1,void 0,this),r("label",{children:[r("input",{type:"checkbox",disabled:h,checked:N.directed,onChange:(B)=>L(Y,{directed:B.currentTarget.checked})},void 0,!1,void 0,this),"Arrow"]},void 0,!0,void 0,this),r("button",{type:"button","aria-label":`Remove kind ${Y+1}`,disabled:h,onClick:()=>l({...a,vocabulary:a.vocabulary.filter((B,J)=>J!==Y)}),children:"×"},void 0,!1,void 0,this)]},Y,!0,void 0,this)),r("button",{type:"button",disabled:h||a.vocabulary.length>=64,onClick:()=>l({...a,vocabulary:[...a.vocabulary,{kind:"",ink:"related",directed:!0}]}),children:"Add kind"},void 0,!1,void 0,this),r("div",{class:"relation-preset-footer",children:[r("button",{type:"submit",disabled:h,children:"Save preset"},void 0,!1,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>I(()=>P(s)),children:"Cancel customization"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):k?r(be,{children:[r("h3",{children:k.name},void 0,!1,void 0,this),r("p",{children:"Saved relations · read-only example"},void 0,!1,void 0,this),r("p",{children:"Use on board replaces only the chosen board’s vocabulary. Matching connections use its ink and direction; connection records are not rewritten."},void 0,!1,void 0,this),r("ul",{class:"relation-preset-preview","aria-label":"Saved relation preview",children:k.vocabulary.map((N)=>r("li",{style:{"--relation-ink":`var(--c-rel-${N.ink})`},children:[r("strong",{children:N.kind},void 0,!1,void 0,this),r("div",{class:"relation-preset-example",children:[r("span",{children:"Example A"},void 0,!1,void 0,this),r("svg",{viewBox:"0 0 120 24","aria-hidden":"true",children:[r("line",{x1:"8",y1:"12",x2:"112",y2:"12",stroke:"currentColor","stroke-width":"2","stroke-dasharray":N.ink==="related"?"3 5":void 0},void 0,!1,void 0,this),N.directed&&r("path",{d:"M 102 6 L 112 12 L 102 18",fill:"none",stroke:"currentColor","stroke-width":"2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{children:"Example B"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{children:[N.ink," · ",N.directed?"Directed: A → B":"Undirected: A — B"]},void 0,!0,void 0,this)]},N.kind,!0,void 0,this))},void 0,!1,void 0,this),!k.vocabulary.length&&r("p",{children:"No relation kinds. This empty preset can still be used on a board."},void 0,!1,void 0,this),r("div",{class:"relation-preset-footer",children:k&&r(be,{children:[r("label",{children:["Apply saved preset to board",r("select",{"aria-label":"Apply saved preset to board",disabled:h,value:f,onChange:(N)=>m(N.currentTarget.value),children:[r("option",{value:"",children:"Choose a board"},void 0,!1,void 0,this),Ge.value.map((N)=>r("option",{value:N.id,children:N.name},N.id,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"relation-preset-use",disabled:h||!f,onClick:async()=>{if(h||!f)return;g(!0);let N=await vr(f,{relationVocabulary:k.vocabulary});g(!1),b(N?"Preset applied. Connection records and other boards are unchanged.":"Preset was not applied. Retry.")},children:"Use on board"},void 0,!1,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>{u(structuredClone(k)),l(structuredClone(k)),C(!1),b("")},children:"Customize preset"},void 0,!1,void 0,this),x?r("div",{role:"group","aria-label":"Confirm preset deletion",children:[r("p",{children:["Delete ",k.name,"? Boards that used it keep their existing vocabulary."]},void 0,!0,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>C(!1),children:"Cancel deletion"},void 0,!1,void 0,this),r("button",{type:"button",class:"is-danger",disabled:h,onClick:async()=>{if(h)return;g(!0);let N=await de("relationPresetRemove",`/api/canvas/knowledge/relation-preset/${encodeURIComponent(k.id)}`,null,{method:"DELETE"});if(await Kt(),g(!1),C(!1),N?.ok)P(null);b(N?.ok?"Preset deleted. Existing boards are unchanged.":"Preset was not deleted. Retry.")},children:"Confirm deletion"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("button",{type:"button",class:"is-danger",disabled:h,onClick:()=>C(!0),children:"Delete preset"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("p",{children:"Choose a saved preset or add a new one."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function GT(e){if(!e)return"never opened";if((Date.now()-new Date(e).getTime())/86400000>=30)return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});return Yd(e)}var ar=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function KT(e){return(e.links?.length??0)+(e.backlinks?.length??0)}async function Ig(e){let t=await On("New board","Board name",{confirm:"Create"});if(t)await Ek(t,e)}var VT="pmx-canvas-home-collapsed";function IL(){try{let e=localStorage.getItem(VT);if(e)return new Set(JSON.parse(e))}catch{}return new Set([CT])}function EL(e){try{localStorage.setItem(VT,JSON.stringify([...e]))}catch{}}var oc=(e,t)=>e.folder===t||!!e.folder?.startsWith(`${t}/`),lr=(e)=>e.split("/").at(-1)??e;function AL({board:e}){return r("div",{class:"home-thumb","aria-hidden":"true",children:r("div",{class:"home-thumb-inner",children:(e.preview??[]).map((t,n)=>r("span",{class:`home-thumb-card${t.pinned?" is-pinned":""}`,style:{left:`${t.x*100}%`,top:`${t.y*100}%`,width:`${t.w*100}%`,height:`${t.h*100}%`}},n,!1,void 0,this))},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function XT(){let e=Ge.value,t=Oe.value,[n,o]=E("Folders"),i=!t&&n==="Review"?"Folders":n,[s,a]=E(()=>[...Ge.value].sort((Ee,S)=>(S.lastOpenedAt??"").localeCompare(Ee.lastOpenedAt??""))[0]?.folder??""),[l,c]=E([]),[u,d]=E(null),[p,f]=E(!1),[m,h]=E(null),[g,v]=E(!1),[b,x]=E(!1),[C,y]=E(null),[k,_]=E(null),[I,w]=E(""),[P,L]=E([]),[N,Y]=E(IL),[B,J]=E(!1),[X,V]=E(!1),ee=D(null),he=D(null),A=[...new Set([...e.flatMap((F)=>F.folder?tc(F.folder):[]),...(Xn.value?.folders??[]).flatMap((F)=>tc(F.path)),...l.flatMap(tc)])].sort((F,Ee)=>F.localeCompare(Ee)),te=(F)=>A.filter((Ee)=>F?Ee.startsWith(`${F}/`)&&!Ee.slice(F.length+1).includes("/"):!Ee.includes("/")),M=I.trim().toLocaleLowerCase(),O=e.filter((F)=>F.pin),Pe=O.reduce((F,Ee)=>F+(Ee.mapChars??0),0),Fe=te(s),De=e.filter((F)=>(F.folder??"")===s).sort((F,Ee)=>(Ee.lastOpenedAt??"").localeCompare(F.lastOpenedAt??"")),Ae=M?e.filter((F)=>`${F.name} ${F.folder??""}`.toLocaleLowerCase().includes(M)):[],ve=e.find((F)=>F.id===m)??null,z=e.find((F)=>F.id===C),re=e.find((F)=>F.id===k),Ne=new Set(e.filter((F)=>!s||oc(F,s)).map((F)=>F.id)),ke=Object.entries(Xn.value?.cards??{}).filter(([F])=>Ne.has(JSON.parse(F)[0])).map(([,F])=>F),ae=ke.filter((F)=>!F.retired&&(F.due||F.sources.length)).length,Se=ke.filter((F)=>F.unknown).length,pe=Xn.value?.resolvedFolders[s]?.category,Ue=new Map;for(let[F,Ee]of Object.entries(Xn.value?.cards??{})){if(Ee.retired||!(Ee.due||Ee.sources.length))continue;let[S,K]=JSON.parse(F),ue=Ue.get(S)??[];ue.push(K),Ue.set(S,ue)}let xe=M?Ae:De,qe=async(F)=>{if(!Oe.value)return;let Ee=tn,S=Ue.get(F)?.[0];if(!S)return;if(await zt({boardId:F,cardId:S})&&Oe.value&&Ee===tn&&se.value===F)Ro.value="To review"};q(()=>{let F=I.trim();if(!F){L([]);return}let Ee=!1,S=window.setTimeout(()=>{de("searchLibrary",`/api/canvas/search?q=${encodeURIComponent(F)}&scope=library&limit=30`,null).then((K)=>{if(!Ee)L(K?.results??[])})},150);return()=>{Ee=!0,window.clearTimeout(S)}},[I]),q(()=>{if(g)he.current?.querySelector('[role="menuitem"]')?.focus()},[g]),q(()=>{if(m&&!e.some((F)=>F.id===m))h(null)},[e,m]),Me(()=>{if(i!=="Folders"||!m)return;let F=(Ee)=>{if(!ir(Ee))return;Ee.preventDefault(),h(null),x(!1)};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[i,m]);let W=(F)=>zt(F),ye=(F)=>{let Ee=new Set(N);if(Ee.has(F))Ee.delete(F);else Ee.add(F);Y(Ee),EL(Ee)},He=(F)=>{a(F),w(""),h(null),J(!1)},R=(F)=>{h(F),v(!1),x(!1)},ne=async()=>{let F=await On("New folder","Folder name",{confirm:"Create"});if(!F)return;let Ee;try{Ee=rp(s?`${s}/${F}`:F)}catch{return}if(!Ee)return;c((S)=>[...S,Ee]),He(Ee)},Ce=async(F)=>{let Ee=await On("Rename board","Board name",{initial:F.name,confirm:"Rename"});if(Ee&&Ee!==F.name)await vr(F.id,{name:Ee})},Ie=(F,Ee)=>{let S=te(F),K=!N.has(F),ue=e.filter((je)=>oc(je,F)).length,$e=e.some((je)=>je.pin&&oc(je,F));return r("li",{children:[r("div",{class:`home-tree-row${s===F&&!M?" is-selected":""}`,"data-folder":F,children:[r("span",{class:"home-tree-indent",style:{width:`${Ee*16}px`}},void 0,!1,void 0,this),S.length>0?r("button",{type:"button",class:"home-tree-chevron","aria-label":K?`Fold ${lr(F)}`:`Unfold ${lr(F)}`,"aria-expanded":K,onClick:()=>ye(F),children:K?r(Us,{},void 0,!1,void 0,this):r(oi,{},void 0,!1,void 0,this)},void 0,!1,void 0,this):r("span",{class:"home-tree-chevron"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-tree-name",onClick:()=>He(F),children:lr(F)},void 0,!1,void 0,this),$e&&r("span",{class:"home-tree-pin","aria-label":"Has a board in the agent's context"},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:ue},void 0,!1,void 0,this)]},void 0,!0,void 0,this),K&&S.length>0&&r("ul",{class:"home-tree",children:S.map((je)=>Ie(je,Ee+1))},void 0,!1,void 0,this)]},F,!0,void 0,this)},fe=r("ul",{class:"home-tree","aria-label":"Folders",children:[te("").map((F)=>Ie(F,0)),r("li",{children:r("div",{class:`home-tree-row is-unfiled${s===""&&!M?" is-selected":""}`,children:[r("span",{class:"home-tree-chevron"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-tree-name",onClick:()=>He(""),children:"Unfiled"},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:e.filter((F)=>!F.folder).length},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),it=r("ul",{class:"home-pinned","aria-label":"Pinned boards",children:O.map((F)=>r("li",{children:r("button",{type:"button",class:"home-pinned-row",onClick:()=>He(F.folder??""),children:[r("span",{class:"home-pin-dot","aria-hidden":"true",children:r(uo,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"home-pinned-name",children:F.name},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:F.folder?lr(F.folder):"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},F.id,!1,void 0,this))},void 0,!1,void 0,this),Ht=r("label",{class:"home-search",children:[r(Nu,{},void 0,!1,void 0,this),r("span",{class:"sr-only",children:"Find boards, cards and folders"},void 0,!1,void 0,this),r("input",{type:"search",placeholder:"Boards, cards, folders…",value:I,onInput:(F)=>w(F.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ye=(F)=>r("li",{children:r("article",{class:`home-card${F.pin?" is-pinned":""}${m===F.id?" is-selected":""}`,"data-testid":"home-board","data-board-id":F.id,children:[r("button",{type:"button",class:"home-card-select","aria-label":F.name,"aria-pressed":m===F.id,onClick:()=>R(F.id),onDblClick:()=>void Mn(F.id),children:[r(AL,{board:F},void 0,!1,void 0,this),r("span",{class:"home-card-body",children:[r("span",{class:"home-card-name",children:F.name},void 0,!1,void 0,this),r("span",{class:"home-card-readme",children:F.summary??"No README yet."},void 0,!1,void 0,this),r("span",{class:"home-card-meta",children:[r("span",{children:ar(F.nodeCount,"card")},void 0,!1,void 0,this),KT(F)>0&&r("span",{children:["↔ ",ar(KT(F),"link")]},void 0,!0,void 0,this),r("span",{class:"home-card-when",children:GT(F.lastOpenedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),t&&Ue.has(F.id)&&r("button",{type:"button",class:"home-card-review","aria-label":`Review ${F.name}`,onClick:()=>void qe(F.id),children:["⧗ Review ",ar(Ue.get(F.id).length,"card")]},void 0,!0,void 0,this),r(ho,{board:F},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},F.id,!1,void 0,this),Lt=ve&&r("aside",{class:"home-details","aria-label":"Board details","data-testid":"home-details",children:[r("button",{type:"button",class:"home-details-grip","aria-label":"Close details",onClick:()=>R(null)},void 0,!1,void 0,this),r("div",{class:"home-details-head",children:[r("span",{class:"home-details-folder",children:ve.folder?lr(ve.folder):"Unfiled"},void 0,!1,void 0,this),r("span",{class:"home-details-name",children:ve.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:`home-details-context${ve.pin?" is-on":""}`,children:[r("span",{class:"home-details-context-text",children:r("span",{class:"home-details-context-label",children:ve.pin?"In the agent's context":"Not in the agent's context"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",role:"switch","aria-checked":!!ve.pin,"aria-label":"In the agent's context",class:"home-switch",onClick:()=>void $s(ve.id,!ve.pin),children:r("span",{class:"home-switch-knob"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b?r("div",{class:"home-details-confirm",role:"alert",children:[r("span",{children:["Delete ",r("strong",{children:ve.name},void 0,!1,void 0,this)," and its ",ar(ve.nodeCount,"card")," and snapshots? This can't be undone."]},void 0,!0,void 0,this),r("span",{class:"home-details-actions",children:[r("button",{type:"button",class:"home-button",onClick:()=>x(!1),children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button is-danger",onClick:()=>{x(!1),Nk(ve.id)},children:"Delete board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):r("div",{class:"home-details-actions",children:[r("button",{type:"button",class:"home-button is-primary",onClick:()=>void Mn(ve.id),children:"Open board"},void 0,!1,void 0,this),t&&Ue.has(ve.id)&&r("button",{type:"button",class:"home-button",onClick:()=>void qe(ve.id),children:"Review cards"},void 0,!1,void 0,this),r("span",{class:"home-more",children:[r("button",{ref:ee,type:"button",class:"home-button is-icon","aria-label":"More: move, rename, create from, delete","aria-haspopup":"menu","aria-expanded":g,onClick:()=>v(!g),children:r(ml,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),g&&r("span",{ref:he,class:"home-more-menu",role:"menu",onKeyDown:(F)=>{let Ee=[...he.current?.querySelectorAll('[role="menuitem"]')??[]],S=Ee.indexOf(document.activeElement);if(F.key==="Escape")F.preventDefault(),v(!1),ee.current?.focus();else if(F.key==="ArrowDown"||F.key==="ArrowUp"){F.preventDefault();let K=F.key==="ArrowDown"?1:-1;Ee[(S+K+Ee.length)%Ee.length]?.focus()}},children:[["Move…",()=>y(ve.id)],["Rename…",()=>void Ce(ve)],["Create from…",()=>_(ve.id)],["Delete…",()=>x(!0)]].map(([F,Ee])=>r("button",{type:"button",role:"menuitem",class:"home-more-item",onClick:()=>{v(!1),Ee()},children:F},F,!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);return r("div",{class:"home-shell",children:[u!==null&&r(WT,{folder:u||void 0,onClose:()=>d(null)},u,!1,void 0,this),p&&r(qT,{onClose:()=>f(!1)},void 0,!1,void 0,this),r("nav",{class:"home-view-tabs","aria-label":"Library view",children:[["Folders","Map","Graph","Review"].filter((F)=>t||F!=="Review").map((F)=>r("button",{type:"button",class:"home-button","aria-pressed":i===F,onClick:()=>o(F),children:F},F,!1,void 0,this)),r("button",{type:"button",class:"home-button",onClick:()=>f(!0),children:"Relation presets"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i==="Map"||i==="Graph"?i==="Map"?r(RT,{},void 0,!1,void 0,this):r(DT,{},void 0,!1,void 0,this):r("div",{class:`home-view${ve&&i==="Folders"?" has-details":""}`,"data-testid":"home-view",children:[r("aside",{class:`home-library${B?" is-open":""}`,"aria-label":"Library",children:[r("div",{class:"home-library-head",children:[r("span",{class:"home-library-title",children:"Library"},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:ar(e.length,"board")},void 0,!1,void 0,this),t&&r("button",{type:"button",class:"home-button",onClick:()=>{if(Oe.value)d("")},children:"Categories"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ht,O.length>0&&r("section",{class:"home-library-section",children:[r("span",{class:"home-section-label",children:"Pinned boards"},void 0,!1,void 0,this),it,r("span",{class:"home-pinned-cost",children:["≈ ",Jl(Pe)," tokens · ",ar(O.length,"board")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("section",{class:"home-library-section is-folders",children:[r("span",{class:"home-section-label",children:"Folders"},void 0,!1,void 0,this),fe,r("button",{type:"button",class:"home-tree-new",onClick:()=>void ne(),children:"+ New folder"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("main",{class:"home-main",children:[r("div",{class:"home-narrow",children:[Ht,O.length>0&&r(be,{children:[r("button",{type:"button",class:"home-narrow-context","aria-expanded":X,onClick:()=>V(!X),children:[r("span",{class:"home-pin-dot","aria-hidden":"true",children:r(uo,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"home-narrow-context-label",children:["In context: ",ar(O.length,"board")]},void 0,!0,void 0,this),r("span",{class:"home-narrow-context-cost",children:["≈ ",Jl(Pe)," tokens"]},void 0,!0,void 0,this),r("span",{children:X?"Hide ▴":"Show ▾"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&it]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-narrow-picker","aria-expanded":B,onClick:()=>J(!B),children:[s?lr(s):"Library",r("span",{class:"home-tree-count",children:["· ",s?e.filter((F)=>oc(F,s)).length:De.length," ▾"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i==="Review"?r(BT,{folder:s,folders:A,onScopeChange:He},void 0,!1,void 0,this):r(be,{children:[r("div",{class:"home-main-head",children:[r("div",{class:"home-main-title",children:[r("nav",{class:"home-crumbs","aria-label":"Folder path",children:[r("button",{type:"button",onClick:()=>He(""),children:"Library"},void 0,!1,void 0,this),s&&tc(s).map((F)=>r("span",{children:[r("span",{class:"home-crumb-sep",children:"/"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>He(F),children:lr(F)},void 0,!1,void 0,this)]},F,!0,void 0,this))]},void 0,!0,void 0,this),r("h1",{class:"home-view-title",children:M?`Results for “${I.trim()}”`:s?lr(s):"Library"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&r("button",{type:"button",class:"home-button",onClick:()=>{if(Oe.value)d(s)},children:[" ",s?"Folder settings":"Categories"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button is-primary",onClick:()=>void Ig(s||null),children:s?"New board here":"New board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&Xn.value&&!M&&r("section",{class:"home-main-section","aria-label":"Folder review summary",children:[r("span",{class:"home-section-label",children:["Card review · ",s?"In this folder and subfolders":"Across the library"]},void 0,!0,void 0,this),r("div",{class:"home-card-meta",children:[pe&&r("span",{children:["Category: ",pe.glyph," ",pe.name]},void 0,!0,void 0,this),r("button",{type:"button",class:`home-review-link${ae?" has-review":""}`,onClick:()=>{o("Review"),h(null)},children:["Review needed: ",ar(ae,"card")]},void 0,!0,void 0,this),r("span",{children:["No review policy: ",ar(Se,"card")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e.length===0?r("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):M?r(be,{children:[P.length>0&&r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:["Cards · ",P.length]},void 0,!0,void 0,this),r("ul",{class:"home-hits","aria-label":"Library search results",children:P.map((F)=>r("li",{children:r("button",{type:"button",class:"home-hit",onClick:()=>void W(F),children:[r("span",{class:"home-card-name",children:F.title||F.boardTitle},void 0,!1,void 0,this),t&&F.qualification?.retired&&r("span",{class:"category-tag",children:"Retired"},void 0,!1,void 0,this),r("span",{class:"home-card-meta",children:[F.boardTitle," · ",F.snippet]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},`${F.boardId}:${F.cardId}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ae.length>0?r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:["Boards · ",Ae.length]},void 0,!0,void 0,this),r("ul",{class:"home-cards",children:Ae.map(Ye)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):P.length===0&&r("div",{class:"home-view-empty",role:"status",children:["No boards match “",I.trim(),"”."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[Fe.length>0&&r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:["Folders · ",Fe.length]},void 0,!0,void 0,this),r("ul",{class:"home-folders",children:Fe.map((F)=>{let Ee=e.filter((ue)=>oc(ue,F)),S=Ee.map((ue)=>ue.lastOpenedAt??"").sort().at(-1),K=Ee.filter((ue)=>ue.pin).length;return r("li",{children:r("button",{type:"button",class:"home-folder","data-testid":"home-section","data-folder":F,onClick:()=>He(F),children:[r("span",{class:"home-folder-stack","aria-hidden":"true",children:[r("span",{},void 0,!1,void 0,this),r("span",{},void 0,!1,void 0,this),r("span",{},void 0,!1,void 0,this)]},void 0,!0,void 0,this),K>0&&r("span",{class:"home-folder-context",children:[K," in context"]},void 0,!0,void 0,this),r("span",{class:"home-folder-name",children:lr(F)},void 0,!1,void 0,this),r("span",{class:"home-folder-meta",children:[ar(Ee.length,"board"),S?` · opened ${GT(S)}`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},F,!1,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:[s?`Boards in ${lr(s)}`:"Unfiled boards"," · ",xe.length]},void 0,!0,void 0,this),xe.length>0?r("ul",{class:"home-cards","aria-label":s?`Boards in ${s}`:"Unfiled boards",children:xe.map(Ye)},void 0,!1,void 0,this):r("div",{class:"home-view-empty",children:"No boards here yet."},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),i==="Folders"&&Lt,z&&r(TT,{board:z,folders:A,onClose:()=>y(null)},z.id,!1,void 0,this),re&&r(IT,{board:re,onClose:()=>_(null)},re.id,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var cs=ie(!1);function RL(e){return e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}function JT(){let[e,t]=E(!1),[n,o]=E(!1),[i,s]=E(null),[a,l]=E(null),[c,u]=E(!1),[d,p]=E(""),f=cs.value,m=se.value;if(q(()=>{if(!f||!m)return;let g=!0;return l(null),p(""),s(null),de("exportPreview",`/api/canvas/export/preview?board=${encodeURIComponent(m)}&includeFiles=${e}&includeDerivedText=${n}`,null).then((v)=>{if(g)s(v?.manifest??null)}),()=>{g=!1}},[f,e,n,m]),q(()=>{o(!1)},[f,m]),q(()=>{if(!f)return;let g=(v)=>{if(v.key!=="Escape")return;v.stopPropagation(),cs.value=!1};return window.addEventListener("keydown",g,{capture:!0}),()=>window.removeEventListener("keydown",g,{capture:!0})},[f]),!f)return null;let h=async()=>{if(!i||i.boardId!==se.value)return;u(!0);let g=await de("exportBoard","/api/canvas/export",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({board:i.boardId,includeFiles:e,includeDerivedText:n})});if(u(!1),g?.path&&se.value===i.boardId)l(g)};return r("div",{class:"text-prompt-backdrop",onPointerDown:()=>cs.value=!1,children:r("div",{class:"text-prompt export-dialog",role:"dialog","aria-label":"Export board","data-testid":"export-dialog",onPointerDown:(g)=>g.stopPropagation(),children:[r("div",{class:"text-prompt-title",children:["Export ",i?`“${i.boardName}”`:"board"]},void 0,!0,void 0,this),!i?r("div",{class:"export-dialog-note",children:"Reading the board…"},void 0,!1,void 0,this):r(be,{children:[r("div",{class:"export-dialog-note",children:"One HTML file anyone can open without installing anything. It will contain:"},void 0,!1,void 0,this),r("ul",{class:"export-dialog-list",children:[r("li",{children:[i.cards," card",i.cards!==1?"s":""," and ",i.connections," connection",i.connections!==1?"s":""]},void 0,!0,void 0,this),i.frames>0&&r("li",{children:[i.frames," embedded pages, charts or diagrams, with the code that draws them"]},void 0,!0,void 0,this),i.embeddedImages>0&&r("li",{children:[i.embeddedImages," local images"]},void 0,!0,void 0,this),i.placeholders.length>0&&r("li",{children:["Shown as placeholders:"," ",i.placeholders.map((g)=>`${g.title} (${g.reason})`).join(", ")]},void 0,!0,void 0,this),i.remoteImages.length>0&&r("li",{children:["Web images loaded when opened: ",i.remoteImages.join(", ")]},void 0,!0,void 0,this),i.links.length>0&&r("li",{children:["Links included in cards: ",i.links.join(", ")]},void 0,!0,void 0,this),i.frameNetworkDestinations.length>0&&r("li",{children:["Network destinations referenced by embedded pages: ",i.frameNetworkDestinations.join(", ")]},void 0,!0,void 0,this),i.embeddedCodeCanAccessNetwork&&r("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),(i.attachments?.length??0)>0&&r("p",{children:"Original attachments are excluded. Their filenames remain visible."},void 0,!1,void 0,this),(i.sourceDerivedCards?.length??0)>0&&r("label",{class:"export-dialog-files",children:[r("input",{type:"checkbox",checked:n,onChange:(g)=>o(g.currentTarget.checked)},void 0,!1,void 0,this),r("span",{children:["Include imported document text (",i.sourceDerivedCards.length," cards)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i.files.length>0&&r("label",{class:"export-dialog-files",children:[r("input",{type:"checkbox",checked:e,onChange:(g)=>t(g.target.checked)},void 0,!1,void 0,this),r("span",{children:["Include the contents of ",i.files.length," local file",i.files.length!==1?"s":"",": ",i.files.map((g)=>g.path).join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&r("div",{class:"export-dialog-result","data-testid":"export-result",children:[r("div",{children:["Saved (",RL(a.bytes),"): ",r("code",{children:a.path},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"export-dialog-links",children:tt()?r("button",{type:"button",disabled:c,onClick:async()=>{u(!0),p("");try{await Ww(a.url)}catch(g){p(g instanceof Error?g.message:"Download failed. Try again.")}finally{u(!1)}},children:c?"Downloading…":"Download"},void 0,!1,void 0,this):r(be,{children:[r("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:"Open"},void 0,!1,void 0,this),r("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),tt()&&r("p",{children:"Download the HTML file to open it outside ChatGPT."},void 0,!1,void 0,this),d&&r("p",{role:"alert",children:d},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",onClick:()=>cs.value=!1,children:a?"Done":"Cancel"},void 0,!1,void 0,this),!a&&r("button",{type:"button",class:"text-prompt-confirm",disabled:!i||c,onClick:()=>void h(),children:c?"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 Eg({presence:e,size:t=18}){return r("span",{class:"writer-avatar",style:{background:So(e.sessionId),width:`${t}px`,height:`${t}px`},"aria-hidden":"true",children:Nd(e.label)},void 0,!1,void 0,this)}function YT(){let e=zd.value;if(tr.value||e.length===0)return null;let t=e.reduce((i,s)=>i+s.opCount,0),n=e.length===1?e[0].label:`${e.length} writers`,o=ts.value;return r(_e,{label:`${e.length} external writer${e.length===1?"":"s"} on this board`,body:"Click for their activity.",align:"end",children:r("button",{type:"button",class:"external-indicator","data-testid":"external-indicator","aria-label":`${n} external activity, ${t} operation${t===1?"":"s"}`,"aria-expanded":o,onClick:()=>{ts.value=!o},children:[r("span",{class:"external-indicator-avatars",children:e.slice(0,3).map((i)=>r(Eg,{presence:i},i.sessionId,!1,void 0,this))},void 0,!1,void 0,this),r("span",{class:"external-indicator-label",children:n},void 0,!1,void 0,this),r("span",{class:"external-indicator-ops hud-collapsible-text",children:[t," op",t===1?"":"s"]},void 0,!0,void 0,this),r("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function PL(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 NL(e){return e.reduce((t,n)=>n.lastSeenAt>t?n.lastSeenAt:t,"")}function ML(){return[...qt.value.values()].filter((e)=>!e.auto&&e.phase==="forming")}function QT(){let e=ts.value,t=zd.value,n=nr(e?1e4:0);if(Me(()=>{if(!e)return;let l=(c)=>{if(c.key!=="Escape"||c.defaultPrevented)return;if(c.preventDefault(),da.value)da.value=!1;else ts.value=!1};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),!e||tr.value||t.length===0)return null;let o=Kh.value,i=ML().filter((l)=>!o||(l.source??"")===o),s=fi.value.filter((l)=>!o||l.sessionId===o),a=(l,c)=>r("button",{type:"button",class:`activity-filter${o===l?" is-active":""}`,style:l?{"--writer":So(l)}:void 0,"aria-pressed":o===l,onClick:()=>{Kh.value=l},children:c},void 0,!1,void 0,this);return r("div",{class:"activity-feed","data-testid":"activity-feed",role:"dialog","aria-label":"External activity",children:[r("div",{class:"activity-feed-head",children:[r("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"activity-feed-titles",children:[r("div",{class:"activity-feed-title",children:["External activity — ",t.length," writer",t.length===1?"":"s"]},void 0,!0,void 0,this),r("div",{class:"activity-feed-sub",children:[t.reduce((l,c)=>l+c.opCount,0)," writes · last"," ",Md(NL(t),n)," · live writers"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"activity-feed-close","aria-label":"Close activity feed",onClick:()=>{ts.value=!1},children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"activity-filters",children:[a(null,"All"),t.map((l)=>a(l.sessionId,l.label))]},void 0,!0,void 0,this),r("div",{class:"activity-rows",children:[i.map((l)=>r("div",{class:"activity-row is-pending","data-testid":"activity-proposal",children:[r("span",{class:"activity-glyph tone-purple","aria-hidden":"true",children:"▢"},void 0,!1,void 0,this),r("div",{class:"activity-main",children:[r("div",{class:"activity-text",children:["Proposing: ",r("b",{children:l.label?.trim()||`${l.kind} intent`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"activity-meta",children:[l.reason?.trim()||"Intent signalled — a real veto window before the mutation",l.source?` · ${l.source}`:""]},void 0,!0,void 0,this),r("div",{class:"activity-actions",children:[r("button",{type:"button",class:"activity-veto",onClick:()=>{Li(l).then((c)=>{if(c)zi(l.id)})},children:"Veto"},void 0,!1,void 0,this),r("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),r("span",{class:"activity-age",children:"now"},void 0,!1,void 0,this)]},l.id,!0,void 0,this)),s.length===0&&i.length===0&&r("div",{class:"activity-empty",children:"No writes yet."},void 0,!1,void 0,this),s.map((l)=>{let{glyph:c,tone:u}=PL(l.op);return r("div",{class:"activity-row","data-testid":"activity-row","data-op":l.op,children:[r("span",{class:`activity-glyph tone-${u}`,"aria-hidden":"true",children:c},void 0,!1,void 0,this),r("div",{class:"activity-main",children:[r("div",{class:"activity-text",children:l.summary},void 0,!1,void 0,this),r("div",{class:"activity-writer",style:{color:So(l.sessionId)},children:l.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"activity-age",children:Md(l.at,n)},void 0,!1,void 0,this)]},l.id,!0,void 0,this)})]},void 0,!0,void 0,this),r("div",{class:"activity-feed-foot",children:[r("span",{class:"activity-feed-note",children:"All writes ghost first · Esc vetoes"},void 0,!1,void 0,this),r("button",{type:"button",class:"activity-feed-link",onClick:()=>{da.value=!0},children:"Writers"},void 0,!1,void 0,this),xt.value&&r("button",{type:"button",class:"activity-feed-link is-accent",onClick:()=>{ts.value=!1,vi()},children:["Start session ",r(ri,{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 zL(){let e=[];if(To.value)e.push("scoped");if(Co.value.length>0)e.push("gated");return e.length>0?e.join(" + "):"open"}function eI(){let e=da.value,t=nr(e?1e4:0),n=D(null);if(bn(n,e),!e)return null;let o=xt.value?en.value.filter((a)=>a.attached):[],i=zd.value,s=()=>{da.value=!1};return r(be,{children:[r("div",{class:"writers-scrim",onClick:s,"aria-hidden":"true"},void 0,!1,void 0,this),r("div",{ref:n,class:"writers-sheet","data-testid":"writers-sheet",role:"dialog","aria-modal":"true","aria-label":"Connected writers",children:[r("div",{class:"writers-head",children:[r("span",{class:"writers-title",children:"Connected writers"},void 0,!1,void 0,this),r("span",{class:"writers-board",children:xr.value.slice(0,12)},void 0,!1,void 0,this),r("button",{type:"button",class:"activity-feed-close","aria-label":"Close writers",onClick:s,children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"writers-body",children:[xt.value&&r(be,{children:[r("div",{class:"writers-section",children:"Agent sessions"},void 0,!1,void 0,this),o.length===0&&r("div",{class:"writers-empty",children:"None attached — start one from the top bar."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.map((a)=>r("div",{class:"writers-row",children:[r(Eg,{presence:a,size:20},void 0,!1,void 0,this),r("span",{class:"writers-name",children:a.label},void 0,!1,void 0,this),r("span",{class:"writers-config",children:zL()},void 0,!1,void 0,this)]},a.sessionId,!0,void 0,this)),r("div",{class:"writers-section",children:xt.value?"External writers · MCP":"Live writers"},void 0,!1,void 0,this),i.length===0&&r("div",{class:"writers-empty",children:"No external writers right now."},void 0,!1,void 0,this),i.map((a)=>r("div",{class:"writers-row",children:[r(Eg,{presence:a,size:20},void 0,!1,void 0,this),r("span",{class:"writers-name is-mono",children:a.label},void 0,!1,void 0,this),r("span",{class:"writers-meta",children:[a.source!==a.label?`${a.source} · `:"","wrote"," ",Md(a.lastSeenAt,t)," ago"]},void 0,!0,void 0,this)]},a.sessionId,!0,void 0,this))]},void 0,!0,void 0,this),r("div",{class:"writers-foot",children:[r("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),r("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 tI({nodeId:e}){let t=se.value,[n,o]=E(null),[i,s]=E(!1),a=et.value,l=H.value,c=Ge.value;q(()=>{let m=!1;if(o(null),s(!1),t)de("relations",`/api/canvas/memory-graph?focus=${encodeURIComponent(Mt({boardId:t,cardId:e}))}&depth=1`,null).then((h)=>{if(!m)o(h),s(!h)});return()=>{m=!0}},[t,e,a,l,c]);let u=t?Mt({boardId:t,cardId:e}):"",d=n?.edges.filter((m)=>m.kind!=="member"&&(m.from===u||m.to===u))??[],p=(m)=>{let h=m.to===u;if(h&&m.relationKind==="supports")return"Evidence for";if(h&&m.relationKind==="contradicts")return"Evidence against";let g=Ud({kind:m.relationKind,type:m.type});if(g)return(g==="from"?!h:h)?"Used by":"Sources";if(m.relationKind==="cites"||m.type==="references")return h?"Used by":"Sources";if(!h&&m.relationKind==="supports")return"Used by";return"Connections"},f=["Evidence for","Evidence against","Sources","Used by","Connections"];return d.sort((m,h)=>f.indexOf(p(m))-f.indexOf(p(h))),r("aside",{class:"relations-panel","aria-label":"Relations",children:[r("h3",{children:"Relations"},void 0,!1,void 0,this),!n&&r("p",{role:"status",children:i?"Relations unavailable. Reopen to retry.":"Loading relations…"},void 0,!1,void 0,this),n&&d.length===0&&r("p",{children:"No connections yet."},void 0,!1,void 0,this),d.map((m,h)=>{let g=m.from===u,v=g?m.target:m.source,b=n?.nodes.find((y)=>y.key===Mt(v)),x=c.find((y)=>y.id===m.source.boardId),C=mo({kind:m.relationKind,type:m.type},x?.relationVocabulary);return r("div",{class:"relation-row",children:[(h===0||p(d[h-1])!==p(m))&&r("h4",{children:p(m)},void 0,!1,void 0,this),r("span",{class:"relation-kind",style:{color:`var(--c-rel-${C.ink})`},children:[g?"→":"←"," ",m.relationKind??m.type??m.kind]},void 0,!0,void 0,this),m.missing?r("span",{children:"Missing target"},void 0,!1,void 0,this):r("button",{type:"button",class:"relation-target",onClick:()=>void zt(v),children:b?.title??v.boardId},void 0,!1,void 0,this),m.label&&r("span",{children:m.label},void 0,!1,void 0,this),r("p",{children:m.reason??"No reason recorded."},void 0,!1,void 0,this)]},m.id,!0,void 0,this)}),r("p",{children:"Manage shared relation presets in Home."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nI(e,t){switch(e.type){case"markdown":return r(Yu,{node:e,expanded:t},void 0,!1,void 0,this);case"mcp-app":return r(di,{node:e,expanded:t},void 0,!1,void 0,this);case"webpage":return r(Ed,{node:e,expanded:t},void 0,!1,void 0,this);case"json-render":return r(di,{node:e,expanded:t},void 0,!1,void 0,this);case"graph":return r(di,{node:e,expanded:t},void 0,!1,void 0,this);case"board":return r(Gd,{node:e},void 0,!1,void 0,this);case"prompt":return r(Ad,{node:e},void 0,!1,void 0,this);case"response":return r(Rd,{node:e,expanded:t},void 0,!1,void 0,this);case"status":return r(Td,{node:e},void 0,!1,void 0,this);case"context":return r(zu,{node:e,expanded:t},void 0,!1,void 0,this);case"ledger":return r(Du,{node:e},void 0,!1,void 0,this);case"trace":return r(Pd,{node:e},void 0,!1,void 0,this);case"file":return r(Ou,{node:e,expanded:t},void 0,!1,void 0,this);case"diff":return r($u,{node:e},void 0,!1,void 0,this);case"mermaid":return r(sd,{node:e,expanded:t},void 0,!1,void 0,this);case"image":return r(Id,{node:e,expanded:t},void 0,!1,void 0,this);case"html":return r(Hl,{node:e,expanded:t},void 0,!1,void 0,this);default:return r("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function oI(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 $L(e){if(!e)return 0;return e.split(/\s+/).filter(Boolean).length}function LL(e,t){return e!==null&&typeof e==="object"&&e.source===Qn&&e.type==="presentation-exit"&&e.token===t}function OL(e){return e==="ArrowRight"||e==="PageDown"||e===" "||e==="ArrowLeft"||e==="PageUp"||e==="Home"||e==="End"}function rI(e){return e instanceof HTMLElement&&Boolean(e.closest(".html-presentation-exit"))}function iI(){let e=Bt.value,t=e?H.value.get(e):void 0,[n,o]=E(!1),[i,s]=E(null),[a,l]=E(!1),[c,u]=E(""),d=D(null),p=D(null),f=oe(()=>{l(!1),Cr()},[]),m=oe(()=>{u(`presentation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`),l(!0)},[]),h=oe((A)=>{document.querySelector(".html-presentation-overlay iframe.html-node-frame-presentation")?.contentWindow?.postMessage({source:Qn,token:c,...A},"*")},[c]),g=oe(()=>{l(!1)},[]),v=oe((A)=>{if(A.key==="Escape"){A.preventDefault(),A.stopPropagation(),l(!1);return}if(A.key==="Tab"&&!rI(A.target)){A.preventDefault(),A.stopPropagation(),p.current?.focus();return}if((A.key===" "||A.key==="Enter")&&rI(A.target))return;if(!OL(A.key))return;A.preventDefault(),A.stopPropagation(),h({type:"presentation-key",key:A.key})},[h]),b=oe((A)=>{if(A.target.classList.contains("expanded-overlay-backdrop"))Cr()},[]),x=oe(()=>{if(!t)return;let A=oI(t);if(!A)return;navigator.clipboard.writeText(A).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},[t]),C=oe(()=>{if(!e)return;lo(e)},[e]);q(()=>{l(!1)},[e]),Me(()=>{if(!a)return;let A=()=>{let O=d.current;if(!O||O.contains(document.activeElement))return;O.focus()},te=[0,50,150].map((O)=>window.setTimeout(A,O)),M=(O)=>{if(!LL(O.data,c))return;l(!1)};return document.addEventListener("keydown",v,!0),window.addEventListener("message",M),()=>{te.forEach((O)=>{window.clearTimeout(O)}),document.removeEventListener("keydown",v,!0),window.removeEventListener("message",M)}},[v,c,a]);let y=D(null),k=oe(()=>e?document.querySelector(`.canvas-node[data-node-id="${CSS.escape(e)}"]`):null,[e]),_=Oe.value&&Ct.value?.nodeId===e,I=!Oe.value&&Ct.value?.nodeId===e&&!!document.activeElement?.closest(".lifecycle-dialog");if(bn(y,t!==void 0&&!_,{restoreTo:k}),Me(()=>{if(I)document.querySelector('button[aria-label="Settings"]')?.focus({preventScroll:!0})},[_]),!t)return null;let w=t.data.title||t.data.path?.split("/").pop()||an[t.type],P=oI(t),L=$L(P),N=e?kt.value.has(e):!1,Y=P.length>0,B=$o.value===e,J=t.type==="mcp-app"||t.type==="webpage"||t.type==="json-render"||t.type==="graph",X=G_(t),V=Bo(t.type),ee=t.data.provenance&&typeof t.data.provenance==="object"?t.data.provenance:null,he=ee?[ee.sourceKind,ee.sourceUri,ee.syncedAt?`synced ${ee.syncedAt.slice(11,16)}`:null].filter((A)=>typeof A==="string"&&A.length>0).join(" · "):null;return r("div",{class:"expanded-overlay-backdrop",onPointerDown:b,style:{pointerEvents:B?"none":"auto"},children:r("div",{ref:y,class:`expanded-overlay-panel${N?" is-pinned":""}`,role:"dialog","aria-modal":_?void 0:"true","aria-label":w,"data-testid":"expanded-node",children:[r("div",{class:"expanded-header",children:[r("span",{class:"expanded-kind-icon","aria-hidden":"true",children:r(V,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"expanded-title",children:w},void 0,!1,void 0,this),r("span",{class:"expanded-kind-pill",children:an[t.type]},void 0,!1,void 0,this),r(_e,{label:N?"In agent context — click to unpin":"Pin as agent context",children:r("button",{type:"button",class:`expanded-pin${N?" is-on":""}`,onClick:C,"aria-label":N?"In agent context — click to unpin":"Pin as agent context","aria-pressed":N,children:"✦"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"expanded-spacer"},void 0,!1,void 0,this),r("div",{class:"expanded-actions",children:[Oe.value&&r("button",{type:"button",class:"expanded-action-btn",onClick:()=>Es(t.id),children:"Review"},void 0,!1,void 0,this),r("button",{type:"button",class:"expanded-action-btn","aria-pressed":i===e,onClick:()=>s(i===e?null:e),children:"Relations"},void 0,!1,void 0,this),Y&&r(_e,{label:"Copy content to clipboard",children:r("button",{type:"button",class:"expanded-action-btn",onClick:x,children:n?"Copied!":"Copy"},void 0,!1,void 0,this)},void 0,!1,void 0,this),nd(t)&&r(_e,{label:"Open as a full-page site in the system browser",children:r("button",{type:"button",class:"expanded-action-btn",onClick:()=>void od(t),children:["Open in tab ",r(ri,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X&&r(_e,{label:"Present this HTML node fullscreen",children:r("button",{type:"button",class:"expanded-action-btn expanded-action-primary",onClick:m,children:"Present"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(_e,{label:"Close",shortcut:"Esc",align:"end",children:r("button",{type:"button",class:"expanded-close",onClick:f,"aria-label":"Close",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"expanded-content-row",children:[r("div",{class:`expanded-body${J?" is-embedded":""}`,children:J?r("div",{style:{flex:1,minHeight:0,display:"flex"},children:nI(t,!0)},void 0,!1,void 0,this):nI(t,!0)},void 0,!1,void 0,this),i===e&&r(tI,{nodeId:t.id},e,!1,void 0,this)]},void 0,!0,void 0,this),r(Zd,{node:t},void 0,!1,void 0,this),r("div",{style:{"--ax-dock-bleed":"0px","--ax-dock-pad":"16px"},children:r(qd,{node:t},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"expanded-footer",children:[r("span",{class:"expanded-footer-meta",children:[he,L>0?`${L.toLocaleString()} word${L!==1?"s":""}`:null].filter(Boolean).join(" · ")||an[t.type].toLowerCase()},void 0,!1,void 0,this),r("span",{class:"expanded-spacer"},void 0,!1,void 0,this),r("span",{class:`expanded-footer-hint${B?" is-saving":""}`,children:B?"Saving edits…":"esc or click outside to close"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&a&&r("div",{ref:d,class:"html-presentation-overlay",role:"dialog","aria-modal":"true","aria-label":`Present ${w}`,tabIndex:-1,onKeyDownCapture:v,children:[r("button",{ref:p,type:"button",class:"html-presentation-exit",onClick:g,"aria-label":"Exit presentation",children:"Exit presentation"},void 0,!1,void 0,this),r("div",{class:"html-presentation-stage",children:r(Hl,{node:t,expanded:!0,presentation:!0,presentationExitToken:c},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 aI=168,lI=112,cp=20;function sI(e,t,n,o){let i=Array.from(e.values()),s=0,a=0,l=1000,c=800;if(i.length>0){s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(let v of i)s=Math.min(s,v.position.x),a=Math.min(a,v.position.y),l=Math.max(l,v.position.x+v.size.width),c=Math.max(c,v.position.y+v.size.height)}let u=-t.x/t.scale,d=-t.y/t.scale,p=u+n/t.scale,f=d+o/t.scale,m={minX:Math.min(s,u)-cp,minY:Math.min(a,d)-cp,maxX:Math.max(l,p)+cp,maxY:Math.max(c,f)+cp},h=m.maxX-m.minX||1,g=m.maxY-m.minY||1;return{bounds:m,scale:Math.min(aI/h,lI/g)}}function cI({viewport:e,nodes:t,onNavigate:n,containerWidth:o,containerHeight:i}){let s=D(null),a=D(!1),l=t.value,c=e.value,u=sI(l,c,o,i),{bounds:d,scale:p}=u,f=(w)=>(w-d.minX)*p,m=(w)=>(w-d.minY)*p,h=oe((w)=>{let P=s.current;if(!P)return;let L=P.getBoundingClientRect(),N=(w.clientX-L.left)/L.width*aI,Y=(w.clientY-L.top)/L.height*lI,B=sI(t.value,e.value,o,i),J=e.value,X=o/J.scale,V=i/J.scale,ee=N/B.scale+B.bounds.minX,he=Y/B.scale+B.bounds.minY;n(-(ee-X/2)*J.scale,-(he-V/2)*J.scale)},[t,e,o,i,n]),g=oe((w)=>{w.stopPropagation(),w.preventDefault(),a.current=!0,h(w);let P=(N)=>{if(a.current)h(N)},L=()=>{a.current=!1,document.removeEventListener("pointermove",P),document.removeEventListener("pointerup",L)};document.addEventListener("pointermove",P),document.addEventListener("pointerup",L)},[h]),v=st.value,b=kt.value,x=tr.value?$d.value:new Set,C=To.value,y=C?Bd(C.nodeIds.map((w)=>l.get(w)).filter((w)=>w!==void 0),C.padding):null,k=en.value.map((w)=>({id:w.sessionId,phase:w.phase,worker:w.parentAgentId!=null,external:!w.attached,at:Ld(w,(P)=>l.get(P))})).filter((w)=>w.at!==null),_=-c.x/c.scale,I=-c.y/c.scale;return r("div",{ref:s,class:"minimap","data-testid":"minimap","aria-label":"Minimap — click to jump, drag the frame to pan",onPointerDown:g,children:[Array.from(l.values()).map((w)=>{let P=w.type==="group";return r("span",{class:`minimap-node${P?" is-group":""}${v.has(w.id)?" is-selected":""}${b.has(w.id)?" is-pinned":""}${x.has(w.id)?" is-agent":""}`,"data-kind":w.type,style:{left:`${f(w.position.x)}px`,top:`${m(w.position.y)}px`,width:`${Math.max(P?6:4,w.size.width*p)}px`,height:`${Math.max(P?5:3,w.size.height*p)}px`}},w.id,!1,void 0,this)}),y&&r("span",{class:"minimap-fence",style:{left:`${f(y.x)}px`,top:`${m(y.y)}px`,width:`${y.width*p}px`,height:`${y.height*p}px`}},void 0,!1,void 0,this),k.map((w)=>r("span",{class:`minimap-presence phase-${w.phase}${w.worker?" is-worker":""}${w.external?" is-external":""}`,style:{left:`${f(w.at.x)-4}px`,top:`${m(w.at.y)-4}px`,"--identity-color":So(w.id)}},w.id,!1,void 0,this)),r("span",{class:"minimap-frame",style:{left:`${f(_)}px`,top:`${m(I)}px`,width:`${o/c.scale*p}px`,height:`${i/c.scale*p}px`}},void 0,!1,void 0,this),r("span",{class:"minimap-zoom",children:[Math.round(c.scale*100),"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function uI(){let e=st.value.size,t=Jd("--selection-bar-height"),n=oe(()=>{let l=Array.from(st.value);if(l.length===0)return;Su(l),$n()},[]),o=oe(()=>{let l=Array.from(st.value);if(l.length===0)return;Ns({title:"Group",childIds:l}),$n()},[]),i=oe(()=>{let l=Array.from(st.value);for(let c=0;c<l.length;c++)for(let u=c+1;u<l.length;u++)yr(l[c],l[u],"relation");$n()},[]),s=oe(()=>{let l=Array.from(st.value);for(let c of l)Xr(c);$n()},[]);if(e===0)return null;let a=e>=2;return r("div",{class:"selection-bar",role:"toolbar","aria-label":"Selection",ref:t,children:[r("span",{class:"selection-bar-count",children:[e," node",e!==1?"s":""," selected"]},void 0,!0,void 0,this),a&&r(be,{children:[r("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),r(_e,{label:"Align left",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Align left",onClick:()=>sm("left"),children:r("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:[r("line",{x1:"2.5",y1:"2",x2:"2.5",y2:"14"},void 0,!1,void 0,this),r("rect",{x:"5",y:"3.5",width:"8",height:"3.5",rx:"1"},void 0,!1,void 0,this),r("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),r(_e,{label:"Align top",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Align top",onClick:()=>sm("top"),children:r("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:[r("line",{x1:"2",y1:"2.5",x2:"14",y2:"2.5"},void 0,!1,void 0,this),r("rect",{x:"3.5",y:"5",width:"3.5",height:"8",rx:"1"},void 0,!1,void 0,this),r("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),r(_e,{label:"Distribute horizontally",body:"Evens the gaps. A selection that cannot fit flows into a clean row instead of overlapping.",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Distribute",disabled:e<3,onClick:()=>qk(),children:r("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[r("rect",{x:"1.5",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"6.25",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),r("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),r(_e,{label:"Auto-arrange selection",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Auto-arrange",onClick:()=>Gk(),children:r(Tr,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),r(_e,{label:"Group the selection",shortcut:"G",side:"up",children:r("button",{type:"button",class:"selection-bar-action",onClick:o,children:[r("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:r("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),r(_e,{label:"Connect every pair",side:"up",children:r("button",{type:"button",class:"selection-bar-action",onClick:i,children:"Connect"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(_e,{label:"Pin to agent context",side:"up",children:r("button",{type:"button",class:"selection-bar-action is-pin",onClick:n,children:[r("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),r("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),r(_e,{label:"Delete selection",side:"up",children:r("button",{type:"button",class:"selection-bar-icon is-danger","aria-label":"Delete selection",onClick:s,children:r("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:[r("path",{d:"M2.5 4 H13.5"},void 0,!1,void 0,this),r("path",{d:"M5.5 4 V2.5 H10.5 V4"},void 0,!1,void 0,this),r("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),r(_e,{label:"Clear selection",shortcut:"Esc",side:"up",children:r("button",{type:"button",class:"selection-bar-icon",onClick:$n,"aria-label":"Clear selection",children:r(Tt,{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 up(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 dp(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 DL={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"vetoed"},BL={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"cancelled"},dI=[{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"}],FL=Object.fromEntries(dI.map((e)=>[e.id,e.hint])),HL={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 Ag(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 UL({item:e}){let t=DL[e.status]??"queued",n=e.nodeIds[0];return r("li",{class:`session-item status-${t}`,"data-work-item-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("button",{type:"button",class:"session-item-title",disabled:!n,onClick:()=>n&&$t(n),children:e.title},void 0,!1,void 0,this),e.detail&&r("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"session-item-status",children:BL[e.status]??t},void 0,!1,void 0,this),r("span",{class:"session-item-time",children:Ag(e.updatedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function pI({gate:e,now:t}){let[n,o]=E(null),i=async(l)=>{o(l),await EC(e,l),o(null)},s=e.nodeIds[0],a=up(e,t);return r("li",{class:"session-item status-awaiting session-gate","data-gate-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("button",{type:"button",class:"session-item-title",disabled:!s,onClick:()=>s&&$t(s),children:e.title},void 0,!1,void 0,this),e.detail&&r("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this),a!==null&&r("div",{class:"session-gate-ttl","data-testid":"gate-countdown",children:["auto-holds in ",dp(a)," if unanswered"]},void 0,!0,void 0,this),r("div",{class:"session-gate-actions",children:[r("button",{type:"button",class:"session-gate-approve",disabled:n!==null,onClick:()=>void i("approved"),children:n==="approved"?"Approving…":"Approve"},void 0,!1,void 0,this),r("button",{type:"button",class:"session-gate-reject",disabled:n!==null,onClick:()=>void i("rejected"),children:n==="rejected"?"Rejecting…":"Reject"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"session-item-time",children:Ag(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function fI({gate:e}){let[t,n]=E(!1);return r("li",{class:"session-item status-vetoed session-gate-held","data-gate-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("span",{class:"session-item-title",children:e.title},void 0,!1,void 0,this),r("div",{class:"session-item-detail",children:"Auto-held — no answer in time, the action did not proceed."},void 0,!1,void 0,this),r("div",{class:"session-gate-actions",children:r("button",{type:"button",class:"session-gate-reject",disabled:t,onClick:()=>{n(!0),AC(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),r("span",{class:"session-item-status",children:"held"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function jL(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 mI({gate:e}){return r("li",{class:`session-item status-${e.status}`,"data-gate-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("span",{class:"session-item-title",children:e.title},void 0,!1,void 0,this),r("div",{class:"session-item-detail",children:jL(e)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function hI(){let e=To.value,t=st.value.size,[n,o]=E(!1),i=(s)=>{o(!0),_C(s).finally(()=>o(!1))};return r("div",{class:`session-scope${e?" is-fenced":""}`,"data-testid":"session-scope",children:[r("span",{class:"session-scope-dot","aria-hidden":"true"},void 0,!1,void 0,this),e?r(be,{children:[r("span",{class:"session-scope-text",children:["Scoped to ",r("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),r("button",{type:"button",class:"session-scope-action",disabled:n,onClick:()=>i(null),children:"Clear"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r("span",{class:"session-scope-text",children:"Unscoped — the agent may write anywhere"},void 0,!1,void 0,this),r(_e,{label:t===0?"Select nodes on the canvas first":"Fence the agent to the selected nodes",align:"end",children:r("button",{type:"button",class:"session-scope-action",disabled:n||t===0,onClick:()=>i([...st.value]),children:["Fence to selection",t>0?` (${t})`:""]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ZL(e){if(e==="browser")return"you";return en.value.find((n)=>n.sessionId===e||n.source===e)?.label??e}function WL({entry:e}){let t=Wl.value.has(e.id);return r("li",{class:`session-timeline-row tone-${HL[e.kind]??"muted"}`,children:[r("span",{class:"session-timeline-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-timeline-main",children:[r("div",{class:"session-timeline-head",children:[r("span",{class:"session-timeline-label",children:e.label},void 0,!1,void 0,this),e.who&&r("span",{class:"session-timeline-who",style:{"--identity-color":So(e.who)},children:ZL(e.who)},void 0,!1,void 0,this),r("span",{class:"session-item-time",children:Ag(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"session-timeline-body",children:e.body},void 0,!1,void 0,this),e.undoable&&!t&&r("button",{type:"button",class:"session-timeline-undo","data-testid":"timeline-undo",onClick:()=>void rg(e),children:[r(bm,{size:14},void 0,!1,void 0,this)," undo this edit"]},void 0,!0,void 0,this),t&&r("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 gI(){let e=Co.value,t=nr();if(!eo.value&&e.length===0)return null;return r("aside",{class:"session-panel","aria-label":"Agent controls",children:[r("header",{class:"session-panel-header",children:[r("span",{class:"session-panel-title",children:"Agent controls"},void 0,!1,void 0,this),r("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),r("button",{type:"button",class:"session-collapse","aria-label":"Collapse agent controls",onClick:()=>eo.value=!1,disabled:e.length>0,children:r(oi,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(hI,{},void 0,!1,void 0,this),r("div",{class:"session-panel-scroll",children:[r("ul",{class:"session-list","aria-label":"Approvals",children:[e.map((n)=>r(pI,{gate:n,now:t},n.id,!1,void 0,this)),os.value.map((n)=>r(fI,{gate:n},n.id,!1,void 0,this)),og.value.map((n)=>r(mI,{gate:n},n.id,!1,void 0,this))]},void 0,!0,void 0,this),pa.value.map((n)=>r("div",{class:"session-item",children:[r("span",{class:"session-item-main",children:n.label},void 0,!1,void 0,this),r("button",{type:"button",class:"session-end",onClick:()=>void ql(n),children:"End attachment"},void 0,!1,void 0,this)]},n.sessionId,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function yI(){q(()=>()=>{eo.value=!1},[]);let e=mi.value,t=SC.value,n=Co.value,o=os.value,i=og.value,s=IC.value,[a,l]=E(!1),[c,u]=E(null),d=nr();if(q(()=>{yi()},[]),!(eo.value||n.length>0))return r("aside",{class:"session-panel is-collapsed","aria-label":"Session (collapsed)",children:[r("button",{type:"button",class:"session-collapse",onClick:()=>{eo.value=!0},"aria-label":"Expand session panel",children:"‹"},void 0,!1,void 0,this),e&&r("span",{class:`session-collapsed-live phase-${e.phase}`,"aria-label":`Session live: ${pi(e)}`,children:[r("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this),r("span",{class:"session-collapsed-label",children:"Session"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("aside",{class:"session-panel","aria-label":"Session",children:[r("header",{class:"session-panel-header",children:[r("span",{class:"session-panel-title",children:"Session"},void 0,!1,void 0,this),e&&r(_e,{label:pi(e),tapToOpen:!0,children:r("span",{class:`session-live phase-${e.phase}`,children:[r("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),e&&r(_e,{label:"End this session",body:"A receipt and a snapshot of the board follow.",align:"end",children:r("button",{type:"button",class:"session-end",onClick:()=>void ql(e),children:"End"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",class:"session-collapse",onClick:()=>{eo.value=!1},"aria-label":"Collapse session panel",children:r(oi,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(hI,{},void 0,!1,void 0,this),(()=>{let f=s.find((m)=>m.undoable&&!Wl.value.has(m.id));if(!f)return null;return r("div",{class:"session-undo-row","data-testid":"session-undo-row",children:[r("span",{class:"session-undo-text",children:["Agent edit on top: ",f.body]},void 0,!0,void 0,this),r("button",{type:"button",class:"session-undo-btn",onClick:()=>void rg(f),children:[r(bm,{size:14},void 0,!1,void 0,this)," Undo"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)})(),r("div",{class:"session-panel-body",children:[r("section",{class:"session-section",children:(()=>{let f=t.filter((C)=>C.status==="in-progress"||C.status==="todo").length,m=t.filter((C)=>C.status!=="cancelled"),h=m.filter((C)=>C.status==="done").length,g=t.length-m.length,v=n.length>0,b=a||v,x=f>0?`${f} running`:m.length>0?`${h}/${m.length} done${g>0?` · ${g} cancelled`:""}`:t.length>0?`${t.length} cancelled`:"none yet";return r(be,{children:[r("button",{type:"button",class:"session-section-toggle","aria-expanded":b,"data-testid":"work-items-toggle",onClick:()=>l((C)=>!C),children:[r("span",{class:"session-section-title",children:"Work items"},void 0,!1,void 0,this),r("span",{class:"session-work-summary",children:[f>0&&r("span",{class:"session-work-dot","aria-hidden":"true"},void 0,!1,void 0,this),x]},void 0,!0,void 0,this),r("span",{class:`session-section-chevron${b?" is-open":""}`,"aria-hidden":"true",children:r(oi,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b&&(n.length===0&&o.length===0&&i.length===0&&t.length===0?r("div",{class:"session-empty",children:"No work items yet — the agent's tasks and gates appear here."},void 0,!1,void 0,this):r("ul",{class:"session-list","aria-live":"polite","aria-label":"Work items and gates",children:[n.map((C)=>r(pI,{gate:C,now:d},C.id,!1,void 0,this)),o.map((C)=>r(fI,{gate:C},C.id,!1,void 0,this)),i.map((C)=>r(mI,{gate:C},C.id,!1,void 0,this)),t.map((C)=>r(UL,{item:C},C.id,!1,void 0,this))]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)})()},void 0,!1,void 0,this),r("section",{class:"session-section",children:[r("h3",{class:"session-section-title",children:"Timeline"},void 0,!1,void 0,this),r("div",{class:"session-timeline-filters",role:"group","aria-label":"Filter timeline",children:dI.map((f)=>r("button",{type:"button",class:`activity-filter${rs.value===f.id?" is-active":""}`,"aria-pressed":rs.value===f.id,onMouseEnter:()=>u(f.id),onMouseLeave:()=>u((m)=>m===f.id?null:m),onFocus:()=>u(f.id),onBlur:()=>u((m)=>m===f.id?null:m),onClick:()=>{rs.value=f.id},children:f.label},f.id,!1,void 0,this))},void 0,!1,void 0,this),r("div",{class:"session-timeline-hint","data-testid":"timeline-filter-hint",children:FL[c??rs.value]},void 0,!1,void 0,this),s.length===0?r("div",{class:"session-empty",children:rs.value==="all"?"Nothing recorded yet.":"Nothing of this kind yet."},void 0,!1,void 0,this):r("ul",{class:"session-list session-timeline","aria-live":"polite","aria-label":"Timeline",children:s.map((f)=>r(WL,{entry:f},f.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Rg(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 vI=(e)=>e.map((t)=>t.title).join(", ");function bI(e){let t=new Date(e);return Number.isNaN(t.getTime())?"":`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function qL({context:e,label:t,snapshotId:n}){let[o,i]=E(!1),[s,a]=E([]),[l,c]=E(!1),[u,d]=E(null),[p,f]=E(!1),m=e.edited.length>0&&e.edited.every((x)=>s.includes(x.id))?"undone":l?"kept":null;q(()=>{a([]),c(!1),d(null)},[e]);let h=async(x)=>{if(!n||p)return;f(!0);try{let C=await NC(n,x.filter((y)=>!s.includes(y.id)));return a((y)=>[...y,...C.restored]),C}finally{f(!1)}},v=[{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((x)=>e[x.key].length>0);if(v.length===0&&e.changedSinceRead.length===0)return null;let b=Fn.value?.kind==="receipt";return r("div",{class:"session-receipt-context","data-testid":"session-receipt-context",children:[e.changedSinceRead.length>0&&r("div",{class:"session-receipt-warn",children:[r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:r("path",{d:gi.warn},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{children:[vI(e.changedSinceRead)," changed after ",t," read"," ",e.changedSinceRead.length===1?"it":"them","."]},void 0,!0,void 0,this),r("button",{type:"button",class:"session-receipt-mini",disabled:o,onClick:()=>{let x=e.changedSinceRead.length===1?"it":"them";fa(`${e.changedSinceRead.map((C)=>`“${C.title}”`).join(", ")} changed after you read ${x} — read ${x} again before relying on ${x}.`).then((C)=>i(C))},children:o?"Told":`Tell ${t}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v.map((x)=>r("div",{class:"session-receipt-context-row","data-row":x.key,children:[r("div",{class:"session-receipt-context-head",children:[x.glyph==="pin"?r(uo,{},void 0,!1,void 0,this):r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:r("path",{d:gi[x.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"session-receipt-context-name",children:x.name},void 0,!1,void 0,this),r("span",{class:"session-receipt-context-count",children:e[x.key].length},void 0,!1,void 0,this),x.key==="pinned"&&r("button",{type:"button",class:"session-receipt-mini",disabled:e.pinned.some((C)=>C.boardId&&C.boardId!==se.value),onClick:()=>Kk(e.pinned.map((C)=>C.id)),children:"Unpin"},void 0,!1,void 0,this),x.key==="edited"&&n&&r("button",{type:"button",class:"session-receipt-mini",disabled:m!==null||p||e.edited.some((C)=>C.boardId&&C.boardId!==se.value),onClick:()=>{h(e.edited).then((C)=>{if(C?.ok)c(!0)})},children:m==="undone"?"✓ Undone":m==="kept"?"Kept your edits":"Undo"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x.key==="edited"&&m&&r("div",{class:"session-receipt-context-items",children:m==="undone"?"every card restored":"cards you edited since were left alone"},void 0,!1,void 0,this),x.key==="edited"?r("ul",{class:"session-receipt-edits",children:e.edited.map((C)=>r(KL,{node:C,canUndo:n!==null,undoing:p,open:u===or(C),onToggle:()=>d(u===or(C)?null:or(C)),undone:s.includes(C.id),onUndo:()=>void h([C])},or(C),!1,void 0,this))},void 0,!1,void 0,this):r("div",{class:"session-receipt-context-items",children:x.key==="pinned"?e.pinned.map((C)=>C.reason?`${C.title} — “${C.reason}”`:C.title).join("; "):vI(e[x.key])},void 0,!1,void 0,this)]},x.key,!0,void 0,this)),r("button",{type:"button",role:"switch","aria-checked":b,class:`session-receipt-lens${b?" is-on":""}`,onClick:()=>Gl(!b),children:[r("span",{class:"session-receipt-lens-track","aria-hidden":"true",children:r("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 GL(e,t){let n=(d)=>d.match(/\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu)??[],o=n(e),i=n(t),s=Array.from({length:o.length+1},()=>new Uint16Array(i.length+1));for(let d=o.length-1;d>=0;d--)for(let p=i.length-1;p>=0;p--)s[d][p]=o[d]===i[p]?s[d+1][p+1]+1:Math.max(s[d+1][p],s[d][p+1]);let a=[],l=[],c=0,u=0;while(c<o.length||u<i.length)if(c<o.length&&u<i.length&&o[c]===i[u])a.push({text:o[c++],changed:!1}),l.push({text:i[u++],changed:!1});else if(c<o.length&&(u===i.length||s[c+1][u]>=s[c][u+1]))a.push({text:o[c++],changed:!0});else l.push({text:i[u++],changed:!0});return[a,l]}function KL({node:e,canUndo:t,undoing:n,open:o,onToggle:i,undone:s,onUndo:a}){let l=!e.boardId||e.boardId===se.value,c=l?H.value.get(e.id):void 0,u=Ge.value.find((m)=>m.id===e.boardId),d=Ke(()=>o?GL(e.before??"",e.after??""):[],[o,e.before,e.after]),p=D(null);Me(()=>{for(let m of p.current?.querySelectorAll(".session-receipt-diff-text")??[]){let h=m.querySelector("del, ins");if(h)m.scrollTop=h.getBoundingClientRect().top-m.getBoundingClientRect().top-24}},[d]);let f=c?.lastEditedBy?.actor==="human";return r("li",{class:"session-receipt-edit",children:[r("span",{class:"session-receipt-edit-line",children:[r("span",{children:[e.title,e.change?r("span",{class:"session-receipt-edit-change",children:[" — ",e.change]},void 0,!0,void 0,this):null]},void 0,!0,void 0,this),e.before!==void 0&&r("button",{type:"button",class:"session-receipt-link","aria-expanded":o,onClick:i,children:o?"Hide change":"See change"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&r("span",{ref:p,class:"session-receipt-diff-pair",children:[d.map((m,h)=>r("span",{class:"session-receipt-diff-side",children:[r("span",{class:"session-receipt-diff-label",children:h===0?"Before":"After"},void 0,!1,void 0,this),r("span",{class:"session-receipt-diff-text",children:m.length?m.map(({text:g,changed:v},b)=>g==="…"&&(b===0||b===m.length-1)?r("span",{class:"session-receipt-diff-cut",children:g},b,!1,void 0,this):v?h===0?r("del",{children:g},b,!1,void 0,this):r("ins",{children:g},b,!1,void 0,this):g):"Empty"},void 0,!1,void 0,this)]},h,!0,void 0,this)),t&&r("span",{class:"session-receipt-undo",children:[c?r("button",{type:"button",class:"session-receipt-mini",disabled:s||f||n,onClick:a,children:s?"✓ Undone":f?"You edited it since":"Undo this card"},void 0,!1,void 0,this):u&&!l?r("button",{type:"button",class:"session-receipt-mini",onClick:()=>void Mn(u.id),children:["Open ",u.name," to undo"]},void 0,!0,void 0,this):r("span",{class:"session-receipt-edit-change",children:"Card no longer on this board"},void 0,!1,void 0,this),r("span",{class:"session-receipt-edit-change",children:c?s?"the card shows Before again":f?"undo would lose your edit":e.before?.includes("…")||e.after?.includes("…")?"undoes the whole card":"puts back the text from before":u&&!l?`it is on ${u.name}`:""},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 xI({onOpenSnapshots:e}){let t=ns.value,[n,o]=E(null),[i,s]=E(!1);if(q(()=>o(null),[t]),!xt.value||!t)return null;let a=t.snapshot?.boardId===se.value,l=Ge.value.find((f)=>f.id===t.snapshot?.boardId),c=async()=>{if(!t.snapshot||!a)return;s(!0);try{let f=await Gt(`/api/canvas/snapshots/${encodeURIComponent(t.snapshot.id)}/diff`,{headers:{"x-pmx-workbench":"1"}});if(f.ok){let m=await f.json();o(Rg(m.diff)??{added:0,removed:0,modified:0})}}finally{s(!1)}},u=bI(t.endedAt),d=t.startedAt?bI(t.startedAt):"",p=t.endedBy==="human"?"ended by you":t.endedBy==="idle-timeout"?"ended on idle timeout":t.endedBy==="agent"?"ended by the agent":"";return r("div",{class:"session-receipt","data-testid":"session-receipt",role:"status",children:[r("div",{class:"session-receipt-head",children:[r("span",{class:"session-receipt-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"session-receipt-title",children:t.sessions>1?`${t.sessions} sessions ended${u?` · ${u}`:""}`:`What ${t.labels[0]} did`},void 0,!1,void 0,this),r("button",{type:"button",class:"session-receipt-close",onClick:Hd,"aria-label":"Dismiss receipt",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.sessions>1?r("div",{class:"session-receipt-who",children:t.labels.join(", ")},void 0,!1,void 0,this):r("div",{class:"session-receipt-who","data-testid":"session-receipt-span",children:[`This session · ${d?`${d}–`:""}${u}`,t.snapshot?"saved as a snapshot":"",p].filter(Boolean).join(" · ")},void 0,!1,void 0,this),r("div",{class:"session-receipt-tiles",children:[r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Items"},void 0,!1,void 0,this),r("span",{class:"session-receipt-tile-value",children:t.counts.items},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Done"},void 0,!1,void 0,this),r("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&&r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Cancelled"},void 0,!1,void 0,this),r("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&&r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Rejected"},void 0,!1,void 0,this),r("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&&r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Held"},void 0,!1,void 0,this),r("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),r(qL,{context:t.context,label:t.labels.join(", "),snapshotId:t.sessions===1?t.snapshot?.id??null:null},void 0,!1,void 0,this),r("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&&r("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),r("div",{class:"session-receipt-actions",children:[t.snapshot&&r("button",{type:"button",class:"session-receipt-primary",disabled:i||!a&&!l,onClick:()=>a?void c():l&&void Mn(l.id),children:!a&&l?`Open ${l.name} to compare`:i?"Comparing…":"View diff"},void 0,!1,void 0,this),r(_e,{label:"Open the History drawer",body:"Saved boards and past sessions.",side:"up",align:"end",children:r("button",{type:"button",class:"session-receipt-secondary",onClick:e,children:"History"},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 VL=[{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:Ft("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:Ft("0"),desc:"Reset viewport to origin"},{keys:`${Ft("+")} / ${Ft("−")}`,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:wl?"Delete / ⌫":"Delete / Backspace",desc:"Delete the selection (or the focused node)"},{keys:wl?"⌘Z / ⇧⌘Z":"Ctrl+Z / Ctrl+Y",desc:"Undo / redo — agent edits included"},{keys:"Esc",desc:"Close overlay first, then clear selection and view filters"}]},{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 wI({onClose:e}){return r("div",{class:"shortcut-overlay-backdrop",onMouseDown:e,children:r("div",{class:"shortcut-overlay",onMouseDown:(t)=>t.stopPropagation(),children:[r("div",{class:"shortcut-overlay-header",children:[r("span",{class:"shortcut-overlay-title",children:"Keyboard Shortcuts"},void 0,!1,void 0,this),r("span",{class:"shortcut-overlay-hint",children:["Press ",r("kbd",{children:"?"},void 0,!1,void 0,this)," or ",r("kbd",{children:"Esc"},void 0,!1,void 0,this)," to close"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"shortcut-overlay-body",children:VL.map((t)=>r("div",{class:"shortcut-group",children:[r("div",{class:"shortcut-group-title",children:t.title},void 0,!1,void 0,this),t.shortcuts.map((n)=>r("div",{class:"shortcut-row",children:[r("kbd",{class:"shortcut-keys",children:n.keys},void 0,!1,void 0,this),r("span",{class:"shortcut-desc",children:tt()&&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 kI="Before session · ";function SI(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 pp(e){if(!e.startsWith(kI))return null;let t=e.slice(kI.length),n=t.lastIndexOf(" · ");return n>0?t.slice(0,n):t}function _I({open:e,onClose:t,anchorRef:n}){let[o,i]=E([]),[s,a]=E(!1),[l,c]=E(!1),[u,d]=E(null),[p,f]=E(""),[m,h]=E(null),[g,v]=E({}),b=D(null),x=D(null);q(()=>{if(!e)return;a(!0),xk().then((w)=>{i(w),a(!1)})},[e]),q(()=>{if(e)setTimeout(()=>x.current?.focus(),50)},[e]),q(()=>{if(!e)return;let w=(P)=>{let L=b.current,N=n.current;if(L&&!L.contains(P.target)&&N&&!N.contains(P.target))t()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[e,t]),q(()=>{if(!e)return;let w=(P)=>{if(P.key==="Escape")t()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,t]);let C=oe(async()=>{let w=p.trim();if(!w)return;c(!0);let P=await wk(w);if(c(!1),P.ok&&P.snapshot)i((L)=>[P.snapshot,...L]),f("")},[p]),y=oe(async(w)=>{h(null),d(w);let P=await kk(w);if(d(null),P.ok)t()},[t]),k=oe(async(w)=>{if((await Sk(w)).ok)i((L)=>L.filter((N)=>N.id!==w));h(null)},[]),_=oe(async(w)=>{v((L)=>({...L,[w]:"loading"}));let P=await de("snapshotDiff",`/api/canvas/snapshots/${encodeURIComponent(w)}/diff`,{});v((L)=>({...L,[w]:Rg(P.diff)??{added:0,removed:0,modified:0}}))},[]);if(!e)return null;let I=(w,P)=>m?.id===w.id?r(be,{children:[r("button",{type:"button",class:`snapshot-action-btn ${m.action==="delete"?"snapshot-action-confirm":"snapshot-action-restore"}`,onClick:()=>m.action==="delete"?k(w.id):y(w.id),disabled:u!==null,children:m.action==="delete"?"Delete":u===w.id?"Restoring…":"Confirm"},void 0,!1,void 0,this),r("button",{type:"button",class:"snapshot-action-btn",onClick:()=>h(null),disabled:u!==null,children:"Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r(_e,{label:"Restore this snapshot",body:tt()?"Replaces the current canvas.":"Replaces the current canvas (undoable).",align:"end",children:r("button",{type:"button",class:"snapshot-action-btn snapshot-action-restore",onClick:()=>h({id:w.id,action:"restore"}),disabled:u!==null,children:u===w.id?"Restoring…":P},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Delete this snapshot",align:"end",children:r("button",{type:"button",class:"snapshot-action-btn snapshot-action-delete",onClick:()=>h({id:w.id,action:"delete"}),"aria-label":"Delete snapshot",disabled:u!==null,children:r(Tt,{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);return r("div",{ref:b,class:"snapshot-panel","data-testid":"history-drawer",role:"dialog","aria-label":"History",children:[r("div",{class:"snapshot-panel-header",children:[r("span",{class:"snapshot-panel-title",children:"History"},void 0,!1,void 0,this),r("span",{class:"snapshot-panel-sub",children:"snapshots + sessions"},void 0,!1,void 0,this),r("span",{class:"snapshot-panel-spacer"},void 0,!1,void 0,this),r("button",{type:"button",class:"snapshot-panel-close",onClick:t,"aria-label":"Close history",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-save-form",children:[r("input",{ref:x,type:"text",class:"snapshot-name-input",value:p,onInput:(w)=>f(w.target.value),onKeyDown:(w)=>{if(w.key==="Enter")C()},placeholder:"Save a snapshot as…","aria-label":"Snapshot name",maxLength:80,disabled:l},void 0,!1,void 0,this),r("button",{type:"button",class:"snapshot-save-btn",onClick:C,disabled:!p.trim()||l,children:l?"…":"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-restore-note",children:tt()?"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),r("div",{class:"snapshot-list",children:[s&&r("div",{class:"snapshot-empty",children:"Loading…"},void 0,!1,void 0,this),!s&&o.length===0&&r("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)=>pp(w.name)===null),...o.some((w)=>pp(w.name)!==null)?[{id:"__sessions-header__"}]:[],...o.filter((w)=>pp(w.name)!==null)].map((w)=>{if(w.id==="__sessions-header__")return r("div",{class:"snapshot-section-header","data-testid":"history-sessions-header",children:"Sessions"},w.id,!1,void 0,this);let P=pp(w.name),L=g[w.id];if(P!==null)return r("div",{class:"snapshot-item is-session","data-testid":"history-session",children:[r("div",{class:"snapshot-item-head",children:[r("span",{class:"snapshot-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"snapshot-item-name",children:["Agent session — ",P]},void 0,!0,void 0,this),r("span",{class:"snapshot-item-time",children:SI(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-meta",children:["snapshot at session start · ",w.nodeCount," node",w.nodeCount!==1?"s":"",L&&L!=="loading"&&r("span",{class:"snapshot-item-diff",children:[" ","· since: ",L.added," added · ",L.removed," removed · ",L.modified," modified"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-actions is-session",children:[r("button",{type:"button",class:"snapshot-action-btn snapshot-action-diff",disabled:L==="loading",onClick:()=>void _(w.id),children:L==="loading"?"Comparing…":"View diff"},void 0,!1,void 0,this),I(w,"Restore pre-state")]},void 0,!0,void 0,this)]},w.id,!0,void 0,this);return r("div",{class:"snapshot-item","data-testid":"history-snapshot",children:[r("div",{class:"snapshot-item-head",children:[r("span",{class:"snapshot-item-glyph","aria-hidden":"true",children:"◫"},void 0,!1,void 0,this),r("span",{class:"snapshot-item-name",children:w.name},void 0,!1,void 0,this),r("span",{class:"snapshot-item-time",children:SI(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-meta",children:[w.nodeCount," node",w.nodeCount!==1?"s":"",w.edgeCount>0?` · ${w.edgeCount} edge${w.edgeCount!==1?"s":""}`:""," · ",Yd(w.createdAt)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-actions",children:I(w,"Restore")},void 0,!1,void 0,this)]},w.id,!0,void 0,this)})]},void 0,!0,void 0,this),r("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 XL=8;function CI({fallbackName:e}){let[t,n]=E(!1),o=D(null),i=D(null),s=D(null);Me(()=>{if(!t)return;let p=(m)=>{if(m.target instanceof Node&&!o.current?.contains(m.target)&&!s.current?.contains(m.target))n(!1)},f=(m)=>{if(m.key==="Escape")m.stopPropagation(),n(!1),i.current?.focus()};return document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",f,!0),()=>{document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",f,!0)}},[t]);let a=Yn(),l=!io.value?e:a&&!ut.value?a.name:"Home",c=Ge.value.filter((p)=>ut.value||p.id!==se.value).slice(0,XL),u=i.current?.getBoundingClientRect(),d=(p)=>{n(!1),Mn(p)};return r("span",{class:"board-switcher",ref:o,children:[r("button",{ref:i,type:"button",class:"top-bar-title board-switcher-button","aria-haspopup":"menu","aria-expanded":t,"aria-label":`Board: ${l}. Switch board`,onClick:()=>n((p)=>!p),children:[r("span",{class:"board-switcher-name",children:l},void 0,!1,void 0,this),r("span",{class:"board-switcher-caret","aria-hidden":"true",children:r(Us,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&u&&r(Zs,{children:r("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:[c.length>0&&r("div",{class:"board-switcher-heading",children:"Recent boards"},void 0,!1,void 0,this),r("div",{class:"board-switcher-recents",children:c.map((p)=>r("div",{class:"board-switcher-row",children:[r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>d(p.id),children:[r("span",{class:"board-switcher-icon","aria-hidden":"true",children:r(Mu,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"board-switcher-item-copy",children:[r("span",{class:"board-switcher-item-name",children:p.name},void 0,!1,void 0,this),r("span",{class:"board-switcher-item-folder",children:p.folder?.split("/").join(" / ")||"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"board-switcher-item-meta",children:[p.nodeCount," ",p.nodeCount===1?"node":"nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(ho,{board:p},void 0,!1,void 0,this)]},p.id,!0,void 0,this))},void 0,!1,void 0,this),r("div",{class:"board-switcher-actions",children:[r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>{n(!1),Ig()},children:[r("span",{class:"board-switcher-icon","aria-hidden":"true",children:r(lS,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),"New board…"]},void 0,!0,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>d(null),children:[r("span",{class:"board-switcher-icon","aria-hidden":"true",children:r(Tr,{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 TI=3,II={"waiting-approval":0,thinking:1,tooling:2,idle:3};function JL(){let[e,t]=E(null),n=D(null);Me(()=>{if(!e)return;let d=(m)=>{if(!n.current?.contains(m.target)&&!e.button.contains(m.target))t(null)},p=(m)=>{if(m.key==="Escape"&&!m.defaultPrevented)m.preventDefault(),t(null),e.button.focus({preventScroll:!0})},f=()=>t(null);return document.addEventListener("pointerdown",d,!0),document.addEventListener("keydown",p),window.addEventListener("resize",f),()=>{document.removeEventListener("pointerdown",d,!0),document.removeEventListener("keydown",p),window.removeEventListener("resize",f)}},[e]);let o=pa.value;if(q(()=>{if(e&&!e.button.isConnected)t(null)},[o,e]),!xt.value||o.length===0)return null;let i=o.filter((d)=>!d.parentAgentId||!o.some((p)=>p.sessionId!==d.sessionId&&!p.parentAgentId&&(p.sessionId===d.parentAgentId||p.source===d.parentAgentId))),s=[...i].sort((d,p)=>(II[d.phase]??4)-(II[p.phase]??4)),a=s.slice(0,TI),l=s.slice(TI),c=i.reduce((d,p)=>(d[p.phase]=(d[p.phase]??0)+1,d),{}),u=[c["waiting-approval"]&&`${c["waiting-approval"]} waiting on approval`,c.thinking&&`${c.thinking} thinking`,c.tooling&&`${c.tooling} running tools`,c.idle&&`${c.idle} idle`].filter(Boolean).join(", ");return r(be,{children:[r("span",{class:"agent-chips",children:a.map((d)=>{let p=d.parentAgentId?0:en.value.filter((f)=>f.parentAgentId!=null&&(f.parentAgentId===d.sessionId||f.parentAgentId===d.source)).length;return r(_e,{label:`Agent session — ${d.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:r("span",{class:`agent-chip phase-${d.phase}`,"data-phase":d.phase,style:{"--identity-color":So(d.sessionId)},children:[r("button",{type:"button",class:"agent-chip-initial","aria-label":`${d.label} session details`,"aria-expanded":e?.id===d.sessionId,"aria-haspopup":"dialog",onClick:(f)=>{f.stopPropagation(),t(e?.id===d.sessionId?null:{id:d.sessionId,button:f.currentTarget})},children:[Nd(d.label),r("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"agent-chip-label",children:pi(d)},void 0,!1,void 0,this),r("span",{class:"agent-chip-who hud-collapsible-text",children:d.label},void 0,!1,void 0,this),r(EI,{session:d},void 0,!1,void 0,this),p>0&&r("span",{class:"agent-chip-workers",children:["+",p," worker",p===1?"":"s"]},void 0,!0,void 0,this),r("button",{type:"button",class:"agent-chip-end","aria-label":`End ${d.label} session`,onClick:(f)=>{f.stopPropagation(),ql({source:d.source,agentId:d.agentId})},children:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},d.sessionId,!1,void 0,this)})},void 0,!1,void 0,this),l.length>0&&r(_e,{label:`${i.length} agent sessions attached`,tapToOpen:!0,body:`${i.length} agents on this board — ${u}. The most active wear their own chips; the rest are here, and idle agents' cursors leave the board until they work again.`,children:r("span",{class:"agent-chip agent-chip-more","data-testid":"agent-chip-more",children:["+",l.length," · ",i.length," agents"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),e&&a.filter((d)=>d.sessionId===e.id).map((d)=>r(Zs,{children:r("div",{ref:n,class:`agent-session-popover phase-${d.phase}`,role:"dialog","aria-label":`${d.label} session details`,style:{right:`${Math.max(12,window.innerWidth-e.button.getBoundingClientRect().right)}px`,top:`${e.button.getBoundingClientRect().bottom+8}px`},children:[r("div",{class:"agent-session-popover-head",children:[r("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("strong",{children:[d.label," · ",pi(d)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(EI,{session:d,popover:!0},void 0,!1,void 0,this),r("button",{type:"button",class:"session-receipt-link",onClick:()=>{eo.value=!0,t(null)},children:"Open session panel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},d.sessionId,!1,void 0,this))]},void 0,!0,void 0,this)}function EI({session:e,popover:t=!1}){let n=e.session,o=n?[["read",n.read.length],["created",n.created.length],["edited",n.edited.length],["pinned",n.pinned.length]].filter(([,l])=>l>0):[],i=Fn.value,s=i?.kind==="live"&&i.sessionId===e.sessionId;if(o.length===0&&!s&&!t)return null;let a=o.map(([l,c])=>`${c} ${l}`).join(" · ")||"nothing yet";if(t)return r(be,{children:[r("span",{class:"agent-session-counts",children:a},void 0,!1,void 0,this),r("button",{type:"button",role:"switch","aria-checked":s,class:`session-receipt-lens${s?" is-on":""}`,onClick:()=>Gl(!s,{sessionId:e.sessionId}),children:[r("span",{class:"session-receipt-lens-track","aria-hidden":"true",children:r("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);return r("button",{type:"button",class:`agent-chip-touches${s?" is-on":""}`,"aria-pressed":s,"aria-label":`This session: ${o.map(([l,c])=>`${c} ${l}`).join(", ")||"nothing yet"}. ${s?"Show all cards":"Dim untouched cards"}`,onClick:(l)=>{l.stopPropagation(),Gl(!s,{sessionId:e.sessionId})},children:a},void 0,!1,void 0,this)}function YL(){let e=Co.value.length,t=e>0,n=nr(t?1000:0);if(!t)return null;let o=Co.value.map((i)=>up(i,n)).filter((i)=>i!==null).sort((i,s)=>i-s)[0];return r(_e,{label:"Approval gates waiting on you",body:"Open agent controls to approve or reject. Unanswered gates auto-hold when the countdown runs out, even with the session beta off.",children:r("button",{type:"button",class:"gate-badge",onClick:()=>eo.value=!0,children:[e," gate",e===1?"":"s",o!==void 0&&` · ${dp(o)}`]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function QL(){let[e,t]=E(!1);if(!xt.value||mi.value)return null;return r(_e,{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:r("button",{type:"button",class:"start-session-btn","aria-label":"Start agent session beta",disabled:e,onClick:()=>{t(!0),vi().finally(()=>t(!1))},children:[r("span",{class:"start-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"start-session-label",children:"Start agent session"},void 0,!1,void 0,this),r("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 AI(){let e=D(null);Me(()=>{let g=e.current,v=g?.querySelector(".top-bar-right");if(!g||!v)return;let b=()=>{let y=g.querySelector('.top-bar-more [aria-expanded="true"]');g.classList.remove("is-folded","is-compact");let k=()=>v.getBoundingClientRect().right>g.getBoundingClientRect().right-14;if(y||k())g.classList.add("is-folded");if(k())g.classList.add("is-compact")},x=new ResizeObserver(b);x.observe(g);let C=new MutationObserver(b);return C.observe(g,{childList:!0,characterData:!0,subtree:!0}),b(),()=>{x.disconnect(),C.disconnect()}},[]);let t=ao.value,n=cn.value,o=Te.value,i=H.value.size,s=et.value.size,a=Os.value,l=Array.from(H.value.values()).filter((g)=>g.type==="trace").length,[c,u]=E("");q(()=>{let g=!1;return Gt("/health").then((v)=>v.ok?v.json():null).then((v)=>{if(g||typeof v?.workspace!=="string"||!v.workspace)return;let b=v.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop();if(b)u(b)}).catch(()=>{}),()=>{g=!0}},[]);let d=xg.value,p=d??(t==="connected"&&!n?"syncing":t),f=Yn(),m=n?[`${i} node${i!==1?"s":""}`,...s>0?[`${s} edge${s!==1?"s":""}`]:[],...l>0?[`${l} trace${l!==1?"s":""}`]:a?["trace armed"]:[]].join(" · "):"Syncing canvas…",h=()=>{let g=Jt();Fs(g.width,g.height)};return r("div",{class:"top-bar",ref:e,children:[r(_e,{label:`Canvas status: ${p}`,tapToOpen:!0,body:"Live updates stream in over SSE; amber means reconnecting.",align:"start",children:r("span",{class:`connection-dot ${d??t}`,"aria-label":`Canvas status: ${p}`},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(CI,{fallbackName:c||"PMX Canvas"},void 0,!1,void 0,this),f&&!ut.value&&r(ho,{board:f},void 0,!1,void 0,this),r("span",{class:"top-bar-meta hud-collapsible-text",children:xr.value?xr.value.slice(0,12):"…"},void 0,!1,void 0,this),!ut.value&&r("span",{class:"top-bar-meta hud-collapsible-text",children:m},void 0,!1,void 0,this),r("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),r("div",{class:"top-bar-right",children:[r(JL,{},void 0,!1,void 0,this),r(YL,{},void 0,!1,void 0,this),r(dT,{},void 0,!1,void 0,this),r(YT,{},void 0,!1,void 0,this),!tt()&&r(QL,{},void 0,!1,void 0,this),!ut.value&&r(be,{children:[r("div",{class:"top-bar-sep"},void 0,!1,void 0,this),r("div",{class:"top-bar-actions",children:[se.value&&r(_e,{label:"Export board",body:"One HTML file of this board that anyone can open, no install needed.",children:r("button",{type:"button",class:"present-button",onClick:()=>{cs.value=!0},children:"Export"},void 0,!1,void 0,this)},void 0,!1,void 0,this),se.value&&r(_e,{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:r("button",{type:"button",class:"present-button",onClick:()=>{fl()},children:"Present"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Zoom out",shortcut:Ft("−"),children:r("button",{type:"button",class:"top-bar-btn",onClick:()=>ti(0.8),"aria-label":"Zoom out",children:r(mS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Reset zoom",shortcut:Ft("0"),children:r("button",{type:"button",class:"top-bar-zoom-label",onClick:()=>_r({x:0,y:0,scale:1},250),"aria-label":"Reset view",children:[Math.round(o.scale*100),"%"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Zoom in",shortcut:Ft("+"),children:r("button",{type:"button",class:"top-bar-btn",onClick:()=>ti(1.25),"aria-label":"Zoom in",children:r(fS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Fit all",shortcut:"F",align:"end",children:r("button",{type:"button",class:"top-bar-btn",onClick:h,"aria-label":"Fit canvas",children:r(Pu,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(eO,{boardOpen:!!se.value,onFit:h},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 eO({boardOpen:e,onFit:t}){let[n,o]=E(!1),i=D(null),s=D(null);Me(()=>{if(!n)return;let l=()=>[...i.current?.querySelectorAll('[role="menuitem"]')??[]];l()[0]?.focus();let c=(d)=>{if(d.key==="Escape")o(!1),s.current?.focus();else if(d.key==="ArrowDown"||d.key==="ArrowUp"){d.preventDefault();let p=l(),f=p.indexOf(document.activeElement),m=d.key==="ArrowDown"?f+1:f-1;p[(m+p.length)%p.length]?.focus()}},u=(d)=>{if(i.current&&!i.current.contains(d.target))o(!1)};return window.addEventListener("keydown",c),window.addEventListener("pointerdown",u),()=>{window.removeEventListener("keydown",c),window.removeEventListener("pointerdown",u)}},[n]);let a=(l)=>()=>{o(!1),l()};return r("div",{class:"top-bar-more",ref:i,children:[r("button",{ref:s,type:"button",class:"top-bar-btn","aria-label":"More: export, present, zoom, fit","aria-haspopup":"menu","aria-expanded":n,onClick:()=>o(!n),children:"⋯"},void 0,!1,void 0,this),n&&r("div",{class:"toolbar-menu top-bar-more-menu",role:"menu",children:[e&&r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>{cs.value=!0}),children:"Export board"},void 0,!1,void 0,this),e&&r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>void fl()),children:"Present board"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>ti(1.25)),children:"Zoom in"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>ti(0.8)),children:"Zoom out"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>_r({x:0,y:0,scale:1},250)),children:"Reset zoom"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(t),children:"Fit all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var bi={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 rc(e,t,n,o={}){let i=bi[t];return{id:e,type:t,position:o.position??{x:i.x,y:i.y},size:o.size??{width:i.w,height:i.h},zIndex:t==="status"?0:1,collapsed:!1,pinned:!1,data:n}}var xi=null,sc=null,fp=0,wi=null,tO=3000,nO=2000,oO=1000,rO=80,RI=5000,iO=1e4,ic=!1,$r=null,wa=null,xa=null,us=0,ki=null;function sO(){if(tt())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 ka=new Map;function ac(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 yp(e){if(!sc)return e;let t=sc.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 lc(e,t,n){return yp(rc(e,t,n))}function aO(){return id([...H.value.values()],bi.markdown.w,bi.markdown.h)}function _a(){if(!H.value.has("status-main"))kr(lc("status-main","status",{phase:"idle",message:"",elapsed:0}))}function lO(e,t){let n=`md-${ac(e)}`;if(H.value.get(n))Xe(n,{path:e,title:t}),gt.value=n;else{let i=aO(),s=lc(n,"markdown",{path:e,title:t,content:"",rendered:""});s.position=i,kr(s),$t(n)}}function cO(e){if(H.value.get("context-main"))Xe("context-main",{cards:e});else if(e.length>0){let o=lc("context-main","context",{cards:e});kr(o)}}function uO(e){let t=e.url,n=`mcp-${ac(t)}`;if(H.value.get(n))Xe(n,e);else kr(lc(n,"mcp-app",e)),$t(n)}function dO(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(H.value.get(o)){Xe(o,e);return}let{serverName:s,toolName:a}=e;if(s&&a){for(let[v,b]of H.value.entries())if(b.type==="mcp-app"&&b.data.mode==="ext-app"&&b.data.serverName===s&&b.data.toolName===a&&!b.data.toolResult){Xe(v,{...e});return}}let{_x:l,_y:c,_width:u,_height:d}=e,p=bi["mcp-app"],f=u??p.w,m=d??p.h,h=l===void 0||c===void 0?id([...H.value.values()],f,m):null,g=yp(rc(o,"mcp-app",{mode:"ext-app",...e},{position:{x:l??h?.x??p.x,y:c??h?.y??p.y},size:{width:f,height:m}}));kr(g),$t(o,{recordHistory:!1})}function pO(e){let t=e.startsWith("ext-app-")?e:`ext-app-${e}`;if(H.value.has(t))return t;let n=`ext-app-${e}`;if(n!==t&&H.value.has(n))return n;for(let[o,i]of H.value.entries())if(i.type==="mcp-app"&&i.data.mode==="ext-app"&&i.data.toolCallId===e)return o;return null}function zI(e){let t=typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null;if(t&&H.value.has(t))return t;if(typeof e.toolCallId!=="string"||!e.toolCallId)return null;return pO(e.toolCallId)}function $I(e,t){if(typeof e!=="string"||!e)return null;if(typeof t!=="string"||!t)return null;let n=null;for(let[o,i]of H.value.entries())if(i.type==="mcp-app"&&i.data.mode==="ext-app"&&i.data.serverName===e&&i.data.toolName===t&&!i.data.toolResult){if(n)return null;n=o}return n}function LI(e){if(H.value.get("ledger-main"))Xe("ledger-main",e);else{let o=lc("ledger-main","ledger",e);o.collapsed=!0,kr(o)}}function Mg(e){if(!El(e))return;if(document.documentElement.setAttribute("data-theme",e),aa(),Qt.value!==e)Qt.value=e}function fO(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 mO(e){return e==="relation"||e==="depends-on"||e==="flow"||e==="references"}function zg(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 OI(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 hO(e){let t=zg(e),n=OI(e);return t&&n?{...t,...n}:null}function gO(e){if(typeof e.id!=="string"||!e.id)return null;if(!fO(e.type))return null;let t=zg(e.position),n=OI(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,linksRevision:typeof e.linksRevision==="number"?e.linksRevision:0,...gp(e.createdBy)?{createdBy:e.createdBy}:{},...gp(e.lastEditedBy)?{lastEditedBy:e.lastEditedBy}:{},data:o}}function gp(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.actor==="string"&&typeof t.source==="string"}function yO(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(!mO(e.type))return null;return{id:e.id,from:e.from,to:e.to,...typeof e.toBoardId==="string"?{toBoardId:e.toBoardId}:{},type:e.type,...typeof e.kind==="string"?{kind:e.kind}:{},...typeof e.reason==="string"?{reason:e.reason}:{},...typeof e.label==="string"?{label:e.label}:{},...e.style==="solid"||e.style==="dashed"||e.style==="dotted"?{style:e.style}:{},...e.animated===!0?{animated:!0}:{},...typeof e.revision==="number"?{revision:e.revision}:{},...gp(e.changedBy)?{changedBy:e.changedBy}:{},...typeof e.changedAt==="string"?{changedAt:e.changedAt}:{},...gp(e.createdBy)?{createdBy:e.createdBy}:{},...typeof e.createdAt==="string"?{createdAt:e.createdAt}:{}}}function vO(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)=>zg(o)).filter((o)=>o!==null),n=hO(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 PI="pmx-canvas-version-reload";function bO(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 i=`${String(e)}::${String(t)}`;try{if(window.sessionStorage.getItem(PI)===i)return;window.sessionStorage.setItem(PI,i)}catch{return}window.location.reload()}function xO(e){let t=fi.value[0]?.id;if(Vh(e),_o.value&&fi.value[0]?.id!==t)yi()}function wO(e){PC(e)}var ds=0,Pg=0,Sa=null;function kO(e){Hf(e)}function SO(e){let t=Sa;if(Sa=null,e){if(t?.boardId===se.value)hp(t);return}let n=se.value,o=++ds;if(sc=null,cn.value=!1,su(),Hk(),pu(),fm({nodes:[],edges:[]}),t?.boardId===se.value)hp(t);if(se.value===null)Hd();if(Fn.value?.kind==="receipt")Fn.value=null;Jh({}),Oo.value=null,$g();let i=Pg,s=Lo;pk(n).then((a)=>{if(o===ds&&i===Pg)hp({layout:a,boardId:n})}),de("fetchPinnedContext","/api/canvas/pinned-context",{}).then((a)=>{if(o===ds&&s===Lo)DI({nodeIds:a.nodeIds})})}Tk(SO);function _O(e){if(bo.value++,ds++,Sa=null,cn.value=!1,typeof e.catalogEpoch==="string")Ck(e.catalogEpoch);if(!tt()&&typeof e.workbenchToken==="string")window.__PMX_WORKBENCH_TOKEN=e.workbenchToken;if(xr.value=e.sessionId||"",Rf(e.workspaceSettings),ao.value="connected",il().then(Jr),Zi.value+=1,bO(e.version,e.bundleStamp),gk().then(Vh),jl(),zr(),Ya(),!fu&&!tt())Jw();if(de("fetchHumanPresence","/api/canvas/human-presence",null).then(Hf),$g().then(()=>{if(_o.value)yi()}),typeof e.theme==="string"&&!wg())Mg(e.theme);if(e.ledgerSummary)LI(e.ledgerSummary)}function CO(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(lO(t,n),e.ledgerSummary)LI(e.ledgerSummary)}function TO(e){_a(),Xe("status-main",{message:typeof e.message==="string"?e.message:String(e.message??""),level:e.level??"ok",source:e.source})}function IO(e){_a(),Xe("status-main",{phase:e.phase,detail:e.detail})}function EO(e){let t=e.cards??[];cO(t)}function AO(e){if(typeof e.url==="string"&&e.url)uO({url:e.url,sourceServer:e.sourceServer,sourceTool:e.sourceTool,inferredType:e.inferredType,trustedDomain:e.trustedDomain,hostMode:e.hostMode??"hosted"})}function RO(e){let t=e.sessions??[];for(let n of t){let o=n.url;if(!o)continue;let i=`mcp-${ac(o)}`;if(H.value.has(i))Xe(i,{sessionState:n.state,lastSeenAt:n.lastSeenAt})}}function PO(e){if(typeof e.url==="string"&&e.url){let t=`mcp-${ac(e.url)}`;if(H.value.has(t))Xe(t,{hostMode:"fallback",fallbackReason:e.reasonCode})}}function NO(e){let n=H.value.get("context-main");if(!n)return;let o=(n.data.auxTabs??[]).concat(e);Xe("context-main",{auxTabs:o})}function MO(e){if(H.value.has("context-main"))if(e.mode==="all")Xe("context-main",{auxTabs:[]});else{let o=H.value.get("context-main");if(!o)return;let i=(o.data.auxTabs??[]).filter((s)=>s.id!==e.id);Xe("context-main",{auxTabs:i})}}function zO(e){_a(),Xe("status-main",{phase:"idle",lastCompletion:{tokenCount:e.tokenCount,artifactCount:e.artifactCount}})}function $O(e){_a(),Xe("status-main",{phase:"tooling",detail:`${e.name}`,activeTool:e.name})}function LO(e){_a(),Xe("status-main",{activeTool:null})}function OO(e){if(e.state==="active"&&e.path){let n=`md-${ac(e.path)}`;if(H.value.has(n))Xe(n,{reviewActive:!0})}}function DO(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;dO({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 BO(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=zI(e)??$I(e.serverName,e.toolName);if(!t)return;if(H.value.has(t))Xe(t,{html:e.html})}function FO(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=zI(e)??$I(e.serverName,e.toolName);if(!t)return;if(H.value.has(t)){if(e.success===!1){ei(t);return}Xe(t,{toolResult:Fh({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 HO(e){_a(),Xe("status-main",{subagent:{state:e.state,name:e.agentDisplayName??e.agentName}})}function UO(e){let t=e.nodeId;if(!t)return;let n=e.text||"",{position:o,parentNodeId:i,contextNodeIds:s}=e;if(e.threadNodeId&&H.value.has(e.threadNodeId)){let a=e.threadNodeId,l=H.value.get(a);if(!l)return;let c=Array.isArray(l.data.turns)?[...l.data.turns]:[],u=c[c.length-1];if(!u||u.role!=="user"||u.text!==n)c.push({role:"user",text:n,status:"pending"});Xe(a,{turns:c,threadStatus:"pending"});return}if(!H.value.has(t)){let a=o??bi.prompt;kr(yp(rc(t,"prompt",{text:n,turns:n?[{role:"user",text:n,status:"pending"}]:[],threadStatus:n?"pending":"draft",status:n?"pending":"draft",parentNodeId:i,contextNodeIds:s},{position:{x:a.x,y:a.y}}))),$t(t)}if(i&&H.value.has(i))zs({id:`edge-${i}-${t}`,from:i,to:t,type:"flow",style:"dashed"})}function jO(e){let{nodeId:t,status:n}=e;if(t&&H.value.has(t))Xe(t,{status:n})}function ZO(e){let{responseNodeId:t,promptNodeId:n}=e;if(!t)return;let o=n?H.value.get(n):void 0;if(o&&Array.isArray(o.data.turns)){ka.set(t,n);let s=[...o.data.turns];s.push({role:"assistant",text:"",status:"streaming"}),Xe(n,{turns:s,threadStatus:"streaming",_activeResponseId:t}),$t(n);return}let i=o?{x:o.position.x,y:o.position.y+o.size.height+24}:{x:bi.response.x,y:bi.response.y};if(!H.value.has(t))kr(yp(rc(t,"response",{content:"",status:"streaming",promptNodeId:n},{position:i})));if(n)zs({id:`edge-${n}-${t}`,from:n,to:t,type:"flow",animated:!0});$t(t)}function WO(e){let t=e.responseNodeId;if(!t)return;let n=ka.get(t);if(n){let o=H.value.get(n);if(o&&Array.isArray(o.data.turns)){let i=[...o.data.turns],s=i[i.length-1];if(s&&s.role==="assistant")s.text=e.content,s.status="streaming";Xe(n,{turns:i,threadStatus:"streaming"})}return}if(!H.value.has(t))return;Xe(t,{content:e.content,status:"streaming"})}function qO(e){let t=e.responseNodeId;if(!t)return;let n=ka.get(t);if(n){let s=H.value.get(n);if(s&&Array.isArray(s.data.turns)){let a=[...s.data.turns],l=a[a.length-1];if(l&&l.role==="assistant")l.text=e.content,l.status="complete";Xe(n,{turns:a,threadStatus:"answered",_activeResponseId:void 0})}ka.delete(t);return}if(!H.value.has(t))return;Xe(t,{content:e.content,status:"complete"});let i=H.value.get(t)?.data.promptNodeId;if(i){let s=`edge-${i}-${t}`,a=et.value.get(s);if(a)Vk(s),zs({...a,animated:!1})}}function hp(e){bo.value++;let t=e.layout;if(!t?.nodes)return;if(typeof e.boardGeneration==="number"){if(e.catalogEpoch!==Sn||Mo!==null&&e.boardGeneration<Mo)return;if(Mo===null||e.boardGeneration>Mo){Sa=e;return}}if(e.boardId!==void 0&&e.boardId!==se.value){Sa=e;return}Pg+=1;let n=!cn.value;cn.value=!0;let o=t.nodes.map(gO).filter((l)=>l!==null),i=Array.isArray(t.edges)?t.edges.map(yO).filter((l)=>l!==null):Array.from(et.value.values()),s=Array.isArray(t.annotations)?t.annotations.map(vO).filter((l)=>l!==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)co();fm({...a?{viewport:a}:{},nodes:o,edges:i,...s?{annotations:s}:{}},{applyViewport:n}),tl({event:"canvas-layout-update",data:e}),zr(1000)}function GO(e){if(e<=1)return 500;if(e===2)return 1000;return Math.min(2500,1500+(e-3)*500)}function KO(e){if(hm())return;let t=e.nodeId;if(t&&H.value.has(t)){if(e.noPan===!0){Sr(t);return}$t(t)}}function VO(e){if(hm()||e.clientId===Kr)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,i=typeof t.scale==="number"?t.scale:1;co(),pm({x:n,y:o,scale:i})}function XO(e){if(Do.value)return;if(!Ln.value&&e.present!==!0)return;let t=Xc.safeParse(e.stop);if(t.success)oS(t.data)}function JO(){if(Do.value)return;Ln.value=!1,Jo.value=""}function YO(e){if(Do.value)return;let t=Xc.safeParse(e.stop);if(!t.success)return;try{gm(t.data,Ln.value?void 0:(n)=>pl(n,{recordHistory:!1}))}catch{let n=Za.safeParse(e.viewport);if(!n.success)return;co(),pm(n.data)}}function QO(e){if(H.value.get("context-main"))Xe("context-main",{currentTokens:e.currentTokens,tokenLimit:e.tokenLimit,messagesLength:e.messagesLength,utilization:e.utilization,nearLimit:e.nearLimit})}function eD(e){Os.value=e.enabled===!0}function tD(e){if(typeof e.theme==="string"&&!wg())Mg(e.theme)}function DI(e){bo.value++;let t=Array.isArray(e.nodeIds)?e.nodeIds.filter((n)=>typeof n==="string"):[];if(ji===0)cm(t);tl({event:"context-pins-changed",data:e}),jl(),zr()}function nD(){jl(),zr()}var mp=null,Ng=0;async function $g(){let e=++Ng,t=ds,n=await hk();if(e===Ng&&t===ds)Oo.value=n}function NI(){if(mp)clearTimeout(mp);Ng+=1,mp=setTimeout(()=>{if(mp=null,$g(),_o.value)yi()},150)}function oD(e){let t=e.intent;if(!t||typeof t.id!=="string"||typeof t.kind!=="string"||typeof t.expiresAt!=="number")return;Hw(t)}function rD(e){let t=typeof e.id==="string"?e.id:"";if(!t)return;if(e.settled===!0)jw(t,typeof e.nodeId==="string"?e.nodeId:void 0);else Bf(t)}var BI={connected:_O,"workbench-open":CO,"canvas-status":TO,"execution-phase":IO,"context-cards":EO,"mcp-app-candidate":AO,"mcp-app-host-snapshot":RO,"mcp-app-host-fallback":PO,"aux-open":NO,"aux-close":MO,"assistant-complete":zO,"tool-start":$O,"tool-complete":LO,"review-state":OO,"subagent-status":HO,"ext-app-open":DO,"ext-app-update":BO,"ext-app-result":FO,"context-pins-changed":DI,"context-status-changed":nD,"knowledge-changed":()=>void Kt(),"lifecycle-changed":()=>void Kt(),"boards-changed":(e)=>{Qr(e),zr()},"canvas-layout-update":hp,"canvas-focus-node":KO,"canvas-viewport-update":VO,"canvas-tour-step":XO,"canvas-tour-exit":JO,"canvas-camera-move":YO,"context-usage":QO,"trace-state":eD,"theme-changed":tD,"settings-changed":(e)=>Rf(e.workspaceSettings),"canvas-prompt-created":UO,"canvas-prompt-status":jO,"canvas-response-start":ZO,"canvas-response-delta":WO,"canvas-response-complete":qO,"ax-state-changed":NI,"ax-event-created":NI,"ax-intent":oD,"ax-intent-clear":rD,"agent-presence":xO,"human-presence":kO,"agent-session-ended":wO};function FI(e,t){let n=BI[e];if(!n)return;let o=n;try{o(t)}catch(i){console.warn(`[sse-bridge] Handler for "${e}" failed:`,i)}}function MI(){ic=!0,us+=1;let e=us;wa?.abort();let t=new AbortController;wa=t;let n=!tt();ao.value="connecting";let o=null,i=!1,s=async()=>{if(e!==us)return;let a=new AbortController,l;try{let c=new URLSearchParams;if(xa!==null){if(c.set("since",String(xa)),n)c.set("waitMs",String(oO))}let u=xr.value;if(u)c.set("session",u);let d=c.toString(),p=Lo,f=await Promise.race([(async()=>{let b=await Gt(`/api/workbench/poll${d?`?${d}`:""}`,{signal:AbortSignal.any([t.signal,a.signal])});if(!b.ok)throw Error(`poll failed with HTTP ${b.status}`);return await b.json()})(),new Promise((b,x)=>{l=setTimeout(()=>{a.abort(),x(Error("poll request timed out"))},iO)})]);if(e!==us)return;if(!f.ok)throw Error("poll returned ok: false");let m=o;if(o=f.sessionId??null,m!==null&&f.sessionId&&m!==f.sessionId&&!f.snapshot){xa=null,$r=setTimeout(()=>void s(),0);return}if(f.snapshot&&i)sc=mm(),cn.value=!1,pu(),su(),ka.clear();let h=p===Lo&&ji===0,g=!1,v=new Set;if(!f.snapshot&&cn.value){let b;for(let x of f.events){let C=x.payload,y=C.catalogEpoch===Sn&&C.boardGeneration===Mo&&(x.event==="boards-changed"?C.activeBoardId:C.boardId)===se.value;if(x.event==="canvas-layout-update"&&y){if(b)v.add(b);b=x}else if(!(x.event==="boards-changed"&&y)&&!["agent-presence","human-presence","ax-intent","ax-intent-clear"].includes(x.event))b=void 0}}for(let b of f.events){if(v.has(b))continue;if(b.event==="context-pins-changed"&&!h){g=!0;continue}FI(b.event,b.payload)}if(g)um(),jl(),zr();i=!0,xa=f.seq,Wi.value=0,qi.value=0,ao.value="connected",$r=setTimeout(()=>void s(),n?rO:nO)}catch(c){if(e!==us)return;console.warn("[sse-bridge] poll transport error:",c),ao.value="disconnected",Wi.value+=1,qi.value=RI,$r=setTimeout(()=>void s(),RI)}finally{clearTimeout(l)}};return s(),()=>{if(Ya(),us+=1,ic=!1,xa=null,t.abort(),wa===t)wa=null;if($r)clearTimeout($r),$r=null}}function Lg(){if(ds++,Sa=null,hT(Mg),sc=mm(),cn.value=!1,pu(),su(),ka.clear(),wi)clearTimeout(wi),wi=null;let e=sO();if(e==="poll"||ic)return MI();let t=xr.value,n=t?`/api/workbench/events?session=${t}`:"/api/workbench/events";ao.value="connecting";let o=new EventSource(n);xi=o;let i=!1;if(ki)clearTimeout(ki);if(ki=null,e!=="sse")ki=setTimeout(()=>{if(ki=null,i||xi!==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(),xi=null,MI()},tO);for(let[s]of Object.entries(BI))o.addEventListener(s,(a)=>{if(xi!==o)return;i=!0;try{FI(s,JSON.parse(a.data))}catch(l){console.warn(`[sse-bridge] Failed to parse "${s}" event:`,l)}});return o.onopen=()=>{if(xi!==o)return;fp=0,Wi.value=0,qi.value=0,ao.value="connected"},o.onerror=()=>{if(xi!==o)return;ao.value="disconnected",o.close(),xi=null,fp+=1;let s=GO(fp);Wi.value=fp,qi.value=s,wi=setTimeout(()=>{wi=null,Lg()},s)},()=>{if(Ya(),wi)clearTimeout(wi),wi=null;if(ki)clearTimeout(ki),ki=null;if(ic){if(us+=1,ic=!1,xa=null,wa?.abort(),wa=null,$r)clearTimeout($r),$r=null}o.close(),xi=null}}function ps(e,t){console.error(`[app] ${e} failed`,t)}var iD=Ve(()=>H.value.size===0),HI=Ve(()=>{let e=Ct.value;return!!e&&!ut.value&&se.value===e.boardId&&wt===e.incarnation&&H.value.has(e.nodeId)}),Og=Ve(()=>Oe.value&&HI.value);function UI(){let[e,t]=E(()=>window.innerWidth>=700),[n,o]=E(!1),[i,s]=E(!1),[a,l]=E(!1),[c,u]=E({}),[d,p]=E(!1),[f,m]=E(null),h=D(null),g=D(null),[v,b]=E(Jt),{menu:x,openNodeMenu:C,openCanvasMenu:y,openEdgeMenu:k,closeMenu:_}=bT(),I=cn.value,w=io.value&&(se.value===null||ut.value),P=tr.value,L=xt.value,N=_o.value||Co.value.length>0||os.value.length>0||!!To.value,Y=Og.value;Me(()=>{if(!L){if(Fn.value=null,eo.value=!1,document.activeElement?.closest(".command-bar, .session-panel, .agent-popover"))h.current?.focus({preventScroll:!0})}},[L]);let B=oe(()=>t((A)=>!A),[]),J=oe(()=>o((A)=>!A),[]),X=oe(()=>o(!1),[]),V=oe((A)=>m(A),[]),ee=oe((A)=>{Ew(A),g.current=A},[]),he=oe((A,te)=>{_r({x:A,y:te,scale:Te.value.scale},200)},[]);return q(()=>Lg(),[]),q(()=>{let A=(te)=>{let M=te.detail;u(M??{}),l(!0)};return window.addEventListener("pmx-open-board-link",A),()=>window.removeEventListener("pmx-open-board-link",A)},[]),q(()=>{let A=null,te=()=>{if(A!==null)window.clearTimeout(A);A=window.setTimeout(()=>{A=null,Jr()},400)};return window.addEventListener("resize",te),()=>{if(A!==null)window.clearTimeout(A);window.removeEventListener("resize",te)}},[]),Me(()=>{let A=(O)=>{let Pe=(O.metaKey||O.ctrlKey)&&!O.altKey;if(d&&(O.key==="Escape"||O.key==="?"||O.key==="/"&&O.shiftKey)){O.preventDefault(),p(!1);return}if(ut.value||se.value===null)return;if(O.defaultPrevented)return;if(Pe&&O.key==="k"){O.preventDefault(),s((ve)=>!ve);return}if(O.key==="Escape"&&f){O.preventDefault(),m(null);return}if(O.key==="Escape"&&Og.value){if(O.target?.closest('[role="menu"], [role="alertdialog"]'))return;O.preventDefault(),Ct.value=null;return}if(O.key==="Escape"&&Bt.value&&!$o.value){O.preventDefault(),Cr();return}if(O.key==="Escape"&&i){O.preventDefault(),s(!1);return}let Fe=O.target,De=Fe?.tagName;if(De==="INPUT"||De==="TEXTAREA"||Fe?.isContentEditable)return;if(Fe?.closest('[role="menu"]'))return;let Ae=Fe?.closest('[role="dialog"]');if((O.key==="Tab"||O.key.startsWith("Arrow"))&&Fe?.closest(".tool-rail, .top-bar"))return;if(O.key===" "&&!O.repeat&&!Pe&&!Ae){O.preventDefault(),ul.value=!0;return}if(O.key==="?"||O.key==="/"&&O.shiftKey){O.preventDefault(),p((ve)=>!ve);return}if(Pe&&(O.key==="z"||O.key==="Z"))O.preventDefault(),ig(O.shiftKey);else if(Pe&&(O.key==="y"||O.key==="Y"))O.preventDefault(),ig(!0);else if(Pe&&O.key==="0")O.preventDefault(),_r({x:0,y:0,scale:1},250);else if(Pe&&(O.key==="="||O.key==="+"))O.preventDefault(),ti(1.25);else if(Pe&&O.key==="-")O.preventDefault(),ti(0.8);else if(Ae)return;else if(O.key==="Escape"){if(!ir(O))return;if(O.preventDefault(),Io.value?.boardId===se.value)Io.value=null;Ro.value="All",$n(),gt.value=null,_()}else if(O.key==="Tab")O.preventDefault(),eS(O.shiftKey?-1:1);else if(O.key==="Delete"||O.key==="Backspace"){if(br.value!==null){let z=br.value;O.preventDefault(),br.value=null,xu(z).catch((re)=>ps("delete-edge",re));return}let ve=st.value.size>0?[...st.value]:gt.value?[gt.value]:[];if(ve.length===0)return;O.preventDefault();for(let z of ve)Xr(z).catch((re)=>ps("delete",re));$n(),gt.value=null}else if(gt.value&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(O.key)){O.preventDefault();let ve=O.key.replace("Arrow","").toLowerCase();tS(ve)}else if(!Pe&&!O.altKey){let ve=O.key.toLowerCase();if(ve==="v"&&!O.shiftKey)Wn.value="select";else if(ve==="c"&&!O.shiftKey&&!Pe)O.preventDefault(),Wn.value=Wn.value==="connect"?"select":"connect";else if(ve==="m"&&!O.shiftKey)O.preventDefault(),Eo({type:"markdown",title:"New note",width:520,height:360}).catch((z)=>ps("create markdown",z));else if(ve==="a"&&!O.shiftKey)O.preventDefault(),m((z)=>z==="pen"?null:"pen");else if(ve==="g"&&!O.shiftKey){O.preventDefault();let z=Array.from(st.value);if(z.length>=2)Ns({title:"Group",childIds:z}).catch((re)=>ps("group selection",re)),$n();else Eo({type:"group",title:"Group"}).catch((re)=>ps("create group",re))}else if(ve==="g"&&O.shiftKey){O.preventDefault();for(let z of Wk())ei(z),Ms(z).catch((re)=>ps("ungroup",re));$n()}else if(ve==="i"&&!O.shiftKey)O.preventDefault(),as("image");else if(ve==="w"&&!O.shiftKey)O.preventDefault(),as("webpage");else if(ve==="h"&&!O.shiftKey)O.preventDefault(),Eo({type:"html",title:"HTML surface"}).catch((z)=>ps("create html",z));else if(ve==="f"&&O.shiftKey)O.preventDefault(),as("file");else if(ve==="f"&&!O.shiftKey){O.preventDefault();let z=Jt();Fs(z.width,z.height)}}},te=(O)=>{if(O.key===" ")ul.value=!1},M=()=>{ul.value=!1};return document.addEventListener("keydown",A),document.addEventListener("keyup",te),window.addEventListener("blur",M),()=>{document.removeEventListener("keydown",A),document.removeEventListener("keyup",te),window.removeEventListener("blur",M)}},[f,_,i,d]),q(()=>{let A=window.setTimeout(()=>void Jr(),250);return()=>window.clearTimeout(A)},[P]),Me(()=>{let A=g.current;if(!A)return;let te=new ResizeObserver(()=>{b(Jt()),Jr();let M=Ct.value;if(M&&Og.value)$t(M.nodeId,{recordHistory:!1})});return te.observe(A),()=>te.disconnect()},[]),q(()=>{if(!I)return;let A=window.__pmxCanvasBootstrapReady;if(typeof A==="function")A()},[I]),r("div",{class:`app-shell${Ln.value?" is-presenting":""}`,"data-session-active":P?"true":"false",children:[r(sS,{},void 0,!1,void 0,this),r(tT,{},void 0,!1,void 0,this),r(ST,{minimapVisible:e,onToggleMinimap:B,snapshotOpen:n,onToggleSnapshot:J,snapshotBtnRef:h,onOpenPalette:()=>s(!0),onOpenShortcuts:()=>p((A)=>!A),annotationTool:f,onSetAnnotationTool:V},void 0,!1,void 0,this),r("div",{class:"app-main",children:[r(AI,{},void 0,!1,void 0,this),r(pT,{},void 0,!1,void 0,this),r("div",{class:`workspace${Y?" is-reviewing":""}`,children:[r("div",{class:"canvas-region",ref:ee,children:[!ut.value&&r(sT,{onNodeContextMenu:C,onCanvasContextMenu:y,onEdgeContextMenu:k,annotationMode:f!==null,annotationTool:f},void 0,!1,void 0,this),r(SS,{},void 0,!1,void 0,this),r($C,{},void 0,!1,void 0,this),!w&&r(LC,{},void 0,!1,void 0,this),!w&&r(QC,{},void 0,!1,void 0,this),r(kS,{},void 0,!1,void 0,this),r(QT,{},void 0,!1,void 0,this),r(eI,{},void 0,!1,void 0,this),w?r(XT,{},void 0,!1,void 0,this):I&&iD.value&&qt.value.size===0&&r(_T,{onOpenPalette:()=>s(!0)},void 0,!1,void 0,this),!w&&st.value.size>0&&r(uI,{},void 0,!1,void 0,this),!w&&!L&&r(uT,{},void 0,!1,void 0,this),!w&&_o.value&&!tt()&&r(aT,{},void 0,!1,void 0,this),!w&&r(xI,{onOpenSnapshots:()=>o(!0)},void 0,!1,void 0,this),r(CS,{},void 0,!1,void 0,this),!ut.value&&r(JT,{},void 0,!1,void 0,this),!w&&Bt.value&&r(iI,{},void 0,!1,void 0,this),r(_I,{open:n&&!ut.value,onClose:X,anchorRef:h},void 0,!1,void 0,this),e&&!w&&r(cI,{viewport:Te,nodes:H,edges:et,onNavigate:he,containerWidth:v.width,containerHeight:v.height},void 0,!1,void 0,this)]},void 0,!0,void 0,this),HI.value&&r(vT,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),P&&r(yI,{},void 0,!1,void 0,this),!P&&N&&r(gI,{},void 0,!1,void 0,this),!ut.value&&x&&r(xT,{menu:x,onClose:_},void 0,!1,void 0,this),!ut.value&&i&&r(gT,{onClose:()=>s(!1),onToggleMinimap:B},void 0,!1,void 0,this),!ut.value&&a&&r(yT,{...c,onClose:()=>l(!1)},void 0,!1,void 0,this),d&&r(wI,{onClose:()=>p(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}NS();var jI=document.getElementById("app");if(jI)Aa(r(UI,{},void 0,!1,void 0,this),jI);
394
+ ${a.trim()}`},void 0,!1,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",onClick:e,children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"submit",class:"text-prompt-confirm",disabled:!i.trim()||!a.trim(),children:["Continue on GitHub ",r(ri,{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 ec(e,t){console.error(`[tool-rail] ${e} failed`,t)}function as(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"}};On(t[e].message,t[e].placeholder).then((n)=>{if(!n)return;Eo({type:e,content:n}).catch((o)=>ec(`create ${e}`,o))})}function to({label:e,shortcut:t,detail:n,ariaLabel:o,active:i,menuOpen:s,onClick:a,btnRef:l,children:c}){let[u,d]=E(null),p=(h)=>{if(s)return;let g=h.currentTarget.getBoundingClientRect();d({left:g.right+10,top:g.top+g.height/2})},f=()=>d(null),m=o??(t?`${e} (${t})`:n?`${e} (${n})`:e);return r(be,{children:[r("button",{ref:l,type:"button",class:`rail-btn${i?" active":""}`,"aria-label":m,"aria-pressed":i===void 0?void 0:i,onClick:(h)=>{f(),a(h)},onPointerEnter:p,onPointerLeave:f,onFocus:p,onBlur:f,children:c},void 0,!1,void 0,this),u&&!s&&r("span",{class:"toolbar-tooltip rail-tooltip",role:"tooltip","data-testid":"rail-tooltip",style:{left:`${u.left}px`,top:`${u.top}px`},children:[r("span",{class:"toolbar-tooltip-label",children:e},void 0,!1,void 0,this),(t||n)&&r("span",{class:"toolbar-tooltip-meta",children:[t&&r("kbd",{class:"toolbar-tooltip-shortcut",children:t},void 0,!1,void 0,this),n&&r("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 rr({label:e,description:t,hint:n,beta:o,toggle:i=o,checked:s,disabled:a,onClick:l}){let c=wy(),[u,d]=E(null),p=(m)=>d(m.currentTarget.getBoundingClientRect()),f=()=>d(null);return r(be,{children:[r("button",{type:"button",role:s===void 0?"menuitem":"menuitemcheckbox","aria-label":o?`${e} (Beta)`:e,"aria-checked":s,"aria-describedby":u?c:void 0,class:"toolbar-menu-item","aria-disabled":a||void 0,onPointerEnter:p,onPointerLeave:f,onFocus:p,onBlur:f,onClick:()=>{if(a)return;f(),l()},children:[r("span",{class:"settings-item-label",children:[e," ",o&&r("span",{class:"beta-tag",children:"Beta"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i?r("span",{class:`settings-switch${s?" is-on":""}`,"aria-hidden":"true"},void 0,!1,void 0,this):n?r("span",{class:"toolbar-menu-hint",children:n},void 0,!1,void 0,this):null]},void 0,!0,void 0,this),u&&r(Ws,{children:r("span",{id:c,class:"toolbar-tooltip settings-tooltip",role:"tooltip",ref:(m)=>{if(!m)return;let h=window.innerWidth-u.right>=m.offsetWidth+20;m.style.left=`${h?u.right+10:Math.max(12,Math.min(u.left,window.innerWidth-m.offsetWidth-12))}px`,m.style.top=`${Math.max(12,Math.min(h?u.top:u.top-m.offsetHeight-8,window.innerHeight-m.offsetHeight-12))}px`},children:[r("span",{class:"toolbar-tooltip-label",children:[e,o?" (Beta)":""]},void 0,!0,void 0,this),r("span",{class:"toolbar-tooltip-body",children:t},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 ST({minimapVisible:e,onToggleMinimap:t,snapshotOpen:n,onToggleSnapshot:o,snapshotBtnRef:i,onOpenPalette:s,onOpenShortcuts:a,annotationTool:l,onSetAnnotationTool:c}){let u=Wn.value,d=Ds.value,p=Array.from(H.value.values()).filter((V)=>V.type==="trace").length,f=et.value.size,[m,h]=E(!1),[g,v]=E(!1),[b,x]=E(!1),C=async(V)=>{if(g||!Wr.value)return;v(!0),x(!1);try{let ee=await pe("saveWorkspaceSettings","/api/canvas/settings",{ok:!1},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({[V]:!Wr.value[V]})});x(ee.ok!==!0)}finally{v(!1)}},[y,k]=E(null),[_,I]=E(null),w=D(null),P=D(null),L=(V)=>{if(y){k(null);return}let ee=V.currentTarget.getBoundingClientRect();I({bottom:ee.bottom,right:ee.right}),k("settings")},N=(V)=>()=>{k(null),i.current?.focus(),V()},Y=_?{position:"fixed",left:`${_.right+8}px`,bottom:`${Math.max(10,window.innerHeight-_.bottom)}px`,top:"auto",right:"auto"}:void 0;Me(()=>{if(!y)return;let V=(he)=>{if(w.current&&he.target instanceof Node&&!w.current.contains(he.target))k(null)},ee=(he)=>{if(he.key==="Escape")he.preventDefault(),he.stopPropagation(),k(null),i.current?.focus({preventScroll:!0})};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",ee,!0),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",ee,!0)}},[y]);let B=(V)=>{op(),document.documentElement.setAttribute("data-theme",V),la(),Qt.value=V,hu(V),k(null)},J=fh(Qt.value),X=(V,ee={})=>{Gt(`/api/workbench/intent?_ts=${Date.now()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:V,payload:ee})}).catch((he)=>ec("sendIntent",he))};return r(be,{children:[r("div",{class:"tool-rail",ref:w,role:"toolbar","aria-label":"Canvas tools","aria-orientation":"vertical",children:[r(to,{label:"Home",ariaLabel:"PMX Canvas — Home",onClick:()=>{k(null),Mn(null).catch((V)=>ec("openHome",V))},children:r("span",{class:"rail-brand",children:r(zu,{size:22},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),!ut.value&&r(be,{children:[r("div",{class:"rail-divider"},void 0,!1,void 0,this),r(to,{label:"Select",shortcut:"V",active:u==="select",onClick:()=>Wn.value="select",children:r(bS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Pan",shortcut:"Space",active:u==="pan",onClick:()=>Wn.value="pan",children:r(xS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Connect",shortcut:"C",active:u==="connect",onClick:()=>Wn.value="connect",children:r("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:[r("circle",{cx:"4",cy:"4",r:"2"},void 0,!1,void 0,this),r("circle",{cx:"12",cy:"12",r:"2"},void 0,!1,void 0,this),r("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),r("div",{class:"rail-divider"},void 0,!1,void 0,this),r(to,{label:"Markdown note",shortcut:"M",onClick:()=>void Eo({type:"markdown",title:"New note",width:520,height:360}).catch((V)=>ec("create markdown",V)),children:r(ni,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{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:()=>P.current?.click(),children:r(dS,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("input",{ref:P,type:"file",hidden:!0,multiple:!0,"aria-label":"Attach files",onChange:(V)=>{let ee=Jt(),he=Ee.value;ua(Array.from(V.currentTarget.files??[]),(ee.width/2-he.x)/he.scale,(ee.height/2-he.y)/he.scale),V.currentTarget.value=""}},void 0,!1,void 0,this),r(to,{label:"Webpage",shortcut:"W",onClick:()=>as("webpage"),children:r(Us,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Group",shortcut:"G",onClick:()=>void Eo({type:"group",title:"Group"}).catch((V)=>ec("create group",V)),children:r(Sm,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Draw",shortcut:"A",active:l==="pen",onClick:()=>c(l==="pen"?null:"pen"),children:r(gS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Text note",active:l==="text",onClick:()=>c(l==="text"?null:"text"),children:r(vS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(to,{label:"Eraser",active:l==="eraser",onClick:()=>c(l==="eraser"?null:"eraser"),children:r(yS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"rail-divider"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!ut.value&&r(to,{label:"Search & commands",shortcut:Ft("K"),onClick:s,children:r(Mu,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),!ut.value&&r(to,{label:"Arrange",detail:f>0?"graph-aware":"grid",onClick:()=>f>0?Eu():Iu(),children:r(Tr,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"rail-spacer"},void 0,!1,void 0,this),r("span",{class:"toolbar-menu-anchor",children:[r(to,{label:"Settings",detail:"Appearance, board tools, beta features, and feedback",ariaLabel:"Settings",menuOpen:y!==null,active:y!==null||n,onClick:L,btnRef:i,children:r("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:r("path",{d:"M4 7h9M17 7h3M4 17h3M11 17h9M13 7a2 2 0 1 0 4 0a2 2 0 1 0-4 0M7 17a2 2 0 1 0 4 0a2 2 0 1 0-4 0"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),y==="settings"&&r("div",{class:"toolbar-menu rail-settings-menu",style:Y,role:"menu","aria-label":"Settings",children:[r(rr,{label:"Theme",description:"Choose the canvas appearance. Your choice is saved with the board.",hint:`${ea[J].label} ›`,onClick:()=>k("theme")},void 0,!1,void 0,this),!ut.value&&r(be,{children:[r(rr,{label:"Snapshots",description:"Save a board checkpoint, compare changes, or restore an earlier version.",onClick:N(o)},void 0,!1,void 0,this),r(rr,{label:"Minimap",description:"Show a small overview of the board. Drag its viewport to move around the canvas.",checked:e,hint:e?"On":"Off",onClick:N(t)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(rr,{label:"Keyboard shortcuts",description:"See shortcuts for creating cards, selecting, navigating, and editing the canvas.",hint:"?",onClick:N(a)},void 0,!1,void 0,this),r("div",{class:"toolbar-menu-divider",role:"separator"},void 0,!1,void 0,this),r("span",{class:"settings-caption",children:"Beta features · workspace-wide · off by default"},void 0,!1,void 0,this),r(rr,{label:"Agent sessions",beta:!0,checked:xt.value,disabled:!Wr.value||g,description:"Show session chips, tasks, timeline, steering composer, and receipts. Turning off hides these without ending attached agents. Approvals and edit protections remain available. Saved for this workspace.",onClick:()=>void C("agentSessions")},void 0,!1,void 0,this),r(rr,{label:"Knowledge lifecycle",beta:!0,checked:Oe.value,disabled:!Wr.value||g,description:"This turns on context lifecycle, where boards and cards decay over time as their relevance fades. Includes Review, review policies, categories, and due or retired indicators. Turning off hides lifecycle tools without deleting their data or drafts. Saved for this workspace.",onClick:()=>void C("knowledgeLifecycle")},void 0,!1,void 0,this),b&&r("p",{class:"settings-error",role:"alert",children:"Could not save settings. Try again."},void 0,!1,void 0,this),!xt.value&&(fa.value.length>0||Co.value.length>0||os.value.length>0||To.value)&&r(rr,{label:"Agent controls",description:"Review pending approvals, inspect or clear the write scope, or end an existing attachment without enabling the session beta.",onClick:N(()=>eo.value=!0)},void 0,!1,void 0,this),r("div",{class:"toolbar-menu-divider",role:"separator"},void 0,!1,void 0,this),!tt()&&!ut.value&&r(be,{children:[r(rr,{label:"Trace",description:"Show execution traces sent by connected tools. Turning off keeps existing traces. This does not start an agent.",toggle:!0,checked:d,onClick:()=>X("trace-toggle",{enabled:!d})},void 0,!1,void 0,this),(d||p>0)&&r(rr,{label:"Clear trace",description:"Remove recorded execution traces from this board without changing whether trace capture is enabled.",onClick:N(()=>X("trace-clear"))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(rr,{label:"Send feedback",description:"Report a problem or suggestion. Review the feedback before sending.",onClick:N(()=>h(!0))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y==="theme"&&r("div",{class:"toolbar-menu",style:Y,role:"menu","aria-label":"Theme",children:[r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>k("settings"),children:r("span",{children:"‹ Settings"},void 0,!1,void 0,this)},void 0,!1,void 0,this),ph.map((V)=>r("button",{type:"button",role:"menuitemradio","aria-checked":J===V,class:`toolbar-menu-item${J===V?" active":""}`,onClick:()=>B(V),children:[r("span",{class:"theme-swatch",style:{background:ea[V].swatchBg},children:r("span",{class:"theme-swatch-dot",style:{background:ea[V].swatchAccent}},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{children:ea[V].label},void 0,!1,void 0,this),J===V&&r("span",{class:"toolbar-menu-check","aria-hidden":"true",children:"✓"},void 0,!1,void 0,this)]},V,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m&&r(kT,{onClose:()=>h(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function _T({onOpenPalette:e}){let t=D(null),n=()=>{Eo({type:"markdown",title:"New note",width:520,height:360}).catch(()=>{})},o=async(i)=>{if(!i||i.length===0)return;let s=Zr(),a=Ee.value;await ua(Array.from(i),(s.x-a.x)/a.scale,(s.y-a.y)/a.scale)};return r("div",{class:"empty-state","data-testid":"empty-state",children:[r("svg",{class:"empty-state-mark",width:"52",height:"52",viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",children:[r("rect",{x:"8",y:"8",width:"48",height:"48",rx:"7"},void 0,!1,void 0,this),r("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),r("div",{class:"empty-state-title",children:"What would you like to work on?"},void 0,!1,void 0,this),r("div",{class:"empty-state-grid",children:[r("button",{type:"button",class:"empty-state-action",onClick:()=>t.current?.click(),children:[r("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:[r("path",{d:"M8 10 V2 M8 2 L5 5 M8 2 L11 5"},void 0,!1,void 0,this),r("path",{d:"M2 10 V13 H14 V10"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"empty-state-action-label",children:["Drop files here",r("span",{class:"empty-state-action-description",children:"Bring in the material you want to work with."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"empty-state-action-hint",children:"or pick"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"empty-state-action",onClick:()=>as("webpage"),children:[r(Us,{size:16,class:"tone-ok"},void 0,!1,void 0,this),r("span",{class:"empty-state-action-label",children:["Paste a link",r("span",{class:"empty-state-action-description",children:"Add a source, reference, or inspiration."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("kbd",{children:Ft("V")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"empty-state-action",onClick:n,children:[r(ni,{size:16,class:"tone-accent"},void 0,!1,void 0,this),r("span",{class:"empty-state-action-label",children:["Start a note",r("span",{class:"empty-state-action-description",children:"Write down an idea, then ask your agent to help you develop it."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("kbd",{children:"M"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"empty-state-agent",children:[r("div",{class:"empty-state-agent-title",children:"Or start with your agent"},void 0,!1,void 0,this),r("div",{class:"empty-state-sub",children:"Give your agent a task and ask it to work on this board."},void 0,!1,void 0,this),xt.value&&r("button",{type:"button",class:"empty-state-action is-agent",onClick:()=>void vi(),children:[r(Zs,{size:16,class:"tone-purple"},void 0,!1,void 0,this),r("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),r("button",{type:"button",class:"empty-state-hint",onClick:e,children:["? shortcuts · ",Ft("K")," palette"]},void 0,!0,void 0,this),r("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:(i)=>{let s=i.currentTarget;o(s.files).finally(()=>{s.value=""})}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ir(e){let t=e.target instanceof HTMLElement?e.target:null;return e.key==="Escape"&&!e.defaultPrevented&&!t?.closest('input, textarea, [contenteditable="true"]')&&!document.querySelector('[role="dialog"], [role="menu"], .context-menu, .shortcut-overlay-backdrop')}var CT="From old snapshots";function ip(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 tc(e){return e.split("/").map((t,n,o)=>o.slice(0,n+1).join("/"))}function TT({board:e,folders:t,onClose:n}){let o=D(null),[i,s]=E(e.folder??""),[a,l]=E(""),[c,u]=E(!1),[d,p]=E("");bn(o,!0),q(()=>{let h=(g)=>{if(g.key!=="Escape")return;if(g.preventDefault(),g.stopPropagation(),!c)n()};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[c,n]);let f=a.trim()?[i,a.trim()].filter(Boolean).join("/"):i,m=async()=>{let h;try{if(a.includes("/"))throw Error("Use one folder name; choose its parent above.");h=ip(f)}catch(g){p(g instanceof Error?g.message:String(g));return}if(u(!0),p(""),await vr(e.id,{folder:h}),Ge.value.find((g)=>g.id===e.id)?.folder===h)n();else p("Could not move this board. Try again.");u(!1)};return r("div",{class:"text-prompt-backdrop",onPointerDown:()=>!c&&n(),children:r("div",{ref:o,class:"text-prompt home-folder-dialog",role:"dialog","aria-modal":"true","aria-label":`Move ${e.name}`,onPointerDown:(h)=>h.stopPropagation(),children:[r("div",{class:"text-prompt-title",children:["Move “",e.name,"”"]},void 0,!0,void 0,this),r("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),r("fieldset",{class:"home-folder-options",disabled:c,children:[r("legend",{children:"Destination folder"},void 0,!1,void 0,this),["",...t].map((h)=>r("label",{class:"home-folder-option",style:{paddingLeft:`${8+Math.min(h.split("/").length-1,5)*14}px`},children:[r("input",{type:"radio",name:"folder-destination",value:h,checked:i===h,onChange:()=>{s(h),p("")}},void 0,!1,void 0,this),r("span",{children:h||"Home (no folder)"},void 0,!1,void 0,this)]},h,!0,void 0,this))]},void 0,!0,void 0,this),r("label",{class:"home-folder-new",children:["New folder inside ",i||"Home"," ",r("span",{class:"home-folder-hint",children:"(optional)"},void 0,!1,void 0,this),r("input",{class:"text-prompt-input","aria-label":"New folder name",placeholder:"e.g. Decisions",maxLength:60,value:a,disabled:c,onInput:(h)=>{l(h.currentTarget.value),p("")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-folder-hint",children:["Move to: ",r("strong",{children:f||"Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),d&&r("p",{role:"alert",children:d},void 0,!1,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",disabled:c,onClick:n,children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"button",class:"text-prompt-confirm",disabled:c||f===(e.folder??""),onClick:()=>void m(),children:c?"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 IT({board:e,onClose:t}){let n=D(null),o=D(null),[i,s]=E(null),[a,l]=E(new Set),[c,u]=E(`${e.name} copy`),[d,p]=E(!0),[f,m]=E(!0),[h,g]=E(!1),[v,b]=E(""),[x,C]=E(!1);return bn(n,!0,{initial:o}),q(()=>{let k=!0;return Ak(e.id).then((_)=>{if(!k)return;if(!_||!Array.isArray(_.cards))return b("Could not load reusable cards. Try again.");s(_),l(new Set(_.cards.filter((I)=>I.reusable).map((I)=>I.id)))}),()=>{k=!1}},[e.id]),r("div",{class:"text-prompt-backdrop",onMouseDown:t,children:r("div",{ref:n,class:"text-prompt board-copy-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"board-copy-title",onMouseDown:(k)=>k.stopPropagation(),children:r("form",{onClick:Ho,onSubmit:async(k)=>{if(k.preventDefault(),!c.trim()||!i)return;C(!0),b("");let _=await Rk({sourceBoardId:e.id,name:c.trim(),...e.folder?{folder:e.folder}:{},nodeIds:[...a],includeReadme:d,includeStructure:f});if(C(!1),!_)return b("Could not create the board. Try a different name.");if(h)await Mn(_.id);t()},children:[r("h2",{id:"board-copy-title",children:["Create from ",e.name]},void 0,!0,void 0,this),r("label",{class:"board-copy-field",children:["Board name",r("input",{ref:o,class:"text-prompt-input",value:c,onInput:(k)=>u(k.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!i&&!v&&r("div",{class:"board-copy-status",role:"status",children:"Loading reusable cards…"},void 0,!1,void 0,this),v&&r("div",{class:"board-copy-error",role:"alert",children:v},void 0,!1,void 0,this),i&&r("fieldset",{class:"board-copy-cards",children:[r("legend",{children:"Cards to copy"},void 0,!1,void 0,this),i.cards.filter((k)=>k.reusable).length===0?r("div",{class:"board-copy-status",children:"No reusable cards on this board."},void 0,!1,void 0,this):i.cards.filter((k)=>k.reusable).map((k)=>r("label",{class:"board-copy-card",children:[r("input",{type:"checkbox",checked:a.has(k.id),onChange:(_)=>{let I=new Set(a);_.currentTarget.checked?I.add(k.id):I.delete(k.id),l(I)}},void 0,!1,void 0,this),r("span",{children:[r("strong",{children:k.title||"Untitled card"},void 0,!1,void 0,this),r("small",{children:k.type},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},k.id,!0,void 0,this))]},void 0,!0,void 0,this),r("div",{class:"board-copy-options",children:[r("label",{children:[r("input",{type:"checkbox",checked:f,onChange:(k)=>m(k.currentTarget.checked)},void 0,!1,void 0,this)," ","Preserve groups and connections"]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:d,disabled:!i?.readmeNodeId,onChange:(k)=>p(k.currentTarget.checked)},void 0,!1,void 0,this)," ","Include README"]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:h,onChange:(k)=>g(k.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),r("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),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",onClick:t,children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"submit",disabled:!i||!c.trim()||x,children:x?"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 sp({children:e,initiallyCollapsed:t=!1,reveal:n=0}){let o=D(null),[i,s]=E(280),[a,l]=E(400),[c,u]=E(t),d=D(null);return Me(()=>{if(n)u(!1)},[n]),Me(()=>{let p=o.current.closest(".home-memory"),f=p.querySelector(".home-memory-stage"),m=p.closest(".canvas-region"),h=p.querySelector(".home-memory-toolbar"),g=p.querySelector(".home-memory-legend"),v=()=>{m?.style.setProperty("--home-memory-content-top",`${f.getBoundingClientRect().top-(m?.getBoundingClientRect().top??0)}px`),l(Math.max(120,p.clientHeight-h.offsetHeight-g.offsetHeight-160))},b=new ResizeObserver(v);for(let x of[p,f,h,g])b.observe(x);return v(),()=>{b.disconnect(),m?.style.removeProperty("--home-memory-content-top")}},[]),r("div",{ref:o,class:`home-memory-inspector${c?" is-collapsed":""}`,style:c?void 0:{height:Math.min(i,a)},children:[!c&&r("div",{class:"home-memory-inspector-resize",role:"separator",tabIndex:0,"aria-label":"Resize relation details","aria-orientation":"horizontal","aria-controls":"home-memory-details","aria-valuemin":120,"aria-valuemax":a,"aria-valuenow":Math.min(i,a),onKeyDown:(p)=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(p.key))return;p.preventDefault(),s(p.key==="Home"?120:p.key==="End"?a:Math.max(120,Math.min(a,Math.min(i,a)+(p.key==="ArrowUp"?32:-32))))},onPointerDown:(p)=>{if(p.button!==0)return;p.preventDefault(),d.current={id:p.pointerId,y:p.clientY,height:Math.min(i,a)},p.currentTarget.focus({preventScroll:!0}),p.currentTarget.setPointerCapture(p.pointerId)},onPointerMove:(p)=>{let f=d.current;if(f?.id===p.pointerId)s(Math.max(120,Math.min(a,f.height+f.y-p.clientY)))},onPointerUp:()=>{d.current=null},onPointerCancel:()=>{if(d.current)s(d.current.height);d.current=null}},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button home-memory-inspector-toggle","aria-expanded":!c,"aria-controls":"home-memory-details",onClick:()=>u(!c),children:c?"Expand details":"Collapse details"},void 0,!1,void 0,this),r("div",{id:"home-memory-details",children:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var go={width:220,height:92};function ET(e,t){let n=e.filter((f)=>f.kind==="board"),o=new Map,i=[],s=new Set,a=new Set;for(let f of n){let m=(f.folder??"").split("/");m.forEach((h,g)=>{a.add(m.slice(0,g+1).join("/"))})}let l=(f,m)=>(f.folder??"")===m||!!m&&!!f.folder?.startsWith(`${m}/`),c=(f,m,h,g)=>{let v=n.filter((B)=>l(B,f)),b=t.has(f),x={path:f,x:m,y:h,width:280,height:72,count:v.length,depth:g,collapsed:b};if(i.push(x),b){for(let B of v)s.add(B.key);return x}let C=v.filter((B)=>(B.folder??"")===f).sort((B,J)=>B.title.localeCompare(J.title)),y=Math.min(3,Math.max(1,Math.ceil(Math.sqrt(C.length))));C.forEach((B,J)=>{let X=B.position??{x:m+24+J%y*(go.width+28),y:h+52+Math.floor(J/y)*(go.height+28)};o.set(B.key,{x:X.x+go.width/2,y:X.y+go.height/2})});let k=h+52+Math.ceil(C.length/y)*(go.height+28),_=C.length?y*(go.width+28)+20:280,I=[...a].filter((B)=>B&&B.slice(0,B.lastIndexOf("/"))===f&&B.includes("/")).sort(),w=20,P=0;for(let B of I){if(w>650)w=20,k+=P+24,P=0;let J=c(B,m+w,k,g+1);w+=J.width+24,P=Math.max(P,J.height),_=Math.max(_,w)}k+=P+(I.length?20:0),x.width=_,x.height=Math.max(100,k-h+4);let L=v.flatMap((B)=>{let J=o.get(B.key);return J?[J]:[]}),N=Math.max(m+x.width,...L.map((B)=>B.x+go.width/2+20)),Y=Math.max(h+x.height,...L.map((B)=>B.y+go.height/2+20));return x.x=Math.min(m,...L.map((B)=>B.x-go.width/2-20)),x.y=Math.min(h,...L.map((B)=>B.y-go.height/2-48)),x.width=N-x.x,x.height=Y-x.y,x},u=32,d=32,p=0;for(let f of[...a].filter((m)=>!m.includes("/")).sort()){if(u>1100)u=32,d+=p+36,p=0;let m=c(f,u,d,0);u+=m.width+36,p=Math.max(p,m.height)}return{positions:o,regions:i,hidden:s}}function ap(e){let t=Ge.value,n=bo.value,[o,i]=E(null),[s,a]=E(!0),[l,c]=E(!1),u=D(()=>{});return q(()=>{let d=!1,p=!1,f=!1,m,h=()=>{if(f=!0,!p&&m===void 0)m=window.setTimeout(g,120)},g=async()=>{m=void 0,f=!1,p=!0,a(!0);let v=Sn,b=bo.peek(),x=Ge.peek(),C=await pe("memoryGraph",`/api/canvas/memory-graph?projection=${e}`,null);if(d)return;if(p=!1,v!==Sn||b!==bo.peek()||x!==Ge.peek()){h();return}if(C&&Array.isArray(C.nodes)&&Array.isArray(C.edges))i(C),c(!1);else c(!0);if(a(!1),f)h()};return u.current=h,h(),()=>{d=!0,window.clearTimeout(m)}},[e]),q(()=>u.current(),[n,t]),{graph:o,loading:s,error:l,retry:()=>u.current()}}var AT={portal:"Portals",wiki:"Wiki links",card:"Card relations",previous:"Previous boards"};function RT(){let e=Ge.value,t=bo.value,{graph:n,loading:o,error:i,retry:s}=ap("boards"),[a,l]=E(""),[c,u]=E(!0),[d,p]=E(!1),[f,m]=E(!0),[h,g]=E(new Set),[v,b]=E(new Set),[x,C]=E(new Set),[y,k]=E(null),[_,I]=E(null),[w,P]=E(null),[L,N]=E({x:0,y:0}),[Y,B]=E(1),[J,X]=E({}),[V,ee]=E(!1),he=D(null),A=D(!0),te=D(!1),M=D(null);Me(()=>{ut.value=!0},[]),Me(()=>{if(!y)return;let R=(ne)=>{if(ir(ne))ne.preventDefault(),k(null)};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[y]),q(()=>{if(!y)return;let R=!1;P(null);let ne=Sn,Ce=bo.peek(),Te=new URLSearchParams({focus:y,depth:"2"});return pe("memoryGraph",`/api/canvas/memory-graph?${Te}`,null).then((fe)=>{if(!R&&ne===Sn&&Ce===bo.peek())P({key:y,graph:fe&&Array.isArray(fe.nodes)&&Array.isArray(fe.edges)?fe:null})}),()=>{R=!0}},[y,n,t]);let O=Ke(()=>(n?.nodes??[]).filter((R)=>R.kind==="board").map((R)=>{let ne=e.find((Ce)=>Ce.id===R.boardId);return ne?{...R,title:ne.name,folder:ne.folder,inContext:!!ne.pin,nodeCount:ne.nodeCount,position:ne.mapPosition??void 0}:R}),[n,e]),Pe=Ke(()=>ET(O,x),[O,x]),Fe=new Map;for(let R of O){let ne=R.folder?.split("/")[0]??"";Fe.set(ne,(Fe.get(ne)??0)+1)}let De=O.filter((R)=>c&&(!d||R.inContext)&&(f||!!R.folder)&&!h.has(R.folder?.split("/")[0]??"")&&!Pe.hidden.has(R.key)&&`${R.title} ${R.summary} ${R.folder??""}`.toLocaleLowerCase().includes(a.trim().toLocaleLowerCase())),Ae=new Set(De.map((R)=>R.key)),ve=(R)=>J[R]??Pe.positions.get(R),z=O.find((R)=>R.key===y),re=O.find((R)=>R.key===(_??y)),Ne=new Map;for(let R of n?.edges??[]){if(R.kind==="member"||v.has(R.kind))continue;let ne=Mt({boardId:R.source.boardId}),Ce=Mt({boardId:R.target.boardId});if(!Ae.has(ne)||!R.missing&&(!Ae.has(Ce)||ne===Ce))continue;let Te=JSON.stringify([ne,Ce,R.kind,R.relationKind,R.missing]),fe=Ne.get(Te);if(fe)fe.edges.push(R);else Ne.set(Te,{from:ne,to:Ce,edges:[R]})}let ke=new Set(re?[re.key]:[]);for(let{from:R,to:ne}of Ne.values())if(re&&(R===re.key||ne===re.key))ke.add(R),ke.add(ne);let ae=(R)=>new Set((n?.edges??[]).filter((ne)=>ne.kind!=="member"&&(ne.source.boardId===R.boardId||ne.target.boardId===R.boardId)).map((ne)=>ne.source.boardId===R.boardId?ne.target.boardId:ne.source.boardId).filter((ne)=>ne!==R.boardId)).size,Se=()=>{let R=he.current;if(!R?.clientWidth||!R.clientHeight)return;let ne=De.flatMap((Ye)=>{let Lt=ve(Ye.key);return Lt?[{x:Lt.x-110,y:Lt.y-46},{x:Lt.x+110,y:Lt.y+46}]:[]});for(let Ye of Pe.regions){if(h.has(Ye.path.split("/")[0]??"")||!f&&!Ye.path)continue;ne.push({x:Ye.x,y:Ye.y},{x:Ye.x+Ye.width,y:Ye.y+Ye.height})}if(!ne.length)return;let Ce=Math.min(...ne.map((Ye)=>Ye.x)),Te=Math.min(...ne.map((Ye)=>Ye.y)),fe=Math.max(...ne.map((Ye)=>Ye.x))-Ce,it=Math.max(...ne.map((Ye)=>Ye.y))-Te,Ht=Math.min(1.25,Math.max(0.08,Math.min((R.clientWidth-64)/Math.max(1,fe),(R.clientHeight-100)/Math.max(1,it))));B(Ht),N({x:(R.clientWidth-fe*Ht)/2-Ce*Ht,y:(R.clientHeight-it*Ht)/2-Te*Ht-12})};q(()=>{A.current=!0},[x]),q(()=>{if(A.current&&n&&(De.length||Pe.regions.length)&&!M.current)A.current=!1,Se()},[n,x]);let de=(R,ne)=>{let Ce=he.current;if(!Ce)return;let Te=ne??{x:Ce.clientWidth/2,y:Ce.clientHeight/2},fe=Math.min(3,Math.max(0.08,R));N({x:Te.x-(Te.x-L.x)*fe/Y,y:Te.y-(Te.y-L.y)*fe/Y}),B(fe)},Ue=(R,ne=!1)=>{k(R.key);let Ce=ve(R.key),Te=he.current;if(ne&&Ce&&Te)N({x:Te.clientWidth/2-Ce.x*Y,y:Te.clientHeight/2-Ce.y*Y})},xe=(R)=>{let ne=M.current;if(M.current=null,!ne)return;if(te.current=ne.moved,!ne.key)return;let Ce=ne.key,Te=()=>X((fe)=>{let it={...fe};return delete it[Ce],it});if(ne.boardId&&ne.moved&&!R){let fe=ne.current??ne.origin;vr(ne.boardId,{mapPosition:{x:fe.x-go.width/2,y:fe.y-go.height/2}}).finally(Te)}else Te()},qe=w?.key===y?w.graph:null,W=(qe?.edges??[]).filter((R)=>z&&R.kind!=="member"&&(R.source.boardId===z.boardId||R.target.boardId===z.boardId)),ye=e.find((R)=>R.id===z?.boardId),He=(R,ne,Ce,Te)=>r("label",{class:"home-memory-check",children:[r("input",{type:"checkbox","aria-label":R,checked:Ce,onChange:Te},void 0,!1,void 0,this),r("span",{children:R},void 0,!1,void 0,this),r("small",{children:ne},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("main",{class:`home-memory is-map${V?" sidebar-open":""}`,"aria-label":"Library Map",children:[r("div",{class:"home-memory-toolbar",children:[r("span",{children:[O.length," boards · ",e.reduce((R,ne)=>R+ne.nodeCount,0)," cards ·"," ",n?.edges.filter((R)=>R.kind!=="member").length??0," links"]},void 0,!0,void 0,this),r("span",{class:`home-memory-live${i?" is-error":""}`,role:"status",children:i?"Update failed":o?"Updating…":"Live"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button home-memory-sidebar-toggle","aria-expanded":V,onClick:()=>ee(!V),children:"Filters"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-body",children:[r("div",{class:"home-memory-stage",ref:he,"aria-label":"Pan the memory view",onWheel:(R)=>{R.preventDefault();let ne=R.currentTarget.getBoundingClientRect();de(Y*Math.exp(-R.deltaY*0.0015),{x:R.clientX-ne.left,y:R.clientY-ne.top})},onPointerDown:(R)=>{if(R.button!==0||R.target.closest("button"))return;te.current=!1,M.current={id:R.pointerId,start:{x:R.clientX,y:R.clientY},origin:L,moved:!1},R.currentTarget.setPointerCapture(R.pointerId)},onPointerMove:(R)=>{let ne=M.current;if(!ne||ne.id!==R.pointerId)return;let Ce=R.clientX-ne.start.x,Te=R.clientY-ne.start.y;if(Math.abs(Ce)+Math.abs(Te)>4)ne.moved=!0;if(!ne.moved)return;let fe={x:ne.origin.x+Ce/(ne.key?Y:1),y:ne.origin.y+Te/(ne.key?Y:1)};if(ne.current=fe,ne.key)X((it)=>({...it,[ne.key]:fe}));else N(fe)},onPointerUp:()=>xe(!1),onPointerCancel:()=>xe(!0),children:[r("div",{class:"home-memory-world",style:{transform:`translate(${L.x}px, ${L.y}px) scale(${Y})`,"--memory-zoom":Y},children:[Pe.regions.filter((R)=>!h.has(R.path.split("/")[0]??"")&&(f||R.path)).map((R)=>r("div",{class:`home-memory-region${R.depth?" is-nested":""}`,style:{left:R.x,top:R.y,width:R.width,height:R.height},children:r("button",{type:"button","aria-expanded":!R.collapsed,onClick:()=>C((ne)=>{let Ce=new Set(ne);if(Ce.has(R.path))Ce.delete(R.path);else Ce.add(R.path);return Ce}),children:[R.collapsed?"▸":"▾"," ",R.path.split("/").at(-1)||"Unfiled"," ",r("small",{children:[R.count," boards"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},R.path,!1,void 0,this)),r("svg",{class:"home-memory-links","aria-hidden":"true",children:[...Ne].map(([R,{from:ne,to:Ce,edges:Te}])=>{let fe=Te[0],it=ve(ne),Ht=ve(Ce);if(!it)return null;let Ye=Ht??{x:it.x+100,y:it.y-70},Lt=it.y+(Ye.y>it.y?46:-46),F=Ht?Ye.y+(Ye.y>it.y?-46:46):Ye.y,Ie=re&&(fe.source.boardId===re.boardId||fe.target.boardId===re.boardId),S=mo({kind:fe.relationKind,type:fe.type},e.find((ue)=>ue.id===fe.source.boardId)?.relationVocabulary),K=fe.missing?"var(--c-warn)":fe.kind==="card"?`var(--c-rel-${S.ink})`:void 0;return r("g",{"data-from":ne,"data-to":Ce,"data-count":Te.length,style:K?{stroke:K}:void 0,class:`memory-edge edge-${fe.kind}${fe.missing?" is-missing":""}${Ie?" is-emphasized":re?" is-dimmed":""}`,children:[r("path",{d:`M ${it.x} ${Lt} C ${it.x} ${(Lt+F)/2}, ${Ye.x} ${(Lt+F)/2}, ${Ye.x} ${F}`},void 0,!1,void 0,this),Te.length>1&&r("text",{x:(it.x+Ye.x)/2,y:(it.y+Ye.y)/2-6,children:[Te.length," links"]},void 0,!0,void 0,this),fe.missing&&r("text",{x:Ye.x,y:Ye.y-5,children:["⚠ Missing ",fe.kind," link"]},void 0,!0,void 0,this)]},R,!0,void 0,this)})},void 0,!1,void 0,this),De.map((R,ne)=>{let Ce=ve(R.key);if(!Ce)return null;let Te=e.find((fe)=>fe.id===R.boardId);return r("article",{"data-key":R.key,class:`home-memory-node is-board${R.inContext?" in-context":""}${y===R.key?" is-selected":""}${ke.has(R.key)?" is-emphasized":re?" is-dimmed":""}`,style:{left:Ce.x,top:Ce.y},onPointerEnter:()=>{if(!M.current)I(R.key)},onPointerLeave:()=>I(null),children:[r("button",{type:"button",class:"home-memory-select","aria-label":`board: ${R.title}`,"aria-pressed":y===R.key,onFocus:(fe)=>{if(!M.current&&fe.currentTarget.matches(":focus-visible"))Ue(R,!0)},onClick:()=>{if(!te.current)Ue(R);te.current=!1},onDblClick:()=>void zt(R),onPointerDown:(fe)=>{if(fe.button!==0)return;fe.stopPropagation(),te.current=!1,M.current={id:fe.pointerId,start:{x:fe.clientX,y:fe.clientY},origin:Ce,key:R.key,boardId:R.boardId,moved:!1},fe.currentTarget.setPointerCapture(fe.pointerId)},onKeyDown:(fe)=>{if(fe.key==="Enter")fe.preventDefault(),zt(R);if(fe.key.startsWith("Arrow")){fe.preventDefault();let it=(ne+(fe.key==="ArrowLeft"||fe.key==="ArrowUp"?-1:1)+De.length)%De.length,Ht=De[it];if(Ht)Ue(Ht,!0),he.current?.querySelectorAll(".home-memory-select")[it]?.focus({preventScroll:!0})}},children:[r("strong",{children:R.title},void 0,!1,void 0,this),r("span",{children:[R.nodeCount??0," cards · ",ae(R)," connected boards"]},void 0,!0,void 0,this),r("span",{class:"home-memory-summary",children:R.summary||"No summary yet"},void 0,!1,void 0,this),R.inContext&&r("span",{class:"home-memory-context",children:"⌖ In context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Te&&r(ho,{board:Te},void 0,!1,void 0,this)]},R.key,!0,void 0,this)})]},void 0,!0,void 0,this),r("div",{class:"home-memory-zoom",children:[r("button",{type:"button",class:"home-button","aria-label":"Zoom out",onClick:()=>de(Y/1.2),children:"−"},void 0,!1,void 0,this),r("span",{children:[Math.round(Y*100),"%"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button","aria-label":"Zoom in",onClick:()=>de(Y*1.2),children:"+"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:Se,children:"Fit view"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(!n||!De.length||i)&&r("div",{class:"home-memory-status",role:"status",children:i?r(be,{children:["Memory update failed."," ",r("button",{type:"button",class:"home-button",onClick:s,children:"Retry"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):!n?"Loading memory…":Pe.hidden.size?"Folders collapsed. Expand a folder to see its boards.":"No matching nodes."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("aside",{class:"home-memory-sidebar","aria-label":"Map settings",children:[r("section",{children:[r("h2",{children:"Filters"},void 0,!1,void 0,this),r("label",{class:"home-memory-search",children:[r("span",{children:"Find boards and cards"},void 0,!1,void 0,this),r("input",{type:"search",value:a,placeholder:"Search boards and cards…",onInput:(R)=>l(R.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),He("Boards",O.length,c,()=>u(!c)),He("Only in context",O.filter((R)=>R.inContext).length,d,()=>p(!d)),He("Include unfiled",O.filter((R)=>!R.folder).length,f,()=>m(!f))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Groups · by folder"},void 0,!1,void 0,this),[...Fe].sort(([R],[ne])=>R.localeCompare(ne)).map(([R,ne])=>r("div",{children:He(R||"Unfiled",ne,!h.has(R),()=>g((Ce)=>{let Te=new Set(Ce);if(Te.has(R))Te.delete(R);else Te.add(R);return Te}))},R,!1,void 0,this))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Links"},void 0,!1,void 0,this),Object.keys(AT).map((R)=>r("div",{class:`memory-legend-${R}`,children:He(AT[R],n?.edges.filter((ne)=>ne.kind===R).length??0,!v.has(R),()=>b((ne)=>{let Ce=new Set(ne);if(Ce.has(R))Ce.delete(R);else Ce.add(R);return Ce}))},R,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-legend","aria-label":"Legend",children:[r("span",{children:"▣ Board"},void 0,!1,void 0,this),r("span",{class:"memory-context-legend",children:"⌖ In context"},void 0,!1,void 0,this),r("span",{class:"memory-legend-portal",children:"━ Portal"},void 0,!1,void 0,this),r("span",{class:"memory-legend-wiki",children:"┄ Wiki"},void 0,!1,void 0,this),r("span",{class:"memory-legend-card",children:"━ Relation"},void 0,!1,void 0,this),r("span",{children:"Drag boards to save positions · drag background to pan · scroll to zoom"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(sp,{children:z?r("section",{class:"home-memory-details",role:"complementary","aria-label":"Selection details",children:[r("button",{type:"button",class:"home-memory-clear","aria-label":"Close details",onClick:()=>k(null),children:"×"},void 0,!1,void 0,this),r("div",{class:"home-memory-detail-header",children:[r("div",{class:"home-memory-selection-title",children:[r("h3",{children:[z.title," · ",W.length," connections"]},void 0,!0,void 0,this),r("p",{children:[z.folder||"Unfiled"," · board"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-actions",children:[r("button",{type:"button",class:"home-button is-primary",onClick:()=>void zt(z),children:"Open board"},void 0,!1,void 0,this),ye&&r(ho,{board:ye},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>void vr(z.boardId,{mapPosition:null}),children:"Reset position"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-detail-body",children:[r("p",{children:[z.nodeCount??0," cards · ",ae(z)," connected boards"]},void 0,!0,void 0,this),r("p",{children:z.summary||"No summary yet."},void 0,!1,void 0,this),r("p",{class:z.inContext?"memory-context-legend":"",children:z.inContext?"⌖ In context":"Not in context"},void 0,!1,void 0,this),r("details",{class:"home-memory-connections",open:!0,children:[r("summary",{children:"Connections"},void 0,!1,void 0,this),!qe&&r("p",{role:"status",children:w?.key===y?"Connections could not be loaded.":"Loading connections…"},void 0,!1,void 0,this),r("ul",{children:[W.map((R)=>{let ne=R.source.boardId===z.boardId,Ce=ne?R.target:R.source,Te=qe?.nodes.find((fe)=>fe.key===Mt(Ce));return r("li",{children:[r("span",{children:[ne?"→":"←"," ",R.kind==="card"?ha({...R,kind:R.relationKind}):`${R.kind}${R.label?` · ${R.label}`:""}`]},void 0,!0,void 0,this),R.missing?r("span",{class:"home-memory-missing",children:["⚠ Missing target: ",Ce.boardId,Ce.cardId?` / ${Ce.cardId}`:""]},void 0,!0,void 0,this):r("button",{type:"button",class:"home-button",onClick:()=>void zt(Ce),children:Te?.title??Ce.boardId},void 0,!1,void 0,this)]},R.id,!0,void 0,this)}),(qe?.unresolvedLinks??[]).filter((R)=>R.source.boardId===z.boardId).map((R)=>r("li",{class:"home-memory-missing",children:["⚠ Unresolved wiki: [[",R.ref,"]]"]},`${Mt(R.source)}:${R.ref}`,!0,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):r("div",{class:"home-memory-empty-details",children:[r("h3",{children:"Relations"},void 0,!1,void 0,this),r("p",{class:"home-memory-help",children:"Overview groups links between boards. Select a board to inspect connections. Double-click to open."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var Je={width:220,height:96,gap:64},nc=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y),SL=(e,t)=>e.x>t.left&&e.x<t.right&&e.y>t.top&&e.y<t.bottom;function _L(e,t,n){let o=0,i=1;for(let[s,a,l,c]of[[e.x,t.x-e.x,n.left,n.right],[e.y,t.y-e.y,n.top,n.bottom]])if(!a){if(s<=l||s>=c)return!1}else{let u=(l-s)/a,d=(c-s)/a;o=Math.max(o,Math.min(u,d)),i=Math.min(i,Math.max(u,d))}return o<i&&i>0&&o<1}function PT(e,t){let o=[...e].map(([f,m])=>({key:f,left:m.x-Je.width/2-8,right:m.x+Je.width/2+8,top:m.y-Je.height/2-8,bottom:m.y+Je.height/2+8})),i=(f,m)=>!o.some((h)=>_L(f,m,h)),s=o.flatMap((f)=>[{x:f.left,y:f.top},{x:f.right,y:f.top},{x:f.right,y:f.bottom},{x:f.left,y:f.bottom}]).filter((f)=>!o.some((m)=>SL(f,m))),a=new Map,l=(f,m)=>[{x:f.x-Je.width/2,y:f.y+m*Je.height},{x:f.x+Je.width/2,y:f.y+m*Je.height},{x:f.x+m*Je.width,y:f.y-Je.height/2},{x:f.x+m*Je.width,y:f.y+Je.height/2}].map((h,g)=>({port:h,stub:{x:h.x+(g===0?-8:g===1?8:0),y:h.y+(g===2?-8:g===3?8:0)}})),c=new Map,u=[],d=new Map,p=new Map;for(let f of t){let m=JSON.stringify([f.from,f.to].sort());p.set(m,(p.get(m)??0)+1)}for(let f of t){let m=e.get(f.from),h=e.get(f.to),g=JSON.stringify([f.from,f.to].sort()),v=d.get(g)??0;d.set(g,v+1);let b=((v+1)/(p.get(g)+1)-0.5)*0.8,x=l(m,b),C=l(h,b),y,k=1/0;for(let P of x)for(let L of C){let N=nc(P.stub,L.stub);if(N&&N<k&&i(P.stub,L.stub))k=N,y=[P.port,P.stub,L.stub,L.port]}if(!y){let P=s.map(()=>1/0),L=s.map(()=>-1),N=s.map(()=>0),Y=new Set;for(let X=0;X<s.length;X++)for(let V=0;V<x.length;V++){let ee=nc(x[V].stub,s[X]);if(ee<P[X]&&i(x[V].stub,s[X]))P[X]=ee,N[X]=V}let B=-1,J=0;while(Y.size<s.length){let X=-1;for(let ee=0;ee<s.length;ee++)if(!Y.has(ee)&&(X<0||P[ee]<P[X]))X=ee;if(X<0||P[X]>=k||!Number.isFinite(P[X]))break;Y.add(X);for(let ee=0;ee<C.length;ee++){let he=P[X]+nc(s[X],C[ee].stub);if(he<k&&i(s[X],C[ee].stub))k=he,B=X,J=ee}let V=a.get(X);if(!V)V=s.flatMap((ee,he)=>he!==X&&i(s[X],ee)?[{index:he,length:nc(s[X],ee)}]:[]),a.set(X,V);for(let ee of V)if(P[X]+ee.length<P[ee.index])P[ee.index]=P[X]+ee.length,L[ee.index]=X,N[ee.index]=N[X]}if(B>=0){let X=[];for(let he=B;he>=0;he=L[he])X.unshift(s[he]);let V=x[N[B]],ee=C[J];y=[V.port,V.stub,...X,ee.stub,ee.port]}}if(!y)continue;let _=Math.max(24,f.label.length*3.6+6),I=y.slice(1).map((P,L)=>({first:y[L],point:P,length:nc(y[L],P)})).filter((P)=>P.length>0).sort((P,L)=>L.length-P.length),w;for(let P=16;f.label&&!w;P+=20)w=I.flatMap(({first:N,point:Y,length:B})=>[0.5,0.25,0.75].flatMap((J)=>[-P,P].map((X)=>{let V=N.x+(Y.x-N.x)*J-(Y.y-N.y)*X/B,ee=N.y+(Y.y-N.y)*J+(Y.x-N.x)*X/B;return{x:V,y:ee,left:V-_,right:V+_,top:ee-16,bottom:ee+8}}))).find((N)=>![...o,...u].some((Y)=>N.left<Y.right&&N.right>Y.left&&N.top<Y.bottom&&N.bottom>Y.top));if(w)u.push(w);c.set(f.id,{points:y,path:y.map((P,L)=>`${L?"L":"M"} ${P.x} ${P.y}`).join(" "),label:w})}return c}var ls=(e)=>e.kind==="overview"?"overview":JSON.stringify(e),CL=(e,t)=>JSON.stringify([e,t].sort());function NT(e){let t=new Map,n=new Map,o=[],i=e.filter((s)=>s.kind!=="member");for(let s of i){if(s.missing){o.push(s);continue}if(s.source.boardId===s.target.boardId){n.set(s.source.boardId,(n.get(s.source.boardId)??0)+1);continue}let a=CL(s.source.boardId,s.target.boardId),l=t.get(a);if(l)l.edges.push(s);else t.set(a,{boardId:s.source.boardId,peerId:s.target.boardId,edges:[s]})}return{evidence:i,pairs:t,internal:n,missing:o}}function lp(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return(t>>>0)/4294967296}function MT(e,t){let n=new Map(e.map((i)=>[i,new Map])),o=t.filter((i)=>i.from!==i.to&&n.has(i.from)&&n.has(i.to)).map((i)=>({ends:[i.from,i.to].sort(),weight:Math.max(0.1,i.weight??1)})).sort((i,s)=>i.ends[0].localeCompare(s.ends[0])||i.ends[1].localeCompare(s.ends[1])||i.weight-s.weight);for(let{ends:[i,s],weight:a}of o)n.get(i).set(s,(n.get(i).get(s)??0)+a),n.get(s).set(i,(n.get(s).get(i)??0)+a);return n}function zT(e,t,n,o){let i=t.get(e),s=[...o.values()].reduce((c,u)=>c+Math.sqrt(u),0),a=0,l=0;for(let c of n){if(c===e)continue;let u=t.get(c),d=i.x-u.x||(lp(e)-0.5)*0.01,p=i.y-u.y||(lp(`${e}:y`)-0.5)*0.01,f=Math.max(1,Math.hypot(d,p)),m=14000/(f*f),h=o.get(c)??0,g=h?(f-290)*0.006*Math.sqrt(h)/s:0;a+=d/f*(m-g),l+=p/f*(m-g);let v=Je.width+Je.gap,b=(Je.height+Je.gap)*Je.width/Je.height;if(Math.abs(d)<v&&Math.abs(p)<b)if(v-Math.abs(d)<b-Math.abs(p))a+=Math.sign(d)*(v-Math.abs(d))*0.2;else l+=Math.sign(p)*(b-Math.abs(p))*0.2}return{x:a,y:l}}function $T(e,t,n,o){let i=[...e.keys()].sort(),s=MT(i,t),a=Je.width/Je.height,l=new Map([...e].map(([u,d])=>[u,{x:d.x,y:d.y*a}])),c=0;for(let u of i){if(u===n)continue;let d=l.get(u),p=zT(u,l,i,s.get(u)),f=Math.min(1,24/Math.max(1,Math.hypot(p.x,p.y)))*o,m=p.x*f,h=p.y*f/a;e.set(u,{x:d.x+m,y:d.y/a+h}),c=Math.max(c,Math.hypot(m,h))}for(let[u,d]of i.entries())for(let p of i.slice(u+1)){let f=e.get(d),m=e.get(p),h=f.x-m.x,g=f.y-m.y,v=Je.width+Je.gap-Math.abs(h),b=Je.height+Je.gap-Math.abs(g);if(v<=0||b<=0)continue;let x=v<b?{x:(Math.sign(h)||-1)*v,y:0}:{x:0,y:(Math.sign(g)||-1)*b},C=p===n?1:0.5,y=d===n?1:0.5;if(d!==n)e.set(d,{x:f.x+x.x*C,y:f.y+x.y*C});if(p!==n)e.set(p,{x:m.x-x.x*y,y:m.y-x.y*y});c=Math.max(c,Math.hypot(x.x,x.y))}return c}function LT(e,t,n){let o=[...new Set(e.map((y)=>y.key))].sort();if(o.every((y)=>n.has(y)))return new Map(o.map((y)=>[y,n.get(y)]));let i=MT(o,t),s=[],a=new Set;for(let y of o){if(a.has(y))continue;let k=[y];a.add(y);for(let _ of k)for(let I of i.get(_).keys()){if(a.has(I))continue;a.add(I),k.push(I)}s.push(k.sort())}let l=new Map,c=Je.width/Je.height;for(let y of o){let k=n.get(y);if(k)l.set(y,{x:k.x,y:k.y*c})}for(let y of s){if(!y.some((k)=>l.has(k)))l.set(y[0],{x:0,y:0});while(y.some((k)=>!l.has(k)))for(let k of y){if(l.has(k))continue;let _=[...i.get(k).keys()].filter((I)=>l.has(I));if(!_.length)continue;l.set(k,{x:_.reduce((I,w)=>I+l.get(w).x,0)/_.length+(lp(k)-0.5)*240,y:_.reduce((I,w)=>I+l.get(w).y,0)/_.length+(lp(`${k}:y`)-0.5)*240})}for(let k=0;k<180;k++){let _=new Map;for(let I of y){if(n.has(I))continue;let w=l.get(I),{x:P,y:L}=zT(I,l,y,i.get(I)),N=Math.min(1,24/Math.max(1,Math.hypot(P,L)))*(1-k/200);_.set(I,{x:w.x+P*N,y:w.y+L*N})}for(let[I,w]of _)l.set(I,w)}}for(let[y,k]of l)l.set(y,n.get(y)??{x:k.x,y:k.y/c});let u=o.filter((y)=>n.has(y)).map((y)=>l.get(y)),d=Je.width+Je.gap,p=Je.height+Je.gap,f=(y,k)=>Math.abs(y.x-k.x)<d&&Math.abs(y.y-k.y)<p,m=0,h=0,g=0,v=0,b=Math.sqrt(o.length)*380,x=(y)=>y.some((k)=>n.has(k));s.sort((y,k)=>Number(x(k))-Number(x(y)));let C=!1;for(let y of s){let k=x(y);if(!k&&!C)m=u.length?Math.max(...u.map((w)=>w.x))+340:0,h=m,C=!0;let _=k?u:[],I=[];for(let w of y){if(n.has(w))continue;let P=l.get(w),L=P;if(_.some((N)=>f(L,N)))L=_.flatMap((Y)=>[{x:Y.x-d,y:P.y},{x:Y.x+d,y:P.y},{x:P.x,y:Y.y-p},{x:P.x,y:Y.y+p}]).filter((Y)=>!_.some((B)=>f(Y,B))).sort((Y,B)=>Math.hypot(Y.x-P.x,Y.y-P.y)-Math.hypot(B.x-P.x,B.y-P.y))[0];l.set(w,L),_.push(L),I.push(L)}if(!k&&I.length){let w=Math.min(...I.map((L)=>L.x)),P=Math.min(...I.map((L)=>L.y));for(let L of I)L.x+=h-w,L.y+=g-P;if(u.push(...I),h=Math.max(...I.map((L)=>L.x))+340,v=Math.max(v,Math.max(...I.map((L)=>L.y))-g+200),h-m>b)h=m,g+=v,v=0}}for(let[y,k]of l)if(!n.has(y))n.set(y,k);return l}var OT={portal:"Portals",wiki:"Wiki links",card:"Card relations",previous:"Previous boards"},Eg=(e)=>({scene:e,camera:null,query:"",context:!1,folders:new Set,hiddenLinks:new Set,inspection:null,limit:80});function DT(){let e=Ge.value,{graph:t,loading:n,error:o,retry:i}=ap("full"),[s,a]=E([Eg({kind:"overview"})]),l=s.at(-1),c=l.scene,u=ls(c),[d,p]=E(!1),[f,m]=E(0),[h,g]=E(0),[v,b]=E(null),[x,C]=E(""),[y,k]=E({width:0,height:0}),_=D(new Map),I=D(null),w=D(null),P=D(null),L=D(null),N=()=>{if(P.current!==null)cancelAnimationFrame(P.current);P.current=null,L.current=null},Y=D(!1),B=(S)=>a((K)=>[...K.slice(0,-1),{...K.at(-1),...S}]),J=()=>{a((S)=>S.length>1?S.slice(0,-1):S),p(!1),b(null),C("")},X=(S)=>{if(ls(S)===u){m((K)=>K+1);return}a((K)=>[...K,Eg(S)]),p(!1),b(null),C("")},V=(S)=>{let K=s.map((ue)=>ls(ue.scene)).lastIndexOf(ls(S));if(K>=0)a((ue)=>ue.slice(0,K+1));else X(S);p(!1)};Me(()=>{ut.value=!0},[]),Me(()=>{let S=I.current,K=()=>k({width:S.clientWidth,height:S.clientHeight}),ue=new ResizeObserver(K);return ue.observe(S),K(),()=>ue.disconnect()},[]),Me(()=>{let S=(K)=>{if(!ir(K))return;if(l.inspection||s.length>1)if(K.preventDefault(),l.inspection)B({inspection:null});else J()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[l.inspection,s.length]);let ee=Ke(()=>(t?.nodes??[]).map((S)=>{let K=e.find((ue)=>ue.id===S.boardId);return K?{...S,folder:K.folder,...S.kind==="board"?{title:K.name,nodeCount:K.nodeCount,inContext:!!K.pin}:{}}:S}),[t,e]),he=Ke(()=>new Map(ee.map((S)=>[S.key,S])),[ee]),A=Ke(()=>NT(t?.edges??[]),[t]),te=c.kind==="overview"?null:Mt(c),M=te?he.get(te):void 0,O=(S)=>e.find((K)=>K.id===S)?.name??S,Pe=(S)=>c.kind!=="overview"&&S.boardId===c.boardId,Fe=c.kind==="overview"?A.evidence:A.evidence.filter((S)=>c.kind==="board"?S.source.boardId===c.boardId||S.target.boardId===c.boardId:S.from===te||S.to===te),De=Ke(()=>{if(c.kind==="overview")return{nodes:ee.filter((ue)=>ue.kind==="board"),links:[...A.pairs].map(([ue,$e])=>({id:ue,from:Mt({boardId:$e.boardId}),to:Mt({boardId:$e.peerId}),edges:$e.edges,bundle:!0}))};let S=new Set;if(c.kind==="board"){for(let ue of ee)if(Pe(ue)&&ue.kind==="card")S.add(ue.key)}else if(te&&he.has(te))S.add(te);let K=new Map;for(let ue of Fe){if(ue.missing||!he.has(ue.from)||!he.has(ue.to))continue;let $e=c.kind==="board"&&ue.source.boardId!==c.boardId?Mt({boardId:ue.source.boardId}):ue.from,je=c.kind==="board"&&ue.target.boardId!==c.boardId?Mt({boardId:ue.target.boardId}):ue.to;S.add($e),S.add(je);let le=c.kind==="card"?ue.id:JSON.stringify([$e,je].sort()),we=K.get(le);if(we)we.edges.push(ue),we.bundle=!0;else K.set(le,{id:le,from:$e,to:je,edges:[ue],bundle:$e!==ue.from||je!==ue.to})}return{nodes:ee.filter((ue)=>S.has(ue.key)),links:[...K.values()]}},[ee,t,u]),Ae=new Map;for(let S of De.links)for(let K of[S.from,S.to])Ae.set(K,(Ae.get(K)??0)+S.edges.length);let ve=De.nodes.filter((S)=>Ae.has(S.key)||S.key===te),z=De.nodes.filter((S)=>!Ae.has(S.key)&&S.key!==te),re=(S)=>S.key===te||(!l.context||S.inContext)&&!l.folders.has(S.folder?.split("/")[0]??"")&&`${S.title} ${S.summary} ${O(S.boardId)} ${S.folder??""}`.toLocaleLowerCase().includes(l.query.trim().toLocaleLowerCase()),Ne=ve.filter(re).sort((S,K)=>Number(K.key===te)-Number(S.key===te)||(Ae.get(K.key)??0)-(Ae.get(S.key)??0)||S.key.localeCompare(K.key)),ke=Ne.slice(0,l.limit),ae=new Set(ke.map((S)=>S.key)),Se=z.filter(re),de=De.links.map((S)=>({...S,edges:S.edges.filter((K)=>!l.hiddenLinks.has(K.kind))})).filter((S)=>S.edges.length&&ae.has(S.from)&&ae.has(S.to));q(()=>()=>{N(),Y.current||=!!w.current?.moved,w.current=null},[De,l.limit,l.query,l.context,l.folders,l.hiddenLinks]);let Ue=(S)=>{if(P.current!==null)return;let K=180,ue=()=>{let $e=w.current?.key===S,je=_.current.get(u);if(L.current)je.set(S,L.current);L.current=null;let le=new Map(ke.map((ge)=>[ge.key,je.get(ge.key)])),we=$T(le,de.map((ge)=>({...ge,weight:ge.edges.length})),S,$e?1:K/180);for(let[ge,Le]of le)je.set(ge,Le);if(g((ge)=>ge+1),$e||--K>0&&we>0.02)P.current=requestAnimationFrame(ue);else P.current=null};P.current=requestAnimationFrame(ue)},xe=Ke(()=>{let S=_.current.get(u);if(!S)S=new Map,_.current.set(u,S);if(c.kind!=="card")return LT(ve,De.links.map((ge)=>({...ge,weight:ge.edges.length})),S);if(!S.has(te))S.set(te,{x:0,y:0});let K=Fe.filter((ge)=>ge.kind!=="card"||mo({kind:ge.relationKind,type:ge.type},e.find((Le)=>Le.id===ge.source.boardId)?.relationVocabulary).directed),ue=new Set(K.filter((ge)=>ge.to===te).map((ge)=>ge.from)),$e=new Set(K.filter((ge)=>ge.from===te).map((ge)=>ge.to)),je=ve.filter((ge)=>ge.key!==te).sort((ge,Le)=>ge.key.localeCompare(Le.key)),le=Je.width+Je.gap,we=Je.height+Je.gap;for(let ge of["incoming","outgoing","mutual"]){let Le=je.filter((on)=>(ue.has(on.key)&&!$e.has(on.key)?"incoming":$e.has(on.key)&&!ue.has(on.key)?"outgoing":"mutual")===ge),Rt=Le.filter((on)=>S.has(on.key)).map((on)=>S.get(on.key)),pt=S.get(te).y+we,pn=0;for(let[on,fs]of Le.entries())if(!S.has(fs.key)){let Pn=Rt.length?Math.max(...Rt.map((fn)=>ge==="mutual"?fn.x:fn.y))+(pn+1)*(ge==="mutual"?le:we):(on-(Le.length-1)/2)*(ge==="mutual"?le:we),xn=ge==="mutual"?{x:Pn,y:pt}:{x:ge==="incoming"?-360:360,y:Pn};while([...S.values()].some((fn)=>Math.abs(fn.x-xn.x)<le&&Math.abs(fn.y-xn.y)<we))xn.y+=we;S.set(fs.key,xn),pn++}}return new Map(S)},[De,u,h]),qe=(S)=>S.bundle?`${S.edges.length} links`:S.edges[0].kind==="card"?mo({kind:S.edges[0].relationKind,type:S.edges[0].type},e.find((K)=>K.id===S.edges[0].source.boardId)?.relationVocabulary).kind:S.edges[0].kind,W=Ke(()=>PT(new Map(ke.map((S)=>[S.key,xe.get(S.key)])),de.map((S)=>({...S,label:S.edges.length>1||c.kind==="card"?qe(S):""})).sort((S,K)=>S.id.localeCompare(K.id))),[xe,De,l.limit,l.query,l.context,l.folders,l.hiddenLinks]),ye=l.camera??{x:0,y:0,scale:1},He=ke.filter((S)=>{let K=xe.get(S.key);return(K.x-Je.width/2)*ye.scale+ye.x<8||(K.x+Je.width/2)*ye.scale+ye.x>y.width-8||(K.y-Je.height/2)*ye.scale+ye.y<(c.kind==="card"?40:8)||(K.y+Je.height/2)*ye.scale+ye.y>y.height-64}).length,R=(S=!1)=>{let K=I.current;if(!K||!ke.length)return;let ue=c.kind==="card"?40:16,$e=K.clientHeight-ue-64-8,je=ke.flatMap((pt)=>{let pn=xe.get(pt.key);return[{x:pn.x-Je.width/2,y:pn.y-Je.height/2},{x:pn.x+Je.width/2,y:pn.y+Je.height/2}]});for(let pt of W.values())if(je.push(...pt.points),pt.label)je.push({x:pt.label.left,y:pt.label.top},{x:pt.label.right,y:pt.label.bottom});let le=Math.min(...je.map((pt)=>pt.x)),we=Math.min(...je.map((pt)=>pt.y)),ge=Math.max(...je.map((pt)=>pt.x))-le,Le=Math.max(...je.map((pt)=>pt.y))-we,Rt=Math.min(1,Math.max(S?1:0.005,Math.min((K.clientWidth-64)/ge,$e/Le)));B({camera:S&&c.kind==="card"?{x:K.clientWidth/2-xe.get(te).x,y:ue+$e/2-xe.get(te).y,scale:1}:{x:(K.clientWidth-ge*Rt)/2-le*Rt,y:ue+($e-Le*Rt)/2-we*Rt,scale:Rt}})};Me(()=>{if(t&&!l.camera&&ke.length)R(!0)},[t,u,l.camera]),q(()=>{if(!t||c.kind==="overview"||M)return;let S=he.has(Mt({boardId:c.boardId}));a((K)=>{let ue=K.filter((je)=>je.scene.kind==="overview"||he.has(Mt(je.scene))),$e=c.kind==="card"&&S?{kind:"board",boardId:c.boardId}:{kind:"overview"};return ls(ue.at(-1).scene)===ls($e)?ue:[...ue,Eg($e)]}),C("The focused endpoint was removed. Returned to its nearest available level.")},[t,te,M]);let ne=(S)=>{let K=xe.get(S.key),ue=I.current;if(!K||!ue)return;let $e=Math.max(1,ye.scale);B({camera:{x:ue.clientWidth/2-K.x*$e,y:ue.clientHeight/2-K.y*$e-20,scale:$e},limit:Math.max(l.limit,Ne.indexOf(S)+1)}),p(!1)},Ce=(S)=>{if(S.kind==="card"&&S.cardId)X({kind:"card",boardId:S.boardId,cardId:S.cardId});else X({kind:"board",boardId:S.boardId})},Te=(S,K)=>{let ue=I.current;if(!ue)return;let $e=K??{x:ue.clientWidth/2,y:ue.clientHeight/2},je=Math.max(0.005,Math.min(3,S));B({camera:{x:$e.x-($e.x-ye.x)*je/ye.scale,y:$e.y-($e.y-ye.y)*je/ye.scale,scale:je}})},fe=De.links.find((S)=>S.id===l.inspection),it=fe?.edges??Fe,Ht=M?e.find((S)=>S.id===M.boardId):void 0,Ye=(S)=>{B({inspection:S.id}),m((K)=>K+1)},Lt=(S,K,ue)=>r("label",{class:"home-memory-check",children:[r("input",{type:"checkbox","aria-label":S,checked:K,onChange:ue},void 0,!1,void 0,this),r("span",{children:S},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F=c.kind!=="overview"&&!M,Ie=c.kind==="overview"?"Library":c.kind==="board"?O(c.boardId):M?.title??"Missing card";return r("main",{class:`home-memory graph-view${d?" sidebar-open":""}`,"aria-label":"Library Graph",style:{"--graph-node-width":`${Je.width}px`,"--graph-node-height":`${Je.height}px`},children:[r("div",{class:"home-memory-toolbar",children:[s.length>1&&r("button",{type:"button",class:"home-button",onClick:J,children:"Back"},void 0,!1,void 0,this),r("nav",{class:"graph-breadcrumb","aria-label":"Graph path",children:[r("button",{type:"button",class:"home-button",onClick:()=>V({kind:"overview"}),children:"Library"},void 0,!1,void 0,this),c.kind!=="overview"&&r(be,{children:[r("span",{children:"›"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>V({kind:"board",boardId:c.boardId}),children:O(c.boardId)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c.kind==="card"&&r(be,{children:[r("span",{children:"›"},void 0,!1,void 0,this),r("strong",{children:Ie},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("span",{children:[ke.length," of ",ve.length," connected drawn · ",He," partly/outside view ·"," ",ve.length-Ne.length," filtered · ",Math.max(0,Ne.length-ke.length)," hidden ·"," ",z.length," without links"]},void 0,!0,void 0,this),Ne.length>l.limit&&r("button",{type:"button",class:"home-button",onClick:()=>B({limit:l.limit+80}),children:"Show more connections"},void 0,!1,void 0,this),r("span",{class:`home-memory-live${o?" is-error":""}`,role:"status",children:o?"Update failed":n?"Updating…":"Live"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button home-memory-sidebar-toggle","aria-expanded":d,onClick:()=>p(!d),children:"Filters"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-body",children:[r("div",{class:"home-memory-stage",ref:I,"aria-label":"Pan the memory view",onWheel:(S)=>{S.preventDefault();let K=S.currentTarget.getBoundingClientRect();Te(ye.scale*Math.exp(-S.deltaY*0.0015),{x:S.clientX-K.left,y:S.clientY-K.top})},onPointerDown:(S)=>{if(S.button!==0||S.target.closest('button, [role="button"]'))return;N(),Y.current=!1,w.current={id:S.pointerId,start:{x:S.clientX,y:S.clientY},origin:ye,moved:!1},S.currentTarget.setPointerCapture(S.pointerId)},onPointerMove:(S)=>{let K=w.current;if(!K||K.id!==S.pointerId||!(S.buttons&1))return;let ue=S.clientX-K.start.x,$e=S.clientY-K.start.y;if(Math.abs(ue)+Math.abs($e)>4)K.moved=!0;if(!K.moved)return;let je={x:K.origin.x+ue/(K.key?ye.scale:1),y:K.origin.y+$e/(K.key?ye.scale:1)};if(K.key)L.current=je,Ue(K.key);else B({camera:{...je,scale:ye.scale}})},onPointerUp:()=>{if(!w.current)return;Y.current=w.current.moved,w.current=null},onPointerCancel:()=>{let S=w.current;if(N(),S?.layout)_.current.set(u,S.layout),g((K)=>K+1);else if(S)B({camera:{...S.origin,scale:ye.scale}});Y.current=!!S?.moved,w.current=null},children:[c.kind==="card"&&r("div",{class:"graph-direction-caption",children:"Incoming starts left · outgoing starts right · drag to rearrange"},void 0,!1,void 0,this),r("div",{class:"home-memory-world",style:{transform:`translate(${ye.x}px, ${ye.y}px) scale(${ye.scale})`},children:[r("svg",{class:"home-memory-links graph-links","aria-label":"Graph connections",children:de.map((S,K)=>{let ue=W.get(S.id);if(!ue)return null;let $e=S.edges[0],je=mo({kind:$e.relationKind,type:$e.type},e.find((Le)=>Le.id===$e.source.boardId)?.relationVocabulary),le=!S.bundle&&($e.kind!=="card"||je.directed),we=S.bundle?"var(--c-muted)":$e.kind==="card"?`var(--c-rel-${je.ink})`:$e.kind==="wiki"?"var(--c-rel-cites)":"var(--c-rel-derived)",ge=`${S.edges.length} ${S.bundle?"links":"link"} between ${he.get(S.from)?.title} and ${he.get(S.to)?.title}`;return r("g",{class:`graph-link${S.bundle?" is-bundle":" is-exact"}${S.from===v||S.to===v?" is-highlighted":""}${l.inspection===S.id?" is-selected":""}`,"data-from":S.from,"data-to":S.to,"data-count":S.edges.length,"data-link-id":S.id,role:"button",tabindex:0,"aria-label":`Inspect ${ge}`,style:{stroke:we},onClick:()=>Ye(S),onKeyDown:(Le)=>{if(Le.key==="Enter"||Le.key===" ")Le.preventDefault(),Ye(S)},children:[r("defs",{children:r("marker",{id:`graph-arrow-${K}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto",children:r("path",{d:"M 0 0 L 10 5 L 0 10 z",style:{fill:we,stroke:"none"}},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("path",{class:"graph-link-hit",d:ue.path},void 0,!1,void 0,this),r("path",{class:"graph-link-line",d:ue.path,"marker-end":le?`url(#graph-arrow-${K})`:void 0},void 0,!1,void 0,this),ue.label&&(S.edges.length>1||c.kind==="card")&&r("text",{x:ue.label.x,y:ue.label.y,children:qe(S)},void 0,!1,void 0,this)]},S.id,!0,void 0,this)})},void 0,!1,void 0,this),ke.map((S,K)=>{let ue=xe.get(S.key),$e=e.find((le)=>le.id===S.boardId),je=S.kind==="board"?S.inContext:!!$e?.pinnedTitles?.some((le)=>le.nodeId===S.cardId)||S.inContext&&!$e?.pin;return r("article",{"data-key":S.key,class:`graph-node is-${S.kind}${te===S.key?" is-selected":""}${je?" in-context":""}${c.kind!=="overview"&&!Pe(S)?" is-external":""}`,style:{left:ue.x,top:ue.y},onPointerEnter:()=>b(S.key),onPointerLeave:()=>b(null),children:r("button",{type:"button",class:"home-memory-select","aria-label":`${S.kind}: ${S.title}`,"aria-pressed":te===S.key,onClick:()=>{if(!Y.current)Ce(S);Y.current=!1},onPointerDown:(le)=>{if(le.button!==0)return;le.stopPropagation(),N(),Y.current=!1,w.current={id:le.pointerId,start:{x:le.clientX,y:le.clientY},origin:ue,key:S.key,layout:new Map(_.current.get(u)),moved:!1},le.currentTarget.setPointerCapture(le.pointerId)},onKeyDown:(le)=>{if(!le.key.startsWith("Arrow"))return;le.preventDefault();let we=(K+(le.key==="ArrowLeft"||le.key==="ArrowUp"?-1:1)+ke.length)%ke.length,ge=ke[we];if(ge)ne(ge),I.current?.querySelectorAll(".home-memory-select")[we]?.focus({preventScroll:!0})},children:[r("span",{class:"graph-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("strong",{children:S.title},void 0,!1,void 0,this),r("span",{children:S.kind==="board"?`${S.nodeCount??0} cards · ${A.internal.get(S.boardId)??0} internal`:`${O(S.boardId)} · ${S.type??"card"}`},void 0,!1,void 0,this),r("span",{class:je?"memory-context-legend":"",children:je?"⌖ In context":S.folder||"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},S.key,!1,void 0,this)})]},void 0,!0,void 0,this),r("div",{class:"home-memory-zoom",children:[r("button",{type:"button",class:"home-button","aria-label":"Zoom out",onClick:()=>Te(ye.scale/1.2),children:"−"},void 0,!1,void 0,this),r("span",{children:[Math.round(ye.scale*100),"%"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button","aria-label":"Zoom in",onClick:()=>Te(ye.scale*1.2),children:"+"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>R(),children:"Fit view"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(x||F||!t||!ke.length||o)&&r("div",{class:"home-memory-status",role:"status",children:x||(F?"This endpoint is no longer available. Use Back to return.":o?r(be,{children:["Memory update failed."," ",r("button",{type:"button",class:"home-button",onClick:i,children:"Retry"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):!t?"Loading memory…":Se.length?"No linked nodes in this view. Choose a node in No connections below.":"No matching nodes.")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("aside",{class:"home-memory-sidebar","aria-label":"Graph settings",children:[r("section",{children:[r("h2",{children:c.kind==="overview"?"Find boards":"Find cards and neighbors"},void 0,!1,void 0,this),r("label",{class:"home-memory-search",children:[r("span",{children:"Search graph"},void 0,!1,void 0,this),r("input",{type:"search",value:l.query,placeholder:"Search this graph…",onInput:(S)=>B({query:S.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),l.query&&r("ul",{class:"graph-search-results",children:[...ve,...z].filter(re).slice(0,30).map((S)=>r("li",{children:r("button",{type:"button",class:"home-button",onClick:()=>{if(Ae.has(S.key)||S.key===te)ne(S);else Ce(S)},children:S.title},void 0,!1,void 0,this)},S.key,!1,void 0,this))},void 0,!1,void 0,this),Lt("Only in context",l.context,()=>B({context:!l.context}))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Folders"},void 0,!1,void 0,this),[...new Set(De.nodes.map((S)=>S.folder?.split("/")[0]??""))].sort().map((S)=>r("div",{children:Lt(S||"Unfiled",!l.folders.has(S),()=>{let K=new Set(l.folders);if(K.has(S))K.delete(S);else K.add(S);B({folders:K})})},S,!1,void 0,this))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Links"},void 0,!1,void 0,this),Object.keys(OT).map((S)=>r("div",{children:Lt(OT[S],!l.hiddenLinks.has(S),()=>{let K=new Set(l.hiddenLinks);if(K.has(S))K.delete(S);else K.add(S);B({hiddenLinks:K})})},S,!1,void 0,this))]},void 0,!0,void 0,this),r("section",{children:[r("h2",{children:"Library evidence"},void 0,!1,void 0,this),r("p",{class:"graph-accounting",children:[A.evidence.length," links ·"," ",[...A.pairs.values()].reduce((S,K)=>S+K.edges.length,0)," between boards ·"," ",[...A.internal.values()].reduce((S,K)=>S+K,0)," inside boards ·"," ",A.missing.length," missing"]},void 0,!0,void 0,this),r("p",{class:"home-memory-help",children:"Counts retain original evidence. Folder membership is not a relation. Filters change the drawing, not the totals."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Se.length>0&&r("details",{class:"graph-unlinked",open:!0,children:[r("summary",{children:["No connections (",Se.length,")"]},void 0,!0,void 0,this),r("div",{children:Se.map((S)=>r("button",{type:"button",class:"home-button graph-tray-node","aria-label":`${S.kind}: ${S.title}`,onClick:()=>Ce(S),children:[S.title,r("small",{children:S.kind==="board"?`${S.nodeCount??0} cards`:O(S.boardId)},void 0,!1,void 0,this)]},S.key,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-legend","aria-label":"Legend",children:[r("span",{children:"Click nodes to drill · drag nodes to rearrange · lines for evidence · drag background to pan · scroll to zoom · Fit shows extent · search reveals at readable size"},void 0,!1,void 0,this),r("span",{class:"memory-context-legend",children:"⌖ In context"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(sp,{initiallyCollapsed:!0,reveal:f,children:M||fe?r("section",{class:"home-memory-details",role:"complementary","aria-label":"Selection details",children:[fe&&r("button",{type:"button",class:"home-memory-clear","aria-label":"Close details",onClick:()=>B({inspection:null}),children:"×"},void 0,!1,void 0,this),r("div",{class:"home-memory-detail-header",children:[r("div",{class:"home-memory-selection-title",children:[r("h3",{children:[fe?`${he.get(fe.from)?.title} ↔ ${he.get(fe.to)?.title}`:Ie," ·"," ",it.length," connections"]},void 0,!0,void 0,this),r("p",{children:fe?"Original evidence, not a new aggregate relation":`${M?.folder||"Unfiled"} / ${O(M.boardId)}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-actions",children:M&&r(be,{children:[r("button",{type:"button",class:"home-button is-primary",onClick:()=>void zt(M),children:["Open ",M.kind]},void 0,!0,void 0,this),Ht&&r(ho,{board:Ht},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-memory-detail-body",children:[M&&r("p",{class:M.inContext?"memory-context-legend":"",children:[M.inContext?"⌖ In context":"Not in context",M.linksComplete===!1?" · Partial discovery":""]},void 0,!0,void 0,this),r("details",{class:"home-memory-connections",open:!0,children:[r("summary",{children:["Connections",fe?" within this pair":""]},void 0,!0,void 0,this),r("ul",{children:[it.map((S)=>{let K=c.kind==="card"?S.from===te:c.kind==="board"?S.source.boardId===c.boardId:!0,ue=K?S.target:S.source,$e=he.get(Mt(ue)),je=mo({kind:S.relationKind,type:S.type},e.find((we)=>we.id===S.source.boardId)?.relationVocabulary),le=S.kind!=="card"||je.directed;return r("li",{children:[r("span",{children:[le?K?"→":"←":"↔"," ",S.kind==="card"?ha({...S,kind:S.relationKind}):`${S.kind}${S.label?` · ${S.label}`:""}`]},void 0,!0,void 0,this),r("small",{children:[he.get(S.from)?.title??S.source.cardId??O(S.source.boardId)," ",le?"→":"↔"," ",he.get(S.to)?.title??S.target.cardId??O(S.target.boardId)," ·"," ",O(ue.boardId)]},void 0,!0,void 0,this),!$e||S.missing?r("span",{class:"home-memory-missing",children:["⚠ Missing target: ",ue.boardId,ue.cardId?` / ${ue.cardId}`:""]},void 0,!0,void 0,this):r("button",{type:"button",class:"home-button",onClick:()=>Ce($e),children:["Follow ",$e.title]},void 0,!0,void 0,this)]},S.id,!0,void 0,this)}),(t?.unresolvedLinks??[]).filter((S)=>c.kind==="board"?S.source.boardId===c.boardId:Mt(S.source)===te).map((S)=>r("li",{class:"home-memory-missing",children:["⚠ Unresolved wiki: [[",S.ref,"]]"]},`${Mt(S.source)}:${S.ref}`,!0,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):r("div",{class:"home-memory-empty-details",children:[r("h3",{children:"Connections"},void 0,!1,void 0,this),r("p",{class:"home-memory-help",children:"Click a board to explore, then a card to see its exact neighbors. Click a connection line to read the original evidence. Open content is always separate."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},"inspector",!1,void 0,this)]},void 0,!0,void 0,this)}function BT({folder:e,folders:t,onScopeChange:n}){let[o,i]=E(""),[s,a]=E(!1),[l,c]=E(null),[u,d]=E(""),p=Oe.value;q(()=>{if(p)Kt()},[p]),Me(()=>{let C=(y)=>{if(!Oe.value)return;if(!ir(y))return;y.preventDefault(),i(""),a(!1)};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[]);let f=Xn.value,m=(C)=>!e||C===e||!!C?.startsWith(`${e}/`),h=(f?.reviewCards??[]).filter((C)=>m(C.folder)),g=o.trim().toLocaleLowerCase(),v=h.filter((C)=>{let y=f?.cards[Mt(C)];return y&&(!s||y.sources.length>0)&&(!g||`${C.title} ${C.boardTitle} ${y.reasons.join(" ")} ${y.sources.map((k)=>k.title).join(" ")}`.toLocaleLowerCase().includes(g))}),b=new Set(Ge.value.filter((C)=>m(C.folder)).map((C)=>C.id)),x=Object.entries(f?.cards??{}).filter(([C,y])=>!y.retired&&y.unknown&&b.has(JSON.parse(C)[0])).length;if(!p)return null;return r("section",{class:"home-review-view","aria-label":"Card review queue",children:[r("div",{class:"home-main-head",children:[r("div",{class:"home-main-title",children:[r("h1",{class:"home-view-title",children:"Knowledge review"},void 0,!1,void 0,this),r("p",{children:e?`${e} and descendants`:"Whole library"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Review scope",r("select",{value:e,onChange:(C)=>n(C.currentTarget.value),children:[r("option",{value:"",children:"Whole library"},void 0,!1,void 0,this),t.map((C)=>r("option",{value:C,children:[C," and descendants"]},C,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"home-review-controls",children:[r("label",{children:["Find review cards",r("input",{type:"search",value:o,onInput:(C)=>i(C.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:s,onChange:(C)=>a(C.currentTarget.checked)},void 0,!1,void 0,this),"Source warnings only"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button",onClick:()=>void Kt(),children:"Refresh queue"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Oi.value&&r("p",{role:"status",children:"Queue unavailable. Retained results may be out of date. Refresh to retry."},void 0,!1,void 0,this),u&&r("p",{role:"alert",children:u},void 0,!1,void 0,this),!f?r("p",{children:"Loading review cards…"},void 0,!1,void 0,this):r(be,{children:[r("p",{class:"home-review-count",children:["Review needed: ",h.length," ",h.length===1?"card":"cards"," · Showing ",v.length]},void 0,!0,void 0,this),r("table",{class:"home-review-table",children:[r("thead",{children:r("tr",{children:[r("th",{children:"Card"},void 0,!1,void 0,this),r("th",{children:"Board"},void 0,!1,void 0,this),r("th",{children:"Why review"},void 0,!1,void 0,this),r("th",{children:"Last checked"},void 0,!1,void 0,this),r("th",{children:"Open"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r("tbody",{children:v.map((C)=>{let y=Mt(C),k=f.cards[y],_=[...k.reasons,...k.sources.map((I)=>`${I.title}: ${I.reasons.join(" ")||"Source needs review."}`)];return r("tr",{children:[r("td",{"data-label":"Card",children:C.title},void 0,!1,void 0,this),r("td",{"data-label":"Board",children:C.boardTitle},void 0,!1,void 0,this),r("td",{"data-label":"Why review",children:_.join(" ")||"A source needs review."},void 0,!1,void 0,this),r("td",{"data-label":"Last checked",children:k.lastValidatedAt?new Date(k.lastValidatedAt).toLocaleString():"Never checked"},void 0,!1,void 0,this),r("td",{children:r("button",{type:"button",class:"home-button",disabled:l===y,"aria-label":`Open review: ${C.title} on ${C.boardTitle}`,onClick:async()=>{if(!Oe.value)return;c(y),d("");let I=await zt(C,{review:!0});if(c(null),!I)d("Review did not open. The card may have moved or navigation was cancelled. Refresh and try again.")},children:"Open review"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},y,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v.length===0&&r("p",{children:"No actionable cards in these filters."},void 0,!1,void 0,this),r("p",{class:"home-review-neutral",children:["No review policy: ",x," ",x===1?"card":"cards",". Missing policy is neutral, not overdue. Explicit content or source warnings still enter the queue."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var TL=Pi({decayType:mn(["reality","decision","dependency","relevance"]),rate:mn(["fast","medium","slow","durable"]),triggers:We(U().trim().min(1)),revalidationMethod:U().trim().min(1),cadenceDays:Ze().int().min(1).max(36500).optional()}).refine((e)=>e.rate!=="medium"||e.cadenceDays!==void 0,{path:["cadenceDays"],message:"Medium lifecycle requires a cadence in days."}),FT=TL.safeExtend({id:U().trim().min(1),name:U().trim().min(1),glyph:U().trim().min(1)});var sr=(e,t,n,o,i,s)=>({id:e,name:t,glyph:n,decayType:o,rate:i,revalidationMethod:s,triggers:[],...i==="medium"?{cadenceDays:90}:{}}),HT=sr("research","Research","⌕","reality","medium","Check the sources and conflicting evidence."),UT=sr("metric","Metric","▥","reality","fast","Re-read the source dashboard and compare."),jT=sr("decision","Decision","⚑","decision","durable","Check for a superseding decision and changed dependencies."),ZT=sr("notes","Notes","✎","relevance","slow","Check relevance to the resumed task."),cp={"Org · team · personal":{categories:[sr("strategy","Strategy","◎","relevance","slow","Check the current goals and decisions."),sr("policy","Policy","◇","decision","slow","Check with the policy owner."),jT,HT,UT,ZT],folders:{Org:"strategy","Org/Policies":"policy",Team:"research","Team/Decisions":"decision","Team/Metrics":"metric",Personal:"notes"}},"Solo research":{categories:[sr("question","Question","?","relevance","slow","Check whether this question still matters."),sr("source","Source","▤","reality","medium","Re-read the original source."),sr("finding","Finding","◉","dependency","durable","Compare the supporting and contradicting evidence."),sr("note","Note","✎","relevance","slow","Check relevance to the resumed task.")],folders:{Projects:"question","Projects/Findings":"finding",Sources:"source",Notes:"note"}},"Product team":{categories:[HT,UT,jT,ZT],folders:{Discovery:"research","Discovery/Metrics":"metric",Delivery:"notes",Decisions:"decision"}},Empty:{categories:[],folders:{}}};function WT({folder:e,onClose:t}){let n=Oe.value,o=D(null),i=Xn.value,s=i?.folders.find((M)=>M.path===e),a=e?i?.resolvedFolders[e]:null,[l,c]=E(s?.categoryId??""),[u,d]=E(!!s?.lifecycleOverride),[p,f]=E(s?.lifecycleOverride??a?.lifecycle??xa),[m,h]=E(()=>i?.categories[0]?structuredClone(i.categories[0]):null),[g,v]=E(null),b=i?.categories.find((M)=>M.id===m?.id),x=i?.folders.filter((M)=>M.categoryId===m?.id)??[],[C,y]=E(!1),[k,_]=E(""),[I,w]=E(()=>JSON.stringify(m)),[P,L]=E("Basics"),[N,Y]=E(""),[B,J]=E(null),X=!e&&JSON.stringify(m)!==I,V=(M)=>{if(!Oe.value||C||B)return;if(X)J(()=>M);else M()},ee=()=>{if(!Oe.value)return;if(B)J(null);else if(g)v(null);else V(t)};bn(o,n,{onEscape:ee}),Me(()=>{if(!n&&o.current?.contains(document.activeElement))document.querySelector('button[aria-label="Settings"]')?.focus({preventScroll:!0})},[n]),q(()=>{if(n)Kt()},[n]);let he=(M)=>{let O=structuredClone(M);h(O),w(JSON.stringify(O)),L("Basics"),v(null),_("")},A=async(M,O)=>{if(!Oe.value)return!1;return(await pe("knowledgeWrite",`/api/canvas/knowledge/${M}`,null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)}))?.ok===!0},te=async(M)=>{if(!Oe.value||C||!i)return;let O=tn;y(!0),_("");let Pe=!0,Fe=cp[M];for(let De of Fe.categories){if(!Oe.value||O!==tn){Pe=!1;break}if(!i.categories.some((Ae)=>Ae.id===De.id))Pe=await A("category",{category:De});if(!Pe)break}if(Pe)for(let[De,Ae]of Object.entries(Fe.folders)){if(!Oe.value||O!==tn){Pe=!1;break}if(!i.folders.some((ve)=>ve.path===De))Pe=await A("folder",{path:De,categoryId:Ae,lifecycleOverride:null});if(!Pe)break}await Kt(),y(!1),_(Pe?M==="Empty"?"No starter data added. Existing data is unchanged.":"Starter data added. Existing categories and folder settings were preserved.":"Template stopped at a failed save. Saved entries remain; retry adds only missing entries.")};return r("div",{class:"knowledge-backdrop",hidden:!n,style:n?void 0:{display:"none"},onKeyDown:(M)=>{if(M.key==="Escape")M.stopPropagation(),M.preventDefault(),ee()},children:r("div",{ref:o,class:`knowledge-dialog${e?"":" is-category-editor"}`,role:"dialog","aria-modal":"true","aria-label":e?"Folder settings":"Categories",children:[r("header",{children:[r("div",{class:"knowledge-dialog-title",children:[r("h2",{children:e?`${e.split("/").at(-1)} · Folder settings`:"Workspace categories"},void 0,!1,void 0,this),e&&r("span",{class:"knowledge-folder-path",children:e},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button","aria-label":"Close settings",disabled:C,onClick:()=>V(t),children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k&&r("p",{role:"status",children:k},void 0,!1,void 0,this),B&&r("div",{role:"group","aria-label":"Discard category changes",class:"category-discard",children:[r("p",{children:"Discard unsaved category changes?"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>J(null),children:"Keep editing"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>{if(!Oe.value)return;let M=B;J(null),w(JSON.stringify(m)),M()},children:"Discard changes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),!i?r("p",{children:"Knowledge settings unavailable. Close and retry."},void 0,!1,void 0,this):e?r("form",{onClick:Ho,onSubmit:async(M)=>{if(M.preventDefault(),!Oe.value||C)return;let O=tn;y(!0);let Pe=await A("folder",{path:e,categoryId:l||null,lifecycleOverride:u?Ql(p):null});if(await Kt(),y(!1),Pe&&Oe.value&&O===tn)t();else if(!Pe)_("Folder settings were not saved. Retry.")},children:[r("div",{class:"knowledge-field",children:[r("span",{children:"Category"},void 0,!1,void 0,this),r(Mr,{label:"Category",value:l,onChange:c,options:[{value:"",label:"Use the parent’s"},...i.categories.map((M)=>({value:M.id,label:`${M.glyph} ${M.name}`}))]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:["Currently"," ",a?.category?`${a.category.glyph} ${a.category.name} · ${a.categorySourceFolder===e?"set here":`inherited from ${a.categorySourceFolder}`}`:"unknown",". Cards inherit their category; only lifecycle can be overridden."]},void 0,!0,void 0,this),r("label",{children:[r("input",{type:"checkbox",checked:u,onChange:(M)=>d(M.currentTarget.checked)},void 0,!1,void 0,this)," ","Override lifecycle for this folder"]},void 0,!0,void 0,this),u?r(Yl,{value:p,onChange:f},void 0,!1,void 0,this):r("p",{children:"Lifecycle comes from the selected category or parent. Unknown has no passive expiry."},void 0,!1,void 0,this),r("button",{type:"submit",disabled:C,children:"Save folder settings"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r("details",{class:"category-templates",children:[r("summary",{children:"Add from template"},void 0,!1,void 0,this),r("div",{class:"knowledge-presets",children:Object.entries(cp).map(([M,O])=>r("button",{type:"button",disabled:C||!!B,onClick:()=>V(()=>{if(X)h(b?structuredClone(b):null),w(JSON.stringify(b??null));te(M)}),children:[r("strong",{children:M},void 0,!1,void 0,this),r("span",{children:Object.keys(O.folders).join(" / ")||"No folders or categories"},void 0,!1,void 0,this)]},M,!0,void 0,this))},void 0,!1,void 0,this),r("p",{children:"Templates add missing data. They never replace your existing settings. Rename any category below."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"category-editor-columns",children:[r("section",{class:"category-list-panel",children:[r("h3",{children:[i.categories.length," categories"]},void 0,!0,void 0,this),r("label",{children:["Search categories",r("input",{type:"search",value:N,onInput:(M)=>Y(M.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",disabled:C,onClick:()=>V(()=>he({...xa,id:crypto.randomUUID(),name:"",glyph:"◇"})),children:"Add category"},void 0,!1,void 0,this),r("div",{class:"category-library",role:"group","aria-label":"Workspace categories",children:i.categories.filter((M)=>M.name.toLocaleLowerCase().includes(N.toLocaleLowerCase())).map((M)=>r("button",{type:"button",class:"category-choice",disabled:C,"aria-pressed":m?.id===M.id,onClick:()=>{if(m?.id!==M.id)V(()=>he(M))},children:[r("strong",{children:[M.glyph," ",M.name]},void 0,!0,void 0,this),r("span",{children:[M.decayType," · ",M.rate,M.rate==="medium"&&M.cadenceDays?` · ${M.cadenceDays} days`:""]},void 0,!0,void 0,this)]},M.id,!0,void 0,this))},void 0,!1,void 0,this),r("p",{children:"Folders with no category above them stay unknown. Categories carry no colour."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m&&r("form",{class:"category-inspector",noValidate:!0,onClick:Ho,onSubmit:async(M)=>{if(M.preventDefault(),!Oe.value||C)return;let O=tn,Pe=FT.safeParse({...m,...Ql(m)});if(!Pe.success){let Ae=String(Pe.error.issues[0].path[0]);L(["name","glyph","id"].includes(Ae)?"Basics":"Review policy"),_(Pe.error.issues[0].message),setTimeout(()=>{if(!Oe.value||O!==tn)return;let ve=Ae==="name"?"Name":Ae==="glyph"?"Glyph":Ae==="cadenceDays"?"Cadence in days":"How to check",z=o.current?.querySelectorAll("label");Array.from(z??[]).find((re)=>re.textContent?.trim().startsWith(ve))?.querySelector("input")?.focus()},0);return}y(!0);let Fe=await pe("knowledgeWrite","/api/canvas/knowledge/category",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:Pe.data})}),De=Fe?.ok===!0;if(await Kt(),y(!1),!Oe.value||O!==tn)return;if(De){let Ae=Fe?.category??Pe.data;h(Ae),w(JSON.stringify(Ae))}_(De?"Category saved. Inheriting folders now use these defaults.":"Category was not saved. Retry.")},children:[r("h3",{children:b?"Edit category defaults":"New category"},void 0,!1,void 0,this),r("div",{role:"tablist","aria-label":"Category settings",class:"category-tabs",children:["Basics","Review policy","Usage"].map((M)=>r("button",{type:"button",role:"tab",id:`category-tab-${M.replace(" ","-")}`,"aria-controls":"category-tab-panel","aria-selected":P===M,onClick:()=>L(M),children:M},M,!1,void 0,this))},void 0,!1,void 0,this),r("fieldset",{disabled:C||!!B,id:"category-tab-panel",role:"tabpanel","aria-labelledby":`category-tab-${P.replace(" ","-")}`,class:"category-tab-content",children:[P==="Basics"&&r(be,{children:[r("label",{children:["Name",r("input",{required:!0,value:m.name,onInput:(M)=>h({...m,name:M.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("label",{children:["Glyph",r("input",{required:!0,value:m.glyph,onInput:(M)=>h({...m,glyph:M.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"category-glyph-choices",role:"group","aria-label":"Glyph choices",children:[...new Set(Object.values(cp).flatMap((M)=>M.categories.map((O)=>O.glyph)))].map((M)=>r("button",{type:"button","aria-label":`Choose glyph ${M}`,"aria-pressed":m.glyph===M,onClick:()=>h({...m,glyph:M}),children:M},M,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P==="Review policy"&&r(Yl,{value:m,onChange:(M)=>h({...m,...M})},void 0,!1,void 0,this),P==="Usage"&&r(be,{children:[r("p",{children:"Folders inherit these defaults. Folder settings and card lifecycle overrides remain unchanged. Unknown has no passive expiry."},void 0,!1,void 0,this),x.length===0&&r("p",{children:"No folders assigned."},void 0,!1,void 0,this),b&&(x.length>0?r("p",{children:["Cannot delete: assigned to ",x.map((M)=>M.path).join(", "),". Reassign or clear those folder categories first. Empty folders also count."]},void 0,!0,void 0,this):g===b.id?r("div",{role:"group","aria-label":"Confirm category deletion",children:[r("p",{children:["Delete ",b.name,"? This removes the category from this workspace."]},void 0,!0,void 0,this),r("button",{type:"button",disabled:C,onClick:()=>v(null),children:"Cancel deletion"},void 0,!1,void 0,this),r("button",{type:"button",class:"is-danger",disabled:C,onClick:async()=>{if(!Oe.value||C)return;let M=tn;y(!0);let O=await pe("knowledgeRemove",`/api/canvas/knowledge/category/${encodeURIComponent(b.id)}`,null,{method:"DELETE"});if(await Kt(),y(!1),!Oe.value||M!==tn)return;if(v(null),O?.ok===!0)h(null),w("null");_(O?.ok===!0?"Category deleted.":O?.error??"Category was not deleted. Retry.")},children:"Confirm deletion"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("button",{type:"button",class:"is-danger",disabled:C,onClick:()=>v(b.id),children:"Delete category"},void 0,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("footer",{class:"category-editor-footer",children:[r("button",{type:"button",disabled:C||!!B,onClick:()=>V(t),children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"submit",disabled:C||!!B,children:"Save category"},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)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function qT({onClose:e}){let t=D(null),n=Xn.value?.relationPresets,[o,i]=E(),s=o===void 0?n?.[0]??null:o,[a,l]=E(null),[c,u]=E(null),[d,p]=E(null),[f,m]=E(""),[h,g]=E(!1),[v,b]=E(""),[x,C]=E(!1),y=D(null);q(()=>{if(!d)return;let N=document.activeElement;return y.current?.querySelector("button")?.focus(),()=>{if(N instanceof HTMLElement&&N.isConnected)N.focus()}},[d]);let k=s,_=a!==null&&JSON.stringify(a)!==JSON.stringify(c),I=(N)=>{if(h)return;if(_)p(()=>N);else N()},w=()=>{if(d)p(null);else if(x)C(!1);else I(e)};bn(t,!0,{onEscape:w});let P=(N)=>{i(N?structuredClone(N):null),l(null),u(null),C(!1),b("")},L=(N,Y)=>{if(a)l({...a,vocabulary:a.vocabulary.map((B,J)=>J===N?{...B,...Y}:B)})};return r("div",{class:"knowledge-backdrop",onKeyDown:(N)=>{if(N.key==="Escape")N.preventDefault(),N.stopPropagation(),w()},children:r("div",{ref:t,class:"knowledge-dialog is-category-editor relation-presets-dialog",role:"dialog","aria-modal":"true","aria-label":"Workspace relation presets",children:[r("header",{children:[r("h2",{children:"Workspace relation presets"},void 0,!1,void 0,this),r("button",{type:"button",disabled:h||!!d,"aria-label":"Close relation presets",onClick:()=>I(e),children:"×"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Saved templates are shared across the workspace. Saving does not apply a preset to any board."},void 0,!1,void 0,this),v&&r("p",{role:"status",children:v},void 0,!1,void 0,this),d&&r("div",{ref:y,role:"alertdialog","aria-label":"Discard preset changes","aria-modal":"true",class:"relation-dirty-guard",children:[r("p",{children:"Discard unsaved preset changes?"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>p(null),children:"Keep editing"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>{let N=d;p(null),N()},children:"Discard changes"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{inert:d?!0:void 0,children:!n?r("p",{children:"Relation presets unavailable. Close and retry."},void 0,!1,void 0,this):r("div",{class:"category-editor-columns",children:[r("section",{children:[r("h3",{children:[n.length," presets"]},void 0,!0,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>I(()=>{P(null);let N={id:crypto.randomUUID(),name:"",vocabulary:[]};u(structuredClone(N)),l(N)}),children:"Add preset"},void 0,!1,void 0,this),r("div",{class:"category-library",role:"group","aria-label":"Workspace relation presets",children:n.map((N)=>r("button",{type:"button",class:"category-choice",disabled:h,"aria-pressed":(a?.id??s?.id)===N.id,onClick:()=>I(()=>P(N)),children:[r("strong",{children:N.name},void 0,!1,void 0,this),r("span",{children:N.vocabulary.map((Y)=>Y.kind).join(" · ")||"No relation kinds"},void 0,!1,void 0,this)]},N.id,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("section",{class:"relation-preset-detail",children:a?r("form",{class:"relation-vocabulary",onClick:Ho,onSubmit:async(N)=>{if(N.preventDefault(),h)return;if(new Set(a.vocabulary.map((B)=>B.kind.trim())).size!==a.vocabulary.length){b("Give each relation kind a unique name.");return}g(!0);let Y=await pe("relationPresetWrite","/api/canvas/knowledge/relation-preset",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({preset:a})});if(await Kt(),g(!1),Y?.ok)P(Y.preset);b(Y?.ok?"Preset saved for the workspace. Existing boards are unchanged.":"Preset was not saved. Retry.")},children:[r("h3",{children:s?"Customize shared preset":"New shared preset"},void 0,!1,void 0,this),r("label",{children:["Name",r("input",{required:!0,pattern:".*\\S.*",maxLength:80,disabled:h,value:a.name,onInput:(N)=>l({...a,name:N.currentTarget.value})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("p",{children:"Kinds stay open. Choose meaning ink and direction, not pin, agent or warning colours."},void 0,!1,void 0,this),a.vocabulary.map((N,Y)=>r("div",{class:"vocabulary-row",children:[r("input",{required:!0,pattern:".*\\S.*","aria-label":`Kind ${Y+1}`,maxLength:80,disabled:h,value:N.kind,onInput:(B)=>L(Y,{kind:B.currentTarget.value})},void 0,!1,void 0,this),r("select",{"aria-label":`Ink ${Y+1}`,disabled:h,value:N.ink,onChange:(B)=>L(Y,{ink:B.currentTarget.value}),children:["supports","contradicts","cites","derived","informs","related"].map((B)=>r("option",{children:B},B,!1,void 0,this))},void 0,!1,void 0,this),r("label",{children:[r("input",{type:"checkbox",disabled:h,checked:N.directed,onChange:(B)=>L(Y,{directed:B.currentTarget.checked})},void 0,!1,void 0,this),"Arrow"]},void 0,!0,void 0,this),r("button",{type:"button","aria-label":`Remove kind ${Y+1}`,disabled:h,onClick:()=>l({...a,vocabulary:a.vocabulary.filter((B,J)=>J!==Y)}),children:"×"},void 0,!1,void 0,this)]},Y,!0,void 0,this)),r("button",{type:"button",disabled:h||a.vocabulary.length>=64,onClick:()=>l({...a,vocabulary:[...a.vocabulary,{kind:"",ink:"related",directed:!0}]}),children:"Add kind"},void 0,!1,void 0,this),r("div",{class:"relation-preset-footer",children:[r("button",{type:"submit",disabled:h,children:"Save preset"},void 0,!1,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>I(()=>P(s)),children:"Cancel customization"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):k?r(be,{children:[r("h3",{children:k.name},void 0,!1,void 0,this),r("p",{children:"Saved relations · read-only example"},void 0,!1,void 0,this),r("p",{children:"Use on board replaces only the chosen board’s vocabulary. Matching connections use its ink and direction; connection records are not rewritten."},void 0,!1,void 0,this),r("ul",{class:"relation-preset-preview","aria-label":"Saved relation preview",children:k.vocabulary.map((N)=>r("li",{style:{"--relation-ink":`var(--c-rel-${N.ink})`},children:[r("strong",{children:N.kind},void 0,!1,void 0,this),r("div",{class:"relation-preset-example",children:[r("span",{children:"Example A"},void 0,!1,void 0,this),r("svg",{viewBox:"0 0 120 24","aria-hidden":"true",children:[r("line",{x1:"8",y1:"12",x2:"112",y2:"12",stroke:"currentColor","stroke-width":"2","stroke-dasharray":N.ink==="related"?"3 5":void 0},void 0,!1,void 0,this),N.directed&&r("path",{d:"M 102 6 L 112 12 L 102 18",fill:"none",stroke:"currentColor","stroke-width":"2"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{children:"Example B"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{children:[N.ink," · ",N.directed?"Directed: A → B":"Undirected: A — B"]},void 0,!0,void 0,this)]},N.kind,!0,void 0,this))},void 0,!1,void 0,this),!k.vocabulary.length&&r("p",{children:"No relation kinds. This empty preset can still be used on a board."},void 0,!1,void 0,this),r("div",{class:"relation-preset-footer",children:k&&r(be,{children:[r("label",{children:["Apply saved preset to board",r("select",{"aria-label":"Apply saved preset to board",disabled:h,value:f,onChange:(N)=>m(N.currentTarget.value),children:[r("option",{value:"",children:"Choose a board"},void 0,!1,void 0,this),Ge.value.map((N)=>r("option",{value:N.id,children:N.name},N.id,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"relation-preset-use",disabled:h||!f,onClick:async()=>{if(h||!f)return;g(!0);let N=await vr(f,{relationVocabulary:k.vocabulary});g(!1),b(N?"Preset applied. Connection records and other boards are unchanged.":"Preset was not applied. Retry.")},children:"Use on board"},void 0,!1,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>{u(structuredClone(k)),l(structuredClone(k)),C(!1),b("")},children:"Customize preset"},void 0,!1,void 0,this),x?r("div",{role:"group","aria-label":"Confirm preset deletion",children:[r("p",{children:["Delete ",k.name,"? Boards that used it keep their existing vocabulary."]},void 0,!0,void 0,this),r("button",{type:"button",disabled:h,onClick:()=>C(!1),children:"Cancel deletion"},void 0,!1,void 0,this),r("button",{type:"button",class:"is-danger",disabled:h,onClick:async()=>{if(h)return;g(!0);let N=await pe("relationPresetRemove",`/api/canvas/knowledge/relation-preset/${encodeURIComponent(k.id)}`,null,{method:"DELETE"});if(await Kt(),g(!1),C(!1),N?.ok)P(null);b(N?.ok?"Preset deleted. Existing boards are unchanged.":"Preset was not deleted. Retry.")},children:"Confirm deletion"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("button",{type:"button",class:"is-danger",disabled:h,onClick:()=>C(!0),children:"Delete preset"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r("p",{children:"Choose a saved preset or add a new one."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function GT(e){if(!e)return"never opened";if((Date.now()-new Date(e).getTime())/86400000>=30)return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});return Qd(e)}var ar=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function KT(e){return(e.links?.length??0)+(e.backlinks?.length??0)}async function Ag(e){let t=await On("New board","Board name",{confirm:"Create"});if(t)await Ek(t,e)}var VT="pmx-canvas-home-collapsed";function IL(){try{let e=localStorage.getItem(VT);if(e)return new Set(JSON.parse(e))}catch{}return new Set([CT])}function EL(e){try{localStorage.setItem(VT,JSON.stringify([...e]))}catch{}}var oc=(e,t)=>e.folder===t||!!e.folder?.startsWith(`${t}/`),lr=(e)=>e.split("/").at(-1)??e;function AL({board:e}){return r("div",{class:"home-thumb","aria-hidden":"true",children:r("div",{class:"home-thumb-inner",children:(e.preview??[]).map((t,n)=>r("span",{class:`home-thumb-card${t.pinned?" is-pinned":""}`,style:{left:`${t.x*100}%`,top:`${t.y*100}%`,width:`${t.w*100}%`,height:`${t.h*100}%`}},n,!1,void 0,this))},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function XT(){let e=Ge.value,t=Oe.value,[n,o]=E("Folders"),i=!t&&n==="Review"?"Folders":n,[s,a]=E(()=>[...Ge.value].sort((Ie,S)=>(S.lastOpenedAt??"").localeCompare(Ie.lastOpenedAt??""))[0]?.folder??""),[l,c]=E([]),[u,d]=E(null),[p,f]=E(!1),[m,h]=E(null),[g,v]=E(!1),[b,x]=E(!1),[C,y]=E(null),[k,_]=E(null),[I,w]=E(""),[P,L]=E([]),[N,Y]=E(IL),[B,J]=E(!1),[X,V]=E(!1),ee=D(null),he=D(null),A=[...new Set([...e.flatMap((F)=>F.folder?tc(F.folder):[]),...(Xn.value?.folders??[]).flatMap((F)=>tc(F.path)),...l.flatMap(tc)])].sort((F,Ie)=>F.localeCompare(Ie)),te=(F)=>A.filter((Ie)=>F?Ie.startsWith(`${F}/`)&&!Ie.slice(F.length+1).includes("/"):!Ie.includes("/")),M=I.trim().toLocaleLowerCase(),O=e.filter((F)=>F.pin),Pe=O.reduce((F,Ie)=>F+(Ie.mapChars??0),0),Fe=te(s),De=e.filter((F)=>(F.folder??"")===s).sort((F,Ie)=>(Ie.lastOpenedAt??"").localeCompare(F.lastOpenedAt??"")),Ae=M?e.filter((F)=>`${F.name} ${F.folder??""}`.toLocaleLowerCase().includes(M)):[],ve=e.find((F)=>F.id===m)??null,z=e.find((F)=>F.id===C),re=e.find((F)=>F.id===k),Ne=new Set(e.filter((F)=>!s||oc(F,s)).map((F)=>F.id)),ke=Object.entries(Xn.value?.cards??{}).filter(([F])=>Ne.has(JSON.parse(F)[0])).map(([,F])=>F),ae=ke.filter((F)=>!F.retired&&(F.due||F.sources.length)).length,Se=ke.filter((F)=>F.unknown).length,de=Xn.value?.resolvedFolders[s]?.category,Ue=new Map;for(let[F,Ie]of Object.entries(Xn.value?.cards??{})){if(Ie.retired||!(Ie.due||Ie.sources.length))continue;let[S,K]=JSON.parse(F),ue=Ue.get(S)??[];ue.push(K),Ue.set(S,ue)}let xe=M?Ae:De,qe=async(F)=>{if(!Oe.value)return;let Ie=tn,S=Ue.get(F)?.[0];if(!S)return;if(await zt({boardId:F,cardId:S})&&Oe.value&&Ie===tn&&se.value===F)Ro.value="To review"};q(()=>{let F=I.trim();if(!F){L([]);return}let Ie=!1,S=window.setTimeout(()=>{pe("searchLibrary",`/api/canvas/search?q=${encodeURIComponent(F)}&scope=library&limit=30`,null).then((K)=>{if(!Ie)L(K?.results??[])})},150);return()=>{Ie=!0,window.clearTimeout(S)}},[I]),q(()=>{if(g)he.current?.querySelector('[role="menuitem"]')?.focus()},[g]),q(()=>{if(m&&!e.some((F)=>F.id===m))h(null)},[e,m]),Me(()=>{if(i!=="Folders"||!m)return;let F=(Ie)=>{if(!ir(Ie))return;Ie.preventDefault(),h(null),x(!1)};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[i,m]);let W=(F)=>zt(F),ye=(F)=>{let Ie=new Set(N);if(Ie.has(F))Ie.delete(F);else Ie.add(F);Y(Ie),EL(Ie)},He=(F)=>{a(F),w(""),h(null),J(!1)},R=(F)=>{h(F),v(!1),x(!1)},ne=async()=>{let F=await On("New folder","Folder name",{confirm:"Create"});if(!F)return;let Ie;try{Ie=ip(s?`${s}/${F}`:F)}catch{return}if(!Ie)return;c((S)=>[...S,Ie]),He(Ie)},Ce=async(F)=>{let Ie=await On("Rename board","Board name",{initial:F.name,confirm:"Rename"});if(Ie&&Ie!==F.name)await vr(F.id,{name:Ie})},Te=(F,Ie)=>{let S=te(F),K=!N.has(F),ue=e.filter((je)=>oc(je,F)).length,$e=e.some((je)=>je.pin&&oc(je,F));return r("li",{children:[r("div",{class:`home-tree-row${s===F&&!M?" is-selected":""}`,"data-folder":F,children:[r("span",{class:"home-tree-indent",style:{width:`${Ie*16}px`}},void 0,!1,void 0,this),S.length>0?r("button",{type:"button",class:"home-tree-chevron","aria-label":K?`Fold ${lr(F)}`:`Unfold ${lr(F)}`,"aria-expanded":K,onClick:()=>ye(F),children:K?r(js,{},void 0,!1,void 0,this):r(oi,{},void 0,!1,void 0,this)},void 0,!1,void 0,this):r("span",{class:"home-tree-chevron"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-tree-name",onClick:()=>He(F),children:lr(F)},void 0,!1,void 0,this),$e&&r("span",{class:"home-tree-pin","aria-label":"Has a board in the agent's context"},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:ue},void 0,!1,void 0,this)]},void 0,!0,void 0,this),K&&S.length>0&&r("ul",{class:"home-tree",children:S.map((je)=>Te(je,Ie+1))},void 0,!1,void 0,this)]},F,!0,void 0,this)},fe=r("ul",{class:"home-tree","aria-label":"Folders",children:[te("").map((F)=>Te(F,0)),r("li",{children:r("div",{class:`home-tree-row is-unfiled${s===""&&!M?" is-selected":""}`,children:[r("span",{class:"home-tree-chevron"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-tree-name",onClick:()=>He(""),children:"Unfiled"},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:e.filter((F)=>!F.folder).length},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),it=r("ul",{class:"home-pinned","aria-label":"Pinned boards",children:O.map((F)=>r("li",{children:r("button",{type:"button",class:"home-pinned-row",onClick:()=>He(F.folder??""),children:[r("span",{class:"home-pin-dot","aria-hidden":"true",children:r(uo,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"home-pinned-name",children:F.name},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:F.folder?lr(F.folder):"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},F.id,!1,void 0,this))},void 0,!1,void 0,this),Ht=r("label",{class:"home-search",children:[r(Mu,{},void 0,!1,void 0,this),r("span",{class:"sr-only",children:"Find boards, cards and folders"},void 0,!1,void 0,this),r("input",{type:"search",placeholder:"Boards, cards, folders…",value:I,onInput:(F)=>w(F.currentTarget.value)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ye=(F)=>r("li",{children:r("article",{class:`home-card${F.pin?" is-pinned":""}${m===F.id?" is-selected":""}`,"data-testid":"home-board","data-board-id":F.id,children:[r("button",{type:"button",class:"home-card-select","aria-label":F.name,"aria-pressed":m===F.id,onClick:()=>R(F.id),onDblClick:()=>void Mn(F.id),children:[r(AL,{board:F},void 0,!1,void 0,this),r("span",{class:"home-card-body",children:[r("span",{class:"home-card-name",children:F.name},void 0,!1,void 0,this),r("span",{class:"home-card-readme",children:F.summary??"No README yet."},void 0,!1,void 0,this),r("span",{class:"home-card-meta",children:[r("span",{children:ar(F.nodeCount,"card")},void 0,!1,void 0,this),KT(F)>0&&r("span",{children:["↔ ",ar(KT(F),"link")]},void 0,!0,void 0,this),r("span",{class:"home-card-when",children:GT(F.lastOpenedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),t&&Ue.has(F.id)&&r("button",{type:"button",class:"home-card-review","aria-label":`Review ${F.name}`,onClick:()=>void qe(F.id),children:["⧗ Review ",ar(Ue.get(F.id).length,"card")]},void 0,!0,void 0,this),r(ho,{board:F},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},F.id,!1,void 0,this),Lt=ve&&r("aside",{class:"home-details","aria-label":"Board details","data-testid":"home-details",children:[r("button",{type:"button",class:"home-details-grip","aria-label":"Close details",onClick:()=>R(null)},void 0,!1,void 0,this),r("div",{class:"home-details-head",children:[r("span",{class:"home-details-folder",children:ve.folder?lr(ve.folder):"Unfiled"},void 0,!1,void 0,this),r("span",{class:"home-details-name",children:ve.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:`home-details-context${ve.pin?" is-on":""}`,children:[r("span",{class:"home-details-context-text",children:r("span",{class:"home-details-context-label",children:ve.pin?"In the agent's context":"Not in the agent's context"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",role:"switch","aria-checked":!!ve.pin,"aria-label":"In the agent's context",class:"home-switch",onClick:()=>void $s(ve.id,!ve.pin),children:r("span",{class:"home-switch-knob"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b?r("div",{class:"home-details-confirm",role:"alert",children:[r("span",{children:["Delete ",r("strong",{children:ve.name},void 0,!1,void 0,this)," and its ",ar(ve.nodeCount,"card")," and snapshots? This can't be undone."]},void 0,!0,void 0,this),r("span",{class:"home-details-actions",children:[r("button",{type:"button",class:"home-button",onClick:()=>x(!1),children:"Cancel"},void 0,!1,void 0,this),r("button",{type:"button",class:"home-button is-danger",onClick:()=>{x(!1),Nk(ve.id)},children:"Delete board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):r("div",{class:"home-details-actions",children:[r("button",{type:"button",class:"home-button is-primary",onClick:()=>void Mn(ve.id),children:"Open board"},void 0,!1,void 0,this),t&&Ue.has(ve.id)&&r("button",{type:"button",class:"home-button",onClick:()=>void qe(ve.id),children:"Review cards"},void 0,!1,void 0,this),r("span",{class:"home-more",children:[r("button",{ref:ee,type:"button",class:"home-button is-icon","aria-label":"More: move, rename, create from, delete","aria-haspopup":"menu","aria-expanded":g,onClick:()=>v(!g),children:r(ml,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),g&&r("span",{ref:he,class:"home-more-menu",role:"menu",onKeyDown:(F)=>{let Ie=[...he.current?.querySelectorAll('[role="menuitem"]')??[]],S=Ie.indexOf(document.activeElement);if(F.key==="Escape")F.preventDefault(),v(!1),ee.current?.focus();else if(F.key==="ArrowDown"||F.key==="ArrowUp"){F.preventDefault();let K=F.key==="ArrowDown"?1:-1;Ie[(S+K+Ie.length)%Ie.length]?.focus()}},children:[["Move…",()=>y(ve.id)],["Rename…",()=>void Ce(ve)],["Create from…",()=>_(ve.id)],["Delete…",()=>x(!0)]].map(([F,Ie])=>r("button",{type:"button",role:"menuitem",class:"home-more-item",onClick:()=>{v(!1),Ie()},children:F},F,!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);return r("div",{class:"home-shell",children:[u!==null&&r(WT,{folder:u||void 0,onClose:()=>d(null)},u,!1,void 0,this),p&&r(qT,{onClose:()=>f(!1)},void 0,!1,void 0,this),r("nav",{class:"home-view-tabs","aria-label":"Library view",children:[["Folders","Map","Graph","Review"].filter((F)=>t||F!=="Review").map((F)=>r("button",{type:"button",class:"home-button","aria-pressed":i===F,onClick:()=>o(F),children:F},F,!1,void 0,this)),r("button",{type:"button",class:"home-button",onClick:()=>f(!0),children:"Relation presets"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),i==="Map"||i==="Graph"?i==="Map"?r(RT,{},void 0,!1,void 0,this):r(DT,{},void 0,!1,void 0,this):r("div",{class:`home-view${ve&&i==="Folders"?" has-details":""}`,"data-testid":"home-view",children:[r("aside",{class:`home-library${B?" is-open":""}`,"aria-label":"Library",children:[r("div",{class:"home-library-head",children:[r("span",{class:"home-library-title",children:"Library"},void 0,!1,void 0,this),r("span",{class:"home-tree-count",children:ar(e.length,"board")},void 0,!1,void 0,this),t&&r("button",{type:"button",class:"home-button",onClick:()=>{if(Oe.value)d("")},children:"Categories"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ht,O.length>0&&r("section",{class:"home-library-section",children:[r("span",{class:"home-section-label",children:"Pinned boards"},void 0,!1,void 0,this),it,r("span",{class:"home-pinned-cost",children:["≈ ",Jl(Pe)," tokens · ",ar(O.length,"board")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("section",{class:"home-library-section is-folders",children:[r("span",{class:"home-section-label",children:"Folders"},void 0,!1,void 0,this),fe,r("button",{type:"button",class:"home-tree-new",onClick:()=>void ne(),children:"+ New folder"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("main",{class:"home-main",children:[r("div",{class:"home-narrow",children:[Ht,O.length>0&&r(be,{children:[r("button",{type:"button",class:"home-narrow-context","aria-expanded":X,onClick:()=>V(!X),children:[r("span",{class:"home-pin-dot","aria-hidden":"true",children:r(uo,{},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"home-narrow-context-label",children:["In context: ",ar(O.length,"board")]},void 0,!0,void 0,this),r("span",{class:"home-narrow-context-cost",children:["≈ ",Jl(Pe)," tokens"]},void 0,!0,void 0,this),r("span",{children:X?"Hide ▴":"Show ▾"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&it]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-narrow-picker","aria-expanded":B,onClick:()=>J(!B),children:[s?lr(s):"Library",r("span",{class:"home-tree-count",children:["· ",s?e.filter((F)=>oc(F,s)).length:De.length," ▾"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i==="Review"?r(BT,{folder:s,folders:A,onScopeChange:He},void 0,!1,void 0,this):r(be,{children:[r("div",{class:"home-main-head",children:[r("div",{class:"home-main-title",children:[r("nav",{class:"home-crumbs","aria-label":"Folder path",children:[r("button",{type:"button",onClick:()=>He(""),children:"Library"},void 0,!1,void 0,this),s&&tc(s).map((F)=>r("span",{children:[r("span",{class:"home-crumb-sep",children:"/"},void 0,!1,void 0,this),r("button",{type:"button",onClick:()=>He(F),children:lr(F)},void 0,!1,void 0,this)]},F,!0,void 0,this))]},void 0,!0,void 0,this),r("h1",{class:"home-view-title",children:M?`Results for “${I.trim()}”`:s?lr(s):"Library"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&r("button",{type:"button",class:"home-button",onClick:()=>{if(Oe.value)d(s)},children:[" ",s?"Folder settings":"Categories"]},void 0,!0,void 0,this),r("button",{type:"button",class:"home-button is-primary",onClick:()=>void Ag(s||null),children:s?"New board here":"New board"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&Xn.value&&!M&&r("section",{class:"home-main-section","aria-label":"Folder review summary",children:[r("span",{class:"home-section-label",children:["Card review · ",s?"In this folder and subfolders":"Across the library"]},void 0,!0,void 0,this),r("div",{class:"home-card-meta",children:[de&&r("span",{children:["Category: ",de.glyph," ",de.name]},void 0,!0,void 0,this),r("button",{type:"button",class:`home-review-link${ae?" has-review":""}`,onClick:()=>{o("Review"),h(null)},children:["Review needed: ",ar(ae,"card")]},void 0,!0,void 0,this),r("span",{children:["No review policy: ",ar(Se,"card")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),e.length===0?r("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):M?r(be,{children:[P.length>0&&r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:["Cards · ",P.length]},void 0,!0,void 0,this),r("ul",{class:"home-hits","aria-label":"Library search results",children:P.map((F)=>r("li",{children:r("button",{type:"button",class:"home-hit",onClick:()=>void W(F),children:[r("span",{class:"home-card-name",children:F.title||F.boardTitle},void 0,!1,void 0,this),t&&F.qualification?.retired&&r("span",{class:"category-tag",children:"Retired"},void 0,!1,void 0,this),r("span",{class:"home-card-meta",children:[F.boardTitle," · ",F.snippet]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},`${F.boardId}:${F.cardId}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Ae.length>0?r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:["Boards · ",Ae.length]},void 0,!0,void 0,this),r("ul",{class:"home-cards",children:Ae.map(Ye)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):P.length===0&&r("div",{class:"home-view-empty",role:"status",children:["No boards match “",I.trim(),"”."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[Fe.length>0&&r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:["Folders · ",Fe.length]},void 0,!0,void 0,this),r("ul",{class:"home-folders",children:Fe.map((F)=>{let Ie=e.filter((ue)=>oc(ue,F)),S=Ie.map((ue)=>ue.lastOpenedAt??"").sort().at(-1),K=Ie.filter((ue)=>ue.pin).length;return r("li",{children:r("button",{type:"button",class:"home-folder","data-testid":"home-section","data-folder":F,onClick:()=>He(F),children:[r("span",{class:"home-folder-stack","aria-hidden":"true",children:[r("span",{},void 0,!1,void 0,this),r("span",{},void 0,!1,void 0,this),r("span",{},void 0,!1,void 0,this)]},void 0,!0,void 0,this),K>0&&r("span",{class:"home-folder-context",children:[K," in context"]},void 0,!0,void 0,this),r("span",{class:"home-folder-name",children:lr(F)},void 0,!1,void 0,this),r("span",{class:"home-folder-meta",children:[ar(Ie.length,"board"),S?` · opened ${GT(S)}`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},F,!1,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("section",{class:"home-main-section",children:[r("span",{class:"home-section-label",children:[s?`Boards in ${lr(s)}`:"Unfiled boards"," · ",xe.length]},void 0,!0,void 0,this),xe.length>0?r("ul",{class:"home-cards","aria-label":s?`Boards in ${s}`:"Unfiled boards",children:xe.map(Ye)},void 0,!1,void 0,this):r("div",{class:"home-view-empty",children:"No boards here yet."},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),i==="Folders"&&Lt,z&&r(TT,{board:z,folders:A,onClose:()=>y(null)},z.id,!1,void 0,this),re&&r(IT,{board:re,onClose:()=>_(null)},re.id,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var cs=ie(!1);function RL(e){return e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}function JT(){let[e,t]=E(!1),[n,o]=E(!1),[i,s]=E(null),[a,l]=E(null),[c,u]=E(!1),[d,p]=E(""),f=cs.value,m=se.value;if(q(()=>{if(!f||!m)return;let g=!0;return l(null),p(""),s(null),pe("exportPreview",`/api/canvas/export/preview?board=${encodeURIComponent(m)}&includeFiles=${e}&includeDerivedText=${n}`,null).then((v)=>{if(g)s(v?.manifest??null)}),()=>{g=!1}},[f,e,n,m]),q(()=>{o(!1)},[f,m]),q(()=>{if(!f)return;let g=(v)=>{if(v.key!=="Escape")return;v.stopPropagation(),cs.value=!1};return window.addEventListener("keydown",g,{capture:!0}),()=>window.removeEventListener("keydown",g,{capture:!0})},[f]),!f)return null;let h=async()=>{if(!i||i.boardId!==se.value)return;u(!0);let g=await pe("exportBoard","/api/canvas/export",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({board:i.boardId,includeFiles:e,includeDerivedText:n})});if(u(!1),g?.path&&se.value===i.boardId)l(g)};return r("div",{class:"text-prompt-backdrop",onPointerDown:()=>cs.value=!1,children:r("div",{class:"text-prompt export-dialog",role:"dialog","aria-label":"Export board","data-testid":"export-dialog",onPointerDown:(g)=>g.stopPropagation(),children:[r("div",{class:"text-prompt-title",children:["Export ",i?`“${i.boardName}”`:"board"]},void 0,!0,void 0,this),!i?r("div",{class:"export-dialog-note",children:"Reading the board…"},void 0,!1,void 0,this):r(be,{children:[r("div",{class:"export-dialog-note",children:"One HTML file anyone can open without installing anything. It will contain:"},void 0,!1,void 0,this),r("ul",{class:"export-dialog-list",children:[r("li",{children:[i.cards," card",i.cards!==1?"s":""," and ",i.connections," connection",i.connections!==1?"s":""]},void 0,!0,void 0,this),i.frames>0&&r("li",{children:[i.frames," embedded pages, charts or diagrams, with the code that draws them"]},void 0,!0,void 0,this),i.embeddedImages>0&&r("li",{children:[i.embeddedImages," local images"]},void 0,!0,void 0,this),i.placeholders.length>0&&r("li",{children:["Shown as placeholders:"," ",i.placeholders.map((g)=>`${g.title} (${g.reason})`).join(", ")]},void 0,!0,void 0,this),i.remoteImages.length>0&&r("li",{children:["Web images loaded when opened: ",i.remoteImages.join(", ")]},void 0,!0,void 0,this),i.links.length>0&&r("li",{children:["Links included in cards: ",i.links.join(", ")]},void 0,!0,void 0,this),i.frameNetworkDestinations.length>0&&r("li",{children:["Network destinations referenced by embedded pages: ",i.frameNetworkDestinations.join(", ")]},void 0,!0,void 0,this),i.embeddedCodeCanAccessNetwork&&r("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),(i.attachments?.length??0)>0&&r("p",{children:"Original attachments are excluded. Their filenames remain visible."},void 0,!1,void 0,this),(i.sourceDerivedCards?.length??0)>0&&r("label",{class:"export-dialog-files",children:[r("input",{type:"checkbox",checked:n,onChange:(g)=>o(g.currentTarget.checked)},void 0,!1,void 0,this),r("span",{children:["Include imported document text (",i.sourceDerivedCards.length," cards)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),i.files.length>0&&r("label",{class:"export-dialog-files",children:[r("input",{type:"checkbox",checked:e,onChange:(g)=>t(g.target.checked)},void 0,!1,void 0,this),r("span",{children:["Include the contents of ",i.files.length," local file",i.files.length!==1?"s":"",": ",i.files.map((g)=>g.path).join(", ")]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),a&&r("div",{class:"export-dialog-result","data-testid":"export-result",children:[r("div",{children:["Saved (",RL(a.bytes),"): ",r("code",{children:a.path},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"export-dialog-links",children:tt()?r("button",{type:"button",disabled:c,onClick:async()=>{u(!0),p("");try{await Gw(a.url)}catch(g){p(g instanceof Error?g.message:"Download failed. Try again.")}finally{u(!1)}},children:c?"Downloading…":"Download"},void 0,!1,void 0,this):r(be,{children:[r("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:"Open"},void 0,!1,void 0,this),r("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),tt()&&r("p",{children:"Download the HTML file to open it outside ChatGPT."},void 0,!1,void 0,this),d&&r("p",{role:"alert",children:d},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"text-prompt-actions",children:[r("button",{type:"button",class:"text-prompt-cancel",onClick:()=>cs.value=!1,children:a?"Done":"Cancel"},void 0,!1,void 0,this),!a&&r("button",{type:"button",class:"text-prompt-confirm",disabled:!i||c,onClick:()=>void h(),children:c?"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 Rg({presence:e,size:t=18}){return r("span",{class:"writer-avatar",style:{background:So(e.sessionId),width:`${t}px`,height:`${t}px`},"aria-hidden":"true",children:Md(e.label)},void 0,!1,void 0,this)}function YT(){let e=$d.value;if(tr.value||e.length===0)return null;let t=e.reduce((i,s)=>i+s.opCount,0),n=e.length===1?e[0].label:`${e.length} writers`,o=ts.value;return r(_e,{label:`${e.length} external writer${e.length===1?"":"s"} on this board`,body:"Click for their activity.",align:"end",children:r("button",{type:"button",class:"external-indicator","data-testid":"external-indicator","aria-label":`${n} external activity, ${t} operation${t===1?"":"s"}`,"aria-expanded":o,onClick:()=>{ts.value=!o},children:[r("span",{class:"external-indicator-avatars",children:e.slice(0,3).map((i)=>r(Rg,{presence:i},i.sessionId,!1,void 0,this))},void 0,!1,void 0,this),r("span",{class:"external-indicator-label",children:n},void 0,!1,void 0,this),r("span",{class:"external-indicator-ops hud-collapsible-text",children:[t," op",t===1?"":"s"]},void 0,!0,void 0,this),r("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function PL(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 NL(e){return e.reduce((t,n)=>n.lastSeenAt>t?n.lastSeenAt:t,"")}function ML(){return[...qt.value.values()].filter((e)=>!e.auto&&e.phase==="forming")}function QT(){let e=ts.value,t=$d.value,n=nr(e?1e4:0);if(Me(()=>{if(!e)return;let l=(c)=>{if(c.key!=="Escape"||c.defaultPrevented)return;if(c.preventDefault(),pa.value)pa.value=!1;else ts.value=!1};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),!e||tr.value||t.length===0)return null;let o=Jh.value,i=ML().filter((l)=>!o||(l.source??"")===o),s=fi.value.filter((l)=>!o||l.sessionId===o),a=(l,c)=>r("button",{type:"button",class:`activity-filter${o===l?" is-active":""}`,style:l?{"--writer":So(l)}:void 0,"aria-pressed":o===l,onClick:()=>{Jh.value=l},children:c},void 0,!1,void 0,this);return r("div",{class:"activity-feed","data-testid":"activity-feed",role:"dialog","aria-label":"External activity",children:[r("div",{class:"activity-feed-head",children:[r("span",{class:"external-indicator-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"activity-feed-titles",children:[r("div",{class:"activity-feed-title",children:["External activity — ",t.length," writer",t.length===1?"":"s"]},void 0,!0,void 0,this),r("div",{class:"activity-feed-sub",children:[t.reduce((l,c)=>l+c.opCount,0)," writes · last"," ",zd(NL(t),n)," · live writers"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("button",{type:"button",class:"activity-feed-close","aria-label":"Close activity feed",onClick:()=>{ts.value=!1},children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"activity-filters",children:[a(null,"All"),t.map((l)=>a(l.sessionId,l.label))]},void 0,!0,void 0,this),r("div",{class:"activity-rows",children:[i.map((l)=>r("div",{class:"activity-row is-pending","data-testid":"activity-proposal",children:[r("span",{class:"activity-glyph tone-purple","aria-hidden":"true",children:"▢"},void 0,!1,void 0,this),r("div",{class:"activity-main",children:[r("div",{class:"activity-text",children:["Proposing: ",r("b",{children:l.label?.trim()||`${l.kind} intent`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"activity-meta",children:[l.reason?.trim()||"Intent signalled — a real veto window before the mutation",l.source?` · ${l.source}`:""]},void 0,!0,void 0,this),r("div",{class:"activity-actions",children:[r("button",{type:"button",class:"activity-veto",onClick:()=>{Li(l).then((c)=>{if(c)zi(l.id)})},children:"Veto"},void 0,!1,void 0,this),r("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),r("span",{class:"activity-age",children:"now"},void 0,!1,void 0,this)]},l.id,!0,void 0,this)),s.length===0&&i.length===0&&r("div",{class:"activity-empty",children:"No writes yet."},void 0,!1,void 0,this),s.map((l)=>{let{glyph:c,tone:u}=PL(l.op);return r("div",{class:"activity-row","data-testid":"activity-row","data-op":l.op,children:[r("span",{class:`activity-glyph tone-${u}`,"aria-hidden":"true",children:c},void 0,!1,void 0,this),r("div",{class:"activity-main",children:[r("div",{class:"activity-text",children:l.summary},void 0,!1,void 0,this),r("div",{class:"activity-writer",style:{color:So(l.sessionId)},children:l.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"activity-age",children:zd(l.at,n)},void 0,!1,void 0,this)]},l.id,!0,void 0,this)})]},void 0,!0,void 0,this),r("div",{class:"activity-feed-foot",children:[r("span",{class:"activity-feed-note",children:"All writes ghost first · Esc vetoes"},void 0,!1,void 0,this),r("button",{type:"button",class:"activity-feed-link",onClick:()=>{pa.value=!0},children:"Writers"},void 0,!1,void 0,this),xt.value&&r("button",{type:"button",class:"activity-feed-link is-accent",onClick:()=>{ts.value=!1,vi()},children:["Start session ",r(ri,{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 zL(){let e=[];if(To.value)e.push("scoped");if(Co.value.length>0)e.push("gated");return e.length>0?e.join(" + "):"open"}function eI(){let e=pa.value,t=nr(e?1e4:0),n=D(null);if(bn(n,e),!e)return null;let o=xt.value?en.value.filter((a)=>a.attached):[],i=$d.value,s=()=>{pa.value=!1};return r(be,{children:[r("div",{class:"writers-scrim",onClick:s,"aria-hidden":"true"},void 0,!1,void 0,this),r("div",{ref:n,class:"writers-sheet","data-testid":"writers-sheet",role:"dialog","aria-modal":"true","aria-label":"Connected writers",children:[r("div",{class:"writers-head",children:[r("span",{class:"writers-title",children:"Connected writers"},void 0,!1,void 0,this),r("span",{class:"writers-board",children:xr.value.slice(0,12)},void 0,!1,void 0,this),r("button",{type:"button",class:"activity-feed-close","aria-label":"Close writers",onClick:s,children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"writers-body",children:[xt.value&&r(be,{children:[r("div",{class:"writers-section",children:"Agent sessions"},void 0,!1,void 0,this),o.length===0&&r("div",{class:"writers-empty",children:"None attached — start one from the top bar."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o.map((a)=>r("div",{class:"writers-row",children:[r(Rg,{presence:a,size:20},void 0,!1,void 0,this),r("span",{class:"writers-name",children:a.label},void 0,!1,void 0,this),r("span",{class:"writers-config",children:zL()},void 0,!1,void 0,this)]},a.sessionId,!0,void 0,this)),r("div",{class:"writers-section",children:xt.value?"External writers · MCP":"Live writers"},void 0,!1,void 0,this),i.length===0&&r("div",{class:"writers-empty",children:"No external writers right now."},void 0,!1,void 0,this),i.map((a)=>r("div",{class:"writers-row",children:[r(Rg,{presence:a,size:20},void 0,!1,void 0,this),r("span",{class:"writers-name is-mono",children:a.label},void 0,!1,void 0,this),r("span",{class:"writers-meta",children:[a.source!==a.label?`${a.source} · `:"","wrote"," ",zd(a.lastSeenAt,t)," ago"]},void 0,!0,void 0,this)]},a.sessionId,!0,void 0,this))]},void 0,!0,void 0,this),r("div",{class:"writers-foot",children:[r("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),r("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 tI({nodeId:e}){let t=se.value,[n,o]=E(null),[i,s]=E(!1),a=et.value,l=H.value,c=Ge.value;q(()=>{let m=!1;if(o(null),s(!1),t)pe("relations",`/api/canvas/memory-graph?focus=${encodeURIComponent(Mt({boardId:t,cardId:e}))}&depth=1`,null).then((h)=>{if(!m)o(h),s(!h)});return()=>{m=!0}},[t,e,a,l,c]);let u=t?Mt({boardId:t,cardId:e}):"",d=n?.edges.filter((m)=>m.kind!=="member"&&(m.from===u||m.to===u))??[],p=(m)=>{let h=m.to===u;if(h&&m.relationKind==="supports")return"Evidence for";if(h&&m.relationKind==="contradicts")return"Evidence against";let g=jd({kind:m.relationKind,type:m.type});if(g)return(g==="from"?!h:h)?"Used by":"Sources";if(m.relationKind==="cites"||m.type==="references")return h?"Used by":"Sources";if(!h&&m.relationKind==="supports")return"Used by";return"Connections"},f=["Evidence for","Evidence against","Sources","Used by","Connections"];return d.sort((m,h)=>f.indexOf(p(m))-f.indexOf(p(h))),r("aside",{class:"relations-panel","aria-label":"Relations",children:[r("h3",{children:"Relations"},void 0,!1,void 0,this),!n&&r("p",{role:"status",children:i?"Relations unavailable. Reopen to retry.":"Loading relations…"},void 0,!1,void 0,this),n&&d.length===0&&r("p",{children:"No connections yet."},void 0,!1,void 0,this),d.map((m,h)=>{let g=m.from===u,v=g?m.target:m.source,b=n?.nodes.find((y)=>y.key===Mt(v)),x=c.find((y)=>y.id===m.source.boardId),C=mo({kind:m.relationKind,type:m.type},x?.relationVocabulary);return r("div",{class:"relation-row",children:[(h===0||p(d[h-1])!==p(m))&&r("h4",{children:p(m)},void 0,!1,void 0,this),r("span",{class:"relation-kind",style:{color:`var(--c-rel-${C.ink})`},children:[g?"→":"←"," ",m.relationKind??m.type??m.kind]},void 0,!0,void 0,this),m.missing?r("span",{children:"Missing target"},void 0,!1,void 0,this):r("button",{type:"button",class:"relation-target",onClick:()=>void zt(v),children:b?.title??v.boardId},void 0,!1,void 0,this),m.label&&r("span",{children:m.label},void 0,!1,void 0,this),r("p",{children:m.reason??"No reason recorded."},void 0,!1,void 0,this)]},m.id,!0,void 0,this)}),r("p",{children:"Manage shared relation presets in Home."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nI(e,t){switch(e.type){case"markdown":return r(Qu,{node:e,expanded:t},void 0,!1,void 0,this);case"mcp-app":return r(di,{node:e,expanded:t},void 0,!1,void 0,this);case"webpage":return r(Ad,{node:e,expanded:t},void 0,!1,void 0,this);case"json-render":return r(di,{node:e,expanded:t},void 0,!1,void 0,this);case"graph":return r(di,{node:e,expanded:t},void 0,!1,void 0,this);case"board":return r(Kd,{node:e},void 0,!1,void 0,this);case"prompt":return r(Rd,{node:e},void 0,!1,void 0,this);case"response":return r(Pd,{node:e,expanded:t},void 0,!1,void 0,this);case"status":return r(Id,{node:e},void 0,!1,void 0,this);case"context":return r($u,{node:e,expanded:t},void 0,!1,void 0,this);case"ledger":return r(Bu,{node:e},void 0,!1,void 0,this);case"trace":return r(Nd,{node:e},void 0,!1,void 0,this);case"file":return r(Du,{node:e,expanded:t},void 0,!1,void 0,this);case"diff":return r(Lu,{node:e},void 0,!1,void 0,this);case"mermaid":return r(ad,{node:e,expanded:t},void 0,!1,void 0,this);case"image":return r(Ed,{node:e,expanded:t},void 0,!1,void 0,this);case"html":return r(Hl,{node:e,expanded:t},void 0,!1,void 0,this);default:return r("div",{children:"Unknown node type"},void 0,!1,void 0,this)}}function oI(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 $L(e){if(!e)return 0;return e.split(/\s+/).filter(Boolean).length}function LL(e,t){return e!==null&&typeof e==="object"&&e.source===Qn&&e.type==="presentation-exit"&&e.token===t}function OL(e){return e==="ArrowRight"||e==="PageDown"||e===" "||e==="ArrowLeft"||e==="PageUp"||e==="Home"||e==="End"}function rI(e){return e instanceof HTMLElement&&Boolean(e.closest(".html-presentation-exit"))}function iI(){let e=Bt.value,t=e?H.value.get(e):void 0,[n,o]=E(!1),[i,s]=E(null),[a,l]=E(!1),[c,u]=E(""),d=D(null),p=D(null),f=oe(()=>{l(!1),Cr()},[]),m=oe(()=>{u(`presentation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`),l(!0)},[]),h=oe((A)=>{document.querySelector(".html-presentation-overlay iframe.html-node-frame-presentation")?.contentWindow?.postMessage({source:Qn,token:c,...A},"*")},[c]),g=oe(()=>{l(!1)},[]),v=oe((A)=>{if(A.key==="Escape"){A.preventDefault(),A.stopPropagation(),l(!1);return}if(A.key==="Tab"&&!rI(A.target)){A.preventDefault(),A.stopPropagation(),p.current?.focus();return}if((A.key===" "||A.key==="Enter")&&rI(A.target))return;if(!OL(A.key))return;A.preventDefault(),A.stopPropagation(),h({type:"presentation-key",key:A.key})},[h]),b=oe((A)=>{if(A.target.classList.contains("expanded-overlay-backdrop"))Cr()},[]),x=oe(()=>{if(!t)return;let A=oI(t);if(!A)return;navigator.clipboard.writeText(A).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},[t]),C=oe(()=>{if(!e)return;lo(e)},[e]);q(()=>{l(!1)},[e]),Me(()=>{if(!a)return;let A=()=>{let O=d.current;if(!O||O.contains(document.activeElement))return;O.focus()},te=[0,50,150].map((O)=>window.setTimeout(A,O)),M=(O)=>{if(!LL(O.data,c))return;l(!1)};return document.addEventListener("keydown",v,!0),window.addEventListener("message",M),()=>{te.forEach((O)=>{window.clearTimeout(O)}),document.removeEventListener("keydown",v,!0),window.removeEventListener("message",M)}},[v,c,a]);let y=D(null),k=oe(()=>e?document.querySelector(`.canvas-node[data-node-id="${CSS.escape(e)}"]`):null,[e]),_=Oe.value&&Ct.value?.nodeId===e,I=!Oe.value&&Ct.value?.nodeId===e&&!!document.activeElement?.closest(".lifecycle-dialog");if(bn(y,t!==void 0&&!_,{restoreTo:k}),Me(()=>{if(I)document.querySelector('button[aria-label="Settings"]')?.focus({preventScroll:!0})},[_]),!t)return null;let w=t.data.title||t.data.path?.split("/").pop()||an[t.type],P=oI(t),L=$L(P),N=e?kt.value.has(e):!1,Y=P.length>0,B=zo.value===e,J=t.type==="mcp-app"||t.type==="webpage"||t.type==="json-render"||t.type==="graph",X=q_(t),V=Do(t.type),ee=t.data.provenance&&typeof t.data.provenance==="object"?t.data.provenance:null,he=ee?[ee.sourceKind,ee.sourceUri,ee.syncedAt?`synced ${ee.syncedAt.slice(11,16)}`:null].filter((A)=>typeof A==="string"&&A.length>0).join(" · "):null;return r("div",{class:"expanded-overlay-backdrop",onPointerDown:b,style:{pointerEvents:B?"none":"auto"},children:r("div",{ref:y,class:`expanded-overlay-panel${N?" is-pinned":""}`,role:"dialog","aria-modal":_?void 0:"true","aria-label":w,"data-testid":"expanded-node",children:[r("div",{class:"expanded-header",children:[r("span",{class:"expanded-kind-icon","aria-hidden":"true",children:r(V,{size:15},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"expanded-title",children:w},void 0,!1,void 0,this),r("span",{class:"expanded-kind-pill",children:an[t.type]},void 0,!1,void 0,this),r(_e,{label:N?"In agent context — click to unpin":"Pin as agent context",children:r("button",{type:"button",class:`expanded-pin${N?" is-on":""}`,onClick:C,"aria-label":N?"In agent context — click to unpin":"Pin as agent context","aria-pressed":N,children:"✦"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"expanded-spacer"},void 0,!1,void 0,this),r("div",{class:"expanded-actions",children:[Oe.value&&r("button",{type:"button",class:"expanded-action-btn",onClick:()=>Es(t.id),children:"Review"},void 0,!1,void 0,this),r("button",{type:"button",class:"expanded-action-btn","aria-pressed":i===e,onClick:()=>s(i===e?null:e),children:"Relations"},void 0,!1,void 0,this),Y&&r(_e,{label:"Copy content to clipboard",children:r("button",{type:"button",class:"expanded-action-btn",onClick:x,children:n?"Copied!":"Copy"},void 0,!1,void 0,this)},void 0,!1,void 0,this),od(t)&&r(_e,{label:"Open as a full-page site in the system browser",children:r("button",{type:"button",class:"expanded-action-btn",onClick:()=>void rd(t),children:["Open in tab ",r(ri,{size:14},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X&&r(_e,{label:"Present this HTML node fullscreen",children:r("button",{type:"button",class:"expanded-action-btn expanded-action-primary",onClick:m,children:"Present"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(_e,{label:"Close",shortcut:"Esc",align:"end",children:r("button",{type:"button",class:"expanded-close",onClick:f,"aria-label":"Close",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"expanded-content-row",children:[r("div",{class:`expanded-body${J?" is-embedded":""}`,children:J?r("div",{style:{flex:1,minHeight:0,display:"flex"},children:nI(t,!0)},void 0,!1,void 0,this):nI(t,!0)},void 0,!1,void 0,this),i===e&&r(tI,{nodeId:t.id},e,!1,void 0,this)]},void 0,!0,void 0,this),r(Wd,{node:t},void 0,!1,void 0,this),r("div",{style:{"--ax-dock-bleed":"0px","--ax-dock-pad":"16px"},children:r(Gd,{node:t},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("div",{class:"expanded-footer",children:[r("span",{class:"expanded-footer-meta",children:[he,L>0?`${L.toLocaleString()} word${L!==1?"s":""}`:null].filter(Boolean).join(" · ")||an[t.type].toLowerCase()},void 0,!1,void 0,this),r("span",{class:"expanded-spacer"},void 0,!1,void 0,this),r("span",{class:`expanded-footer-hint${B?" is-saving":""}`,children:B?"Saving edits…":"esc or click outside to close"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&a&&r("div",{ref:d,class:"html-presentation-overlay",role:"dialog","aria-modal":"true","aria-label":`Present ${w}`,tabIndex:-1,onKeyDownCapture:v,children:[r("button",{ref:p,type:"button",class:"html-presentation-exit",onClick:g,"aria-label":"Exit presentation",children:"Exit presentation"},void 0,!1,void 0,this),r("div",{class:"html-presentation-stage",children:r(Hl,{node:t,expanded:!0,presentation:!0,presentationExitToken:c},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 aI=168,lI=112,up=20;function sI(e,t,n,o){let i=Array.from(e.values()),s=0,a=0,l=1000,c=800;if(i.length>0){s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(let v of i)s=Math.min(s,v.position.x),a=Math.min(a,v.position.y),l=Math.max(l,v.position.x+v.size.width),c=Math.max(c,v.position.y+v.size.height)}let u=-t.x/t.scale,d=-t.y/t.scale,p=u+n/t.scale,f=d+o/t.scale,m={minX:Math.min(s,u)-up,minY:Math.min(a,d)-up,maxX:Math.max(l,p)+up,maxY:Math.max(c,f)+up},h=m.maxX-m.minX||1,g=m.maxY-m.minY||1;return{bounds:m,scale:Math.min(aI/h,lI/g)}}function cI({viewport:e,nodes:t,onNavigate:n,containerWidth:o,containerHeight:i}){let s=D(null),a=D(!1),l=t.value,c=e.value,u=sI(l,c,o,i),{bounds:d,scale:p}=u,f=(w)=>(w-d.minX)*p,m=(w)=>(w-d.minY)*p,h=oe((w)=>{let P=s.current;if(!P)return;let L=P.getBoundingClientRect(),N=(w.clientX-L.left)/L.width*aI,Y=(w.clientY-L.top)/L.height*lI,B=sI(t.value,e.value,o,i),J=e.value,X=o/J.scale,V=i/J.scale,ee=N/B.scale+B.bounds.minX,he=Y/B.scale+B.bounds.minY;n(-(ee-X/2)*J.scale,-(he-V/2)*J.scale)},[t,e,o,i,n]),g=oe((w)=>{w.stopPropagation(),w.preventDefault(),a.current=!0,h(w);let P=(N)=>{if(a.current)h(N)},L=()=>{a.current=!1,document.removeEventListener("pointermove",P),document.removeEventListener("pointerup",L)};document.addEventListener("pointermove",P),document.addEventListener("pointerup",L)},[h]),v=st.value,b=kt.value,x=tr.value?Ld.value:new Set,C=To.value,y=C?Fd(C.nodeIds.map((w)=>l.get(w)).filter((w)=>w!==void 0),C.padding):null,k=en.value.map((w)=>({id:w.sessionId,phase:w.phase,worker:w.parentAgentId!=null,external:!w.attached,at:Od(w,(P)=>l.get(P))})).filter((w)=>w.at!==null),_=-c.x/c.scale,I=-c.y/c.scale;return r("div",{ref:s,class:"minimap","data-testid":"minimap","aria-label":"Minimap — click to jump, drag the frame to pan",onPointerDown:g,children:[Array.from(l.values()).map((w)=>{let P=w.type==="group";return r("span",{class:`minimap-node${P?" is-group":""}${v.has(w.id)?" is-selected":""}${b.has(w.id)?" is-pinned":""}${x.has(w.id)?" is-agent":""}`,"data-kind":w.type,style:{left:`${f(w.position.x)}px`,top:`${m(w.position.y)}px`,width:`${Math.max(P?6:4,w.size.width*p)}px`,height:`${Math.max(P?5:3,w.size.height*p)}px`}},w.id,!1,void 0,this)}),y&&r("span",{class:"minimap-fence",style:{left:`${f(y.x)}px`,top:`${m(y.y)}px`,width:`${y.width*p}px`,height:`${y.height*p}px`}},void 0,!1,void 0,this),k.map((w)=>r("span",{class:`minimap-presence phase-${w.phase}${w.worker?" is-worker":""}${w.external?" is-external":""}`,style:{left:`${f(w.at.x)-4}px`,top:`${m(w.at.y)-4}px`,"--identity-color":So(w.id)}},w.id,!1,void 0,this)),r("span",{class:"minimap-frame",style:{left:`${f(_)}px`,top:`${m(I)}px`,width:`${o/c.scale*p}px`,height:`${i/c.scale*p}px`}},void 0,!1,void 0,this),r("span",{class:"minimap-zoom",children:[Math.round(c.scale*100),"%"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function uI(){let e=st.value.size,t=Yd("--selection-bar-height"),n=oe(()=>{let l=Array.from(st.value);if(l.length===0)return;_u(l),$n()},[]),o=oe(()=>{let l=Array.from(st.value);if(l.length===0)return;Ns({title:"Group",childIds:l}),$n()},[]),i=oe(()=>{let l=Array.from(st.value);for(let c=0;c<l.length;c++)for(let u=c+1;u<l.length;u++)yr(l[c],l[u],"relation");$n()},[]),s=oe(()=>{let l=Array.from(st.value);for(let c of l)Xr(c);$n()},[]);if(e===0)return null;let a=e>=2;return r("div",{class:"selection-bar",role:"toolbar","aria-label":"Selection",ref:t,children:[r("span",{class:"selection-bar-count",children:[e," node",e!==1?"s":""," selected"]},void 0,!0,void 0,this),a&&r(be,{children:[r("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),r(_e,{label:"Align left",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Align left",onClick:()=>am("left"),children:r("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:[r("line",{x1:"2.5",y1:"2",x2:"2.5",y2:"14"},void 0,!1,void 0,this),r("rect",{x:"5",y:"3.5",width:"8",height:"3.5",rx:"1"},void 0,!1,void 0,this),r("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),r(_e,{label:"Align top",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Align top",onClick:()=>am("top"),children:r("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:[r("line",{x1:"2",y1:"2.5",x2:"14",y2:"2.5"},void 0,!1,void 0,this),r("rect",{x:"3.5",y:"5",width:"3.5",height:"8",rx:"1"},void 0,!1,void 0,this),r("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),r(_e,{label:"Distribute horizontally",body:"Evens the gaps. A selection that cannot fit flows into a clean row instead of overlapping.",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Distribute",disabled:e<3,onClick:()=>qk(),children:r("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"1.5","aria-hidden":"true",children:[r("rect",{x:"1.5",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),r("rect",{x:"6.25",y:"5",width:"3.5",height:"6",rx:"1"},void 0,!1,void 0,this),r("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),r(_e,{label:"Auto-arrange selection",side:"up",children:r("button",{type:"button",class:"selection-bar-icon","aria-label":"Auto-arrange",onClick:()=>Gk(),children:r(Tr,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),r(_e,{label:"Group the selection",shortcut:"G",side:"up",children:r("button",{type:"button",class:"selection-bar-action",onClick:o,children:[r("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:r("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),r(_e,{label:"Connect every pair",side:"up",children:r("button",{type:"button",class:"selection-bar-action",onClick:i,children:"Connect"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(_e,{label:"Pin to agent context",side:"up",children:r("button",{type:"button",class:"selection-bar-action is-pin",onClick:n,children:[r("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),r("span",{class:"selection-bar-sep"},void 0,!1,void 0,this),r(_e,{label:"Delete selection",side:"up",children:r("button",{type:"button",class:"selection-bar-icon is-danger","aria-label":"Delete selection",onClick:s,children:r("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:[r("path",{d:"M2.5 4 H13.5"},void 0,!1,void 0,this),r("path",{d:"M5.5 4 V2.5 H10.5 V4"},void 0,!1,void 0,this),r("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),r(_e,{label:"Clear selection",shortcut:"Esc",side:"up",children:r("button",{type:"button",class:"selection-bar-icon",onClick:$n,"aria-label":"Clear selection",children:r(Tt,{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 dp(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 pp(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 DL={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"vetoed"},BL={todo:"queued","in-progress":"running",blocked:"awaiting",done:"done",cancelled:"cancelled"},dI=[{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"}],FL=Object.fromEntries(dI.map((e)=>[e.id,e.hint])),HL={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 Pg(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 UL({item:e}){let t=DL[e.status]??"queued",n=e.nodeIds[0];return r("li",{class:`session-item status-${t}`,"data-work-item-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("button",{type:"button",class:"session-item-title",disabled:!n,onClick:()=>n&&$t(n),children:e.title},void 0,!1,void 0,this),e.detail&&r("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"session-item-status",children:BL[e.status]??t},void 0,!1,void 0,this),r("span",{class:"session-item-time",children:Pg(e.updatedAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function pI({gate:e,now:t}){let[n,o]=E(null),i=async(l)=>{o(l),await EC(e,l),o(null)},s=e.nodeIds[0],a=dp(e,t);return r("li",{class:"session-item status-awaiting session-gate","data-gate-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("button",{type:"button",class:"session-item-title",disabled:!s,onClick:()=>s&&$t(s),children:e.title},void 0,!1,void 0,this),e.detail&&r("div",{class:"session-item-detail",children:e.detail},void 0,!1,void 0,this),a!==null&&r("div",{class:"session-gate-ttl","data-testid":"gate-countdown",children:["auto-holds in ",pp(a)," if unanswered"]},void 0,!0,void 0,this),r("div",{class:"session-gate-actions",children:[r("button",{type:"button",class:"session-gate-approve",disabled:n!==null,onClick:()=>void i("approved"),children:n==="approved"?"Approving…":"Approve"},void 0,!1,void 0,this),r("button",{type:"button",class:"session-gate-reject",disabled:n!==null,onClick:()=>void i("rejected"),children:n==="rejected"?"Rejecting…":"Reject"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"session-item-time",children:Pg(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function fI({gate:e}){let[t,n]=E(!1);return r("li",{class:"session-item status-vetoed session-gate-held","data-gate-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("span",{class:"session-item-title",children:e.title},void 0,!1,void 0,this),r("div",{class:"session-item-detail",children:"Auto-held — no answer in time, the action did not proceed."},void 0,!1,void 0,this),r("div",{class:"session-gate-actions",children:r("button",{type:"button",class:"session-gate-reject",disabled:t,onClick:()=>{n(!0),AC(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),r("span",{class:"session-item-status",children:"held"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function jL(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 mI({gate:e}){return r("li",{class:`session-item status-${e.status}`,"data-gate-id":e.id,children:[r("span",{class:"session-glyph","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-item-main",children:[r("span",{class:"session-item-title",children:e.title},void 0,!1,void 0,this),r("div",{class:"session-item-detail",children:jL(e)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function hI(){let e=To.value,t=st.value.size,[n,o]=E(!1),i=(s)=>{o(!0),_C(s).finally(()=>o(!1))};return r("div",{class:`session-scope${e?" is-fenced":""}`,"data-testid":"session-scope",children:[r("span",{class:"session-scope-dot","aria-hidden":"true"},void 0,!1,void 0,this),e?r(be,{children:[r("span",{class:"session-scope-text",children:["Scoped to ",r("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),r("button",{type:"button",class:"session-scope-action",disabled:n,onClick:()=>i(null),children:"Clear"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r("span",{class:"session-scope-text",children:"Unscoped — the agent may write anywhere"},void 0,!1,void 0,this),r(_e,{label:t===0?"Select nodes on the canvas first":"Fence the agent to the selected nodes",align:"end",children:r("button",{type:"button",class:"session-scope-action",disabled:n||t===0,onClick:()=>i([...st.value]),children:["Fence to selection",t>0?` (${t})`:""]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ZL(e){if(e==="browser")return"you";return en.value.find((n)=>n.sessionId===e||n.source===e)?.label??e}function WL({entry:e}){let t=Wl.value.has(e.id);return r("li",{class:`session-timeline-row tone-${HL[e.kind]??"muted"}`,children:[r("span",{class:"session-timeline-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("div",{class:"session-timeline-main",children:[r("div",{class:"session-timeline-head",children:[r("span",{class:"session-timeline-label",children:e.label},void 0,!1,void 0,this),e.who&&r("span",{class:"session-timeline-who",style:{"--identity-color":So(e.who)},children:ZL(e.who)},void 0,!1,void 0,this),r("span",{class:"session-item-time",children:Pg(e.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"session-timeline-body",children:e.body},void 0,!1,void 0,this),e.undoable&&!t&&r("button",{type:"button",class:"session-timeline-undo","data-testid":"timeline-undo",onClick:()=>void sg(e),children:[r(km,{size:14},void 0,!1,void 0,this)," undo this edit"]},void 0,!0,void 0,this),t&&r("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 gI(){let e=Co.value,t=nr();if(!eo.value&&e.length===0)return null;return r("aside",{class:"session-panel","aria-label":"Agent controls",children:[r("header",{class:"session-panel-header",children:[r("span",{class:"session-panel-title",children:"Agent controls"},void 0,!1,void 0,this),r("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),r("button",{type:"button",class:"session-collapse","aria-label":"Collapse agent controls",onClick:()=>eo.value=!1,disabled:e.length>0,children:r(oi,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(hI,{},void 0,!1,void 0,this),r("div",{class:"session-panel-scroll",children:[r("ul",{class:"session-list","aria-label":"Approvals",children:[e.map((n)=>r(pI,{gate:n,now:t},n.id,!1,void 0,this)),os.value.map((n)=>r(fI,{gate:n},n.id,!1,void 0,this)),ig.value.map((n)=>r(mI,{gate:n},n.id,!1,void 0,this))]},void 0,!0,void 0,this),fa.value.map((n)=>r("div",{class:"session-item",children:[r("span",{class:"session-item-main",children:n.label},void 0,!1,void 0,this),r("button",{type:"button",class:"session-end",onClick:()=>void ql(n),children:"End attachment"},void 0,!1,void 0,this)]},n.sessionId,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function yI(){q(()=>()=>{eo.value=!1},[]);let e=mi.value,t=SC.value,n=Co.value,o=os.value,i=ig.value,s=IC.value,[a,l]=E(!1),[c,u]=E(null),d=nr();if(q(()=>{yi()},[]),!(eo.value||n.length>0))return r("aside",{class:"session-panel is-collapsed","aria-label":"Session (collapsed)",children:[r("button",{type:"button",class:"session-collapse",onClick:()=>{eo.value=!0},"aria-label":"Expand session panel",children:"‹"},void 0,!1,void 0,this),e&&r("span",{class:`session-collapsed-live phase-${e.phase}`,"aria-label":`Session live: ${pi(e)}`,children:[r("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this),r("span",{class:"session-collapsed-label",children:"Session"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return r("aside",{class:"session-panel","aria-label":"Session",children:[r("header",{class:"session-panel-header",children:[r("span",{class:"session-panel-title",children:"Session"},void 0,!1,void 0,this),e&&r(_e,{label:pi(e),tapToOpen:!0,children:r("span",{class:`session-live phase-${e.phase}`,children:[r("span",{class:"session-live-dot","aria-hidden":"true"},void 0,!1,void 0,this),"live"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),e&&r(_e,{label:"End this session",body:"A receipt and a snapshot of the board follow.",align:"end",children:r("button",{type:"button",class:"session-end",onClick:()=>void ql(e),children:"End"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("button",{type:"button",class:"session-collapse",onClick:()=>{eo.value=!1},"aria-label":"Collapse session panel",children:r(oi,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(hI,{},void 0,!1,void 0,this),(()=>{let f=s.find((m)=>m.undoable&&!Wl.value.has(m.id));if(!f)return null;return r("div",{class:"session-undo-row","data-testid":"session-undo-row",children:[r("span",{class:"session-undo-text",children:["Agent edit on top: ",f.body]},void 0,!0,void 0,this),r("button",{type:"button",class:"session-undo-btn",onClick:()=>void sg(f),children:[r(km,{size:14},void 0,!1,void 0,this)," Undo"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)})(),r("div",{class:"session-panel-body",children:[r("section",{class:"session-section",children:(()=>{let f=t.filter((C)=>C.status==="in-progress"||C.status==="todo").length,m=t.filter((C)=>C.status!=="cancelled"),h=m.filter((C)=>C.status==="done").length,g=t.length-m.length,v=n.length>0,b=a||v,x=f>0?`${f} running`:m.length>0?`${h}/${m.length} done${g>0?` · ${g} cancelled`:""}`:t.length>0?`${t.length} cancelled`:"none yet";return r(be,{children:[r("button",{type:"button",class:"session-section-toggle","aria-expanded":b,"data-testid":"work-items-toggle",onClick:()=>l((C)=>!C),children:[r("span",{class:"session-section-title",children:"Work items"},void 0,!1,void 0,this),r("span",{class:"session-work-summary",children:[f>0&&r("span",{class:"session-work-dot","aria-hidden":"true"},void 0,!1,void 0,this),x]},void 0,!0,void 0,this),r("span",{class:`session-section-chevron${b?" is-open":""}`,"aria-hidden":"true",children:r(oi,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b&&(n.length===0&&o.length===0&&i.length===0&&t.length===0?r("div",{class:"session-empty",children:"No work items yet — the agent's tasks and gates appear here."},void 0,!1,void 0,this):r("ul",{class:"session-list","aria-live":"polite","aria-label":"Work items and gates",children:[n.map((C)=>r(pI,{gate:C,now:d},C.id,!1,void 0,this)),o.map((C)=>r(fI,{gate:C},C.id,!1,void 0,this)),i.map((C)=>r(mI,{gate:C},C.id,!1,void 0,this)),t.map((C)=>r(UL,{item:C},C.id,!1,void 0,this))]},void 0,!0,void 0,this))]},void 0,!0,void 0,this)})()},void 0,!1,void 0,this),r("section",{class:"session-section",children:[r("h3",{class:"session-section-title",children:"Timeline"},void 0,!1,void 0,this),r("div",{class:"session-timeline-filters",role:"group","aria-label":"Filter timeline",children:dI.map((f)=>r("button",{type:"button",class:`activity-filter${rs.value===f.id?" is-active":""}`,"aria-pressed":rs.value===f.id,onMouseEnter:()=>u(f.id),onMouseLeave:()=>u((m)=>m===f.id?null:m),onFocus:()=>u(f.id),onBlur:()=>u((m)=>m===f.id?null:m),onClick:()=>{rs.value=f.id},children:f.label},f.id,!1,void 0,this))},void 0,!1,void 0,this),r("div",{class:"session-timeline-hint","data-testid":"timeline-filter-hint",children:FL[c??rs.value]},void 0,!1,void 0,this),s.length===0?r("div",{class:"session-empty",children:rs.value==="all"?"Nothing recorded yet.":"Nothing of this kind yet."},void 0,!1,void 0,this):r("ul",{class:"session-list session-timeline","aria-live":"polite","aria-label":"Timeline",children:s.map((f)=>r(WL,{entry:f},f.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Ng(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 vI=(e)=>e.map((t)=>t.title).join(", ");function bI(e){let t=new Date(e);return Number.isNaN(t.getTime())?"":`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function qL({context:e,label:t,snapshotId:n}){let[o,i]=E(!1),[s,a]=E([]),[l,c]=E(!1),[u,d]=E(null),[p,f]=E(!1),m=e.edited.length>0&&e.edited.every((x)=>s.includes(x.id))?"undone":l?"kept":null;q(()=>{a([]),c(!1),d(null)},[e]);let h=async(x)=>{if(!n||p)return;f(!0);try{let C=await NC(n,x.filter((y)=>!s.includes(y.id)));return a((y)=>[...y,...C.restored]),C}finally{f(!1)}},v=[{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((x)=>e[x.key].length>0);if(v.length===0&&e.changedSinceRead.length===0)return null;let b=Fn.value?.kind==="receipt";return r("div",{class:"session-receipt-context","data-testid":"session-receipt-context",children:[e.changedSinceRead.length>0&&r("div",{class:"session-receipt-warn",children:[r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:r("path",{d:gi.warn},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{children:[vI(e.changedSinceRead)," changed after ",t," read"," ",e.changedSinceRead.length===1?"it":"them","."]},void 0,!0,void 0,this),r("button",{type:"button",class:"session-receipt-mini",disabled:o,onClick:()=>{let x=e.changedSinceRead.length===1?"it":"them";ma(`${e.changedSinceRead.map((C)=>`“${C.title}”`).join(", ")} changed after you read ${x} — read ${x} again before relying on ${x}.`).then((C)=>i(C))},children:o?"Told":`Tell ${t}`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v.map((x)=>r("div",{class:"session-receipt-context-row","data-row":x.key,children:[r("div",{class:"session-receipt-context-head",children:[x.glyph==="pin"?r(uo,{},void 0,!1,void 0,this):r("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:r("path",{d:gi[x.glyph]},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"session-receipt-context-name",children:x.name},void 0,!1,void 0,this),r("span",{class:"session-receipt-context-count",children:e[x.key].length},void 0,!1,void 0,this),x.key==="pinned"&&r("button",{type:"button",class:"session-receipt-mini",disabled:e.pinned.some((C)=>C.boardId&&C.boardId!==se.value),onClick:()=>Kk(e.pinned.map((C)=>C.id)),children:"Unpin"},void 0,!1,void 0,this),x.key==="edited"&&n&&r("button",{type:"button",class:"session-receipt-mini",disabled:m!==null||p||e.edited.some((C)=>C.boardId&&C.boardId!==se.value),onClick:()=>{h(e.edited).then((C)=>{if(C?.ok)c(!0)})},children:m==="undone"?"✓ Undone":m==="kept"?"Kept your edits":"Undo"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x.key==="edited"&&m&&r("div",{class:"session-receipt-context-items",children:m==="undone"?"every card restored":"cards you edited since were left alone"},void 0,!1,void 0,this),x.key==="edited"?r("ul",{class:"session-receipt-edits",children:e.edited.map((C)=>r(KL,{node:C,canUndo:n!==null,undoing:p,open:u===or(C),onToggle:()=>d(u===or(C)?null:or(C)),undone:s.includes(C.id),onUndo:()=>void h([C])},or(C),!1,void 0,this))},void 0,!1,void 0,this):r("div",{class:"session-receipt-context-items",children:x.key==="pinned"?e.pinned.map((C)=>C.reason?`${C.title} — “${C.reason}”`:C.title).join("; "):vI(e[x.key])},void 0,!1,void 0,this)]},x.key,!0,void 0,this)),r("button",{type:"button",role:"switch","aria-checked":b,class:`session-receipt-lens${b?" is-on":""}`,onClick:()=>Gl(!b),children:[r("span",{class:"session-receipt-lens-track","aria-hidden":"true",children:r("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 GL(e,t){let n=(d)=>d.match(/\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu)??[],o=n(e),i=n(t),s=Array.from({length:o.length+1},()=>new Uint16Array(i.length+1));for(let d=o.length-1;d>=0;d--)for(let p=i.length-1;p>=0;p--)s[d][p]=o[d]===i[p]?s[d+1][p+1]+1:Math.max(s[d+1][p],s[d][p+1]);let a=[],l=[],c=0,u=0;while(c<o.length||u<i.length)if(c<o.length&&u<i.length&&o[c]===i[u])a.push({text:o[c++],changed:!1}),l.push({text:i[u++],changed:!1});else if(c<o.length&&(u===i.length||s[c+1][u]>=s[c][u+1]))a.push({text:o[c++],changed:!0});else l.push({text:i[u++],changed:!0});return[a,l]}function KL({node:e,canUndo:t,undoing:n,open:o,onToggle:i,undone:s,onUndo:a}){let l=!e.boardId||e.boardId===se.value,c=l?H.value.get(e.id):void 0,u=Ge.value.find((m)=>m.id===e.boardId),d=Ke(()=>o?GL(e.before??"",e.after??""):[],[o,e.before,e.after]),p=D(null);Me(()=>{for(let m of p.current?.querySelectorAll(".session-receipt-diff-text")??[]){let h=m.querySelector("del, ins");if(h)m.scrollTop=h.getBoundingClientRect().top-m.getBoundingClientRect().top-24}},[d]);let f=c?.lastEditedBy?.actor==="human";return r("li",{class:"session-receipt-edit",children:[r("span",{class:"session-receipt-edit-line",children:[r("span",{children:[e.title,e.change?r("span",{class:"session-receipt-edit-change",children:[" — ",e.change]},void 0,!0,void 0,this):null]},void 0,!0,void 0,this),e.before!==void 0&&r("button",{type:"button",class:"session-receipt-link","aria-expanded":o,onClick:i,children:o?"Hide change":"See change"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o&&r("span",{ref:p,class:"session-receipt-diff-pair",children:[d.map((m,h)=>r("span",{class:"session-receipt-diff-side",children:[r("span",{class:"session-receipt-diff-label",children:h===0?"Before":"After"},void 0,!1,void 0,this),r("span",{class:"session-receipt-diff-text",children:m.length?m.map(({text:g,changed:v},b)=>g==="…"&&(b===0||b===m.length-1)?r("span",{class:"session-receipt-diff-cut",children:g},b,!1,void 0,this):v?h===0?r("del",{children:g},b,!1,void 0,this):r("ins",{children:g},b,!1,void 0,this):g):"Empty"},void 0,!1,void 0,this)]},h,!0,void 0,this)),t&&r("span",{class:"session-receipt-undo",children:[c?r("button",{type:"button",class:"session-receipt-mini",disabled:s||f||n,onClick:a,children:s?"✓ Undone":f?"You edited it since":"Undo this card"},void 0,!1,void 0,this):u&&!l?r("button",{type:"button",class:"session-receipt-mini",onClick:()=>void Mn(u.id),children:["Open ",u.name," to undo"]},void 0,!0,void 0,this):r("span",{class:"session-receipt-edit-change",children:"Card no longer on this board"},void 0,!1,void 0,this),r("span",{class:"session-receipt-edit-change",children:c?s?"the card shows Before again":f?"undo would lose your edit":e.before?.includes("…")||e.after?.includes("…")?"undoes the whole card":"puts back the text from before":u&&!l?`it is on ${u.name}`:""},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 xI({onOpenSnapshots:e}){let t=ns.value,[n,o]=E(null),[i,s]=E(!1);if(q(()=>o(null),[t]),!xt.value||!t)return null;let a=t.snapshot?.boardId===se.value,l=Ge.value.find((f)=>f.id===t.snapshot?.boardId),c=async()=>{if(!t.snapshot||!a)return;s(!0);try{let f=await Gt(`/api/canvas/snapshots/${encodeURIComponent(t.snapshot.id)}/diff`,{headers:{"x-pmx-workbench":"1"}});if(f.ok){let m=await f.json();o(Ng(m.diff)??{added:0,removed:0,modified:0})}}finally{s(!1)}},u=bI(t.endedAt),d=t.startedAt?bI(t.startedAt):"",p=t.endedBy==="human"?"ended by you":t.endedBy==="idle-timeout"?"ended on idle timeout":t.endedBy==="agent"?"ended by the agent":"";return r("div",{class:"session-receipt","data-testid":"session-receipt",role:"status",children:[r("div",{class:"session-receipt-head",children:[r("span",{class:"session-receipt-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"session-receipt-title",children:t.sessions>1?`${t.sessions} sessions ended${u?` · ${u}`:""}`:`What ${t.labels[0]} did`},void 0,!1,void 0,this),r("button",{type:"button",class:"session-receipt-close",onClick:Ud,"aria-label":"Dismiss receipt",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t.sessions>1?r("div",{class:"session-receipt-who",children:t.labels.join(", ")},void 0,!1,void 0,this):r("div",{class:"session-receipt-who","data-testid":"session-receipt-span",children:[`This session · ${d?`${d}–`:""}${u}`,t.snapshot?"saved as a snapshot":"",p].filter(Boolean).join(" · ")},void 0,!1,void 0,this),r("div",{class:"session-receipt-tiles",children:[r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Items"},void 0,!1,void 0,this),r("span",{class:"session-receipt-tile-value",children:t.counts.items},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Done"},void 0,!1,void 0,this),r("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&&r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Cancelled"},void 0,!1,void 0,this),r("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&&r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Rejected"},void 0,!1,void 0,this),r("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&&r("div",{class:"session-receipt-tile",children:[r("span",{class:"session-receipt-tile-label",children:"Held"},void 0,!1,void 0,this),r("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),r(qL,{context:t.context,label:t.labels.join(", "),snapshotId:t.sessions===1?t.snapshot?.id??null:null},void 0,!1,void 0,this),r("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&&r("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),r("div",{class:"session-receipt-actions",children:[t.snapshot&&r("button",{type:"button",class:"session-receipt-primary",disabled:i||!a&&!l,onClick:()=>a?void c():l&&void Mn(l.id),children:!a&&l?`Open ${l.name} to compare`:i?"Comparing…":"View diff"},void 0,!1,void 0,this),r(_e,{label:"Open the History drawer",body:"Saved boards and past sessions.",side:"up",align:"end",children:r("button",{type:"button",class:"session-receipt-secondary",onClick:e,children:"History"},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 VL=[{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:Ft("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:Ft("0"),desc:"Reset viewport to origin"},{keys:`${Ft("+")} / ${Ft("−")}`,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:wl?"Delete / ⌫":"Delete / Backspace",desc:"Delete the selection (or the focused node)"},{keys:wl?"⌘Z / ⇧⌘Z":"Ctrl+Z / Ctrl+Y",desc:"Undo / redo — agent edits included"},{keys:"Esc",desc:"Close overlay first, then clear selection and view filters"}]},{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 wI({onClose:e}){return r("div",{class:"shortcut-overlay-backdrop",onMouseDown:e,children:r("div",{class:"shortcut-overlay",onMouseDown:(t)=>t.stopPropagation(),children:[r("div",{class:"shortcut-overlay-header",children:[r("span",{class:"shortcut-overlay-title",children:"Keyboard Shortcuts"},void 0,!1,void 0,this),r("span",{class:"shortcut-overlay-hint",children:["Press ",r("kbd",{children:"?"},void 0,!1,void 0,this)," or ",r("kbd",{children:"Esc"},void 0,!1,void 0,this)," to close"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"shortcut-overlay-body",children:VL.map((t)=>r("div",{class:"shortcut-group",children:[r("div",{class:"shortcut-group-title",children:t.title},void 0,!1,void 0,this),t.shortcuts.map((n)=>r("div",{class:"shortcut-row",children:[r("kbd",{class:"shortcut-keys",children:n.keys},void 0,!1,void 0,this),r("span",{class:"shortcut-desc",children:tt()&&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 kI="Before session · ";function SI(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 fp(e){if(!e.startsWith(kI))return null;let t=e.slice(kI.length),n=t.lastIndexOf(" · ");return n>0?t.slice(0,n):t}function _I({open:e,onClose:t,anchorRef:n}){let[o,i]=E([]),[s,a]=E(!1),[l,c]=E(!1),[u,d]=E(null),[p,f]=E(""),[m,h]=E(null),[g,v]=E({}),b=D(null),x=D(null);q(()=>{if(!e)return;a(!0),xk().then((w)=>{i(w),a(!1)})},[e]),q(()=>{if(e)setTimeout(()=>x.current?.focus(),50)},[e]),q(()=>{if(!e)return;let w=(P)=>{let L=b.current,N=n.current;if(L&&!L.contains(P.target)&&N&&!N.contains(P.target))t()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[e,t]),q(()=>{if(!e)return;let w=(P)=>{if(P.key==="Escape")t()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,t]);let C=oe(async()=>{let w=p.trim();if(!w)return;c(!0);let P=await wk(w);if(c(!1),P.ok&&P.snapshot)i((L)=>[P.snapshot,...L]),f("")},[p]),y=oe(async(w)=>{h(null),d(w);let P=await kk(w);if(d(null),P.ok)t()},[t]),k=oe(async(w)=>{if((await Sk(w)).ok)i((L)=>L.filter((N)=>N.id!==w));h(null)},[]),_=oe(async(w)=>{v((L)=>({...L,[w]:"loading"}));let P=await pe("snapshotDiff",`/api/canvas/snapshots/${encodeURIComponent(w)}/diff`,{});v((L)=>({...L,[w]:Ng(P.diff)??{added:0,removed:0,modified:0}}))},[]);if(!e)return null;let I=(w,P)=>m?.id===w.id?r(be,{children:[r("button",{type:"button",class:`snapshot-action-btn ${m.action==="delete"?"snapshot-action-confirm":"snapshot-action-restore"}`,onClick:()=>m.action==="delete"?k(w.id):y(w.id),disabled:u!==null,children:m.action==="delete"?"Delete":u===w.id?"Restoring…":"Confirm"},void 0,!1,void 0,this),r("button",{type:"button",class:"snapshot-action-btn",onClick:()=>h(null),disabled:u!==null,children:"Cancel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this):r(be,{children:[r(_e,{label:"Restore this snapshot",body:tt()?"Replaces the current canvas.":"Replaces the current canvas (undoable).",align:"end",children:r("button",{type:"button",class:"snapshot-action-btn snapshot-action-restore",onClick:()=>h({id:w.id,action:"restore"}),disabled:u!==null,children:u===w.id?"Restoring…":P},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Delete this snapshot",align:"end",children:r("button",{type:"button",class:"snapshot-action-btn snapshot-action-delete",onClick:()=>h({id:w.id,action:"delete"}),"aria-label":"Delete snapshot",disabled:u!==null,children:r(Tt,{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);return r("div",{ref:b,class:"snapshot-panel","data-testid":"history-drawer",role:"dialog","aria-label":"History",children:[r("div",{class:"snapshot-panel-header",children:[r("span",{class:"snapshot-panel-title",children:"History"},void 0,!1,void 0,this),r("span",{class:"snapshot-panel-sub",children:"snapshots + sessions"},void 0,!1,void 0,this),r("span",{class:"snapshot-panel-spacer"},void 0,!1,void 0,this),r("button",{type:"button",class:"snapshot-panel-close",onClick:t,"aria-label":"Close history",children:r(Tt,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-save-form",children:[r("input",{ref:x,type:"text",class:"snapshot-name-input",value:p,onInput:(w)=>f(w.target.value),onKeyDown:(w)=>{if(w.key==="Enter")C()},placeholder:"Save a snapshot as…","aria-label":"Snapshot name",maxLength:80,disabled:l},void 0,!1,void 0,this),r("button",{type:"button",class:"snapshot-save-btn",onClick:C,disabled:!p.trim()||l,children:l?"…":"Save"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-restore-note",children:tt()?"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),r("div",{class:"snapshot-list",children:[s&&r("div",{class:"snapshot-empty",children:"Loading…"},void 0,!1,void 0,this),!s&&o.length===0&&r("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)=>fp(w.name)===null),...o.some((w)=>fp(w.name)!==null)?[{id:"__sessions-header__"}]:[],...o.filter((w)=>fp(w.name)!==null)].map((w)=>{if(w.id==="__sessions-header__")return r("div",{class:"snapshot-section-header","data-testid":"history-sessions-header",children:"Sessions"},w.id,!1,void 0,this);let P=fp(w.name),L=g[w.id];if(P!==null)return r("div",{class:"snapshot-item is-session","data-testid":"history-session",children:[r("div",{class:"snapshot-item-head",children:[r("span",{class:"snapshot-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"snapshot-item-name",children:["Agent session — ",P]},void 0,!0,void 0,this),r("span",{class:"snapshot-item-time",children:SI(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-meta",children:["snapshot at session start · ",w.nodeCount," node",w.nodeCount!==1?"s":"",L&&L!=="loading"&&r("span",{class:"snapshot-item-diff",children:[" ","· since: ",L.added," added · ",L.removed," removed · ",L.modified," modified"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-actions is-session",children:[r("button",{type:"button",class:"snapshot-action-btn snapshot-action-diff",disabled:L==="loading",onClick:()=>void _(w.id),children:L==="loading"?"Comparing…":"View diff"},void 0,!1,void 0,this),I(w,"Restore pre-state")]},void 0,!0,void 0,this)]},w.id,!0,void 0,this);return r("div",{class:"snapshot-item","data-testid":"history-snapshot",children:[r("div",{class:"snapshot-item-head",children:[r("span",{class:"snapshot-item-glyph","aria-hidden":"true",children:"◫"},void 0,!1,void 0,this),r("span",{class:"snapshot-item-name",children:w.name},void 0,!1,void 0,this),r("span",{class:"snapshot-item-time",children:SI(w.createdAt)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-meta",children:[w.nodeCount," node",w.nodeCount!==1?"s":"",w.edgeCount>0?` · ${w.edgeCount} edge${w.edgeCount!==1?"s":""}`:""," · ",Qd(w.createdAt)]},void 0,!0,void 0,this),r("div",{class:"snapshot-item-actions",children:I(w,"Restore")},void 0,!1,void 0,this)]},w.id,!0,void 0,this)})]},void 0,!0,void 0,this),r("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 XL=8;function CI({fallbackName:e}){let[t,n]=E(!1),o=D(null),i=D(null),s=D(null);Me(()=>{if(!t)return;let p=(m)=>{if(m.target instanceof Node&&!o.current?.contains(m.target)&&!s.current?.contains(m.target))n(!1)},f=(m)=>{if(m.key==="Escape")m.stopPropagation(),n(!1),i.current?.focus()};return document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",f,!0),()=>{document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",f,!0)}},[t]);let a=Yn(),l=!io.value?e:a&&!ut.value?a.name:"Home",c=Ge.value.filter((p)=>ut.value||p.id!==se.value).slice(0,XL),u=i.current?.getBoundingClientRect(),d=(p)=>{n(!1),Mn(p)};return r("span",{class:"board-switcher",ref:o,children:[r("button",{ref:i,type:"button",class:"top-bar-title board-switcher-button","aria-haspopup":"menu","aria-expanded":t,"aria-label":`Board: ${l}. Switch board`,onClick:()=>n((p)=>!p),children:[r("span",{class:"board-switcher-name",children:l},void 0,!1,void 0,this),r("span",{class:"board-switcher-caret","aria-hidden":"true",children:r(js,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t&&u&&r(Ws,{children:r("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:[c.length>0&&r("div",{class:"board-switcher-heading",children:"Recent boards"},void 0,!1,void 0,this),r("div",{class:"board-switcher-recents",children:c.map((p)=>r("div",{class:"board-switcher-row",children:[r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>d(p.id),children:[r("span",{class:"board-switcher-icon","aria-hidden":"true",children:r(zu,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),r("span",{class:"board-switcher-item-copy",children:[r("span",{class:"board-switcher-item-name",children:p.name},void 0,!1,void 0,this),r("span",{class:"board-switcher-item-folder",children:p.folder?.split("/").join(" / ")||"Unfiled"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"board-switcher-item-meta",children:[p.nodeCount," ",p.nodeCount===1?"node":"nodes"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(ho,{board:p},void 0,!1,void 0,this)]},p.id,!0,void 0,this))},void 0,!1,void 0,this),r("div",{class:"board-switcher-actions",children:[r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>{n(!1),Ag()},children:[r("span",{class:"board-switcher-icon","aria-hidden":"true",children:r(aS,{size:18},void 0,!1,void 0,this)},void 0,!1,void 0,this),"New board…"]},void 0,!0,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:()=>d(null),children:[r("span",{class:"board-switcher-icon","aria-hidden":"true",children:r(Tr,{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 TI=3,II={"waiting-approval":0,thinking:1,tooling:2,idle:3};function JL(){let[e,t]=E(null),n=D(null);Me(()=>{if(!e)return;let d=(m)=>{if(!n.current?.contains(m.target)&&!e.button.contains(m.target))t(null)},p=(m)=>{if(m.key==="Escape"&&!m.defaultPrevented)m.preventDefault(),t(null),e.button.focus({preventScroll:!0})},f=()=>t(null);return document.addEventListener("pointerdown",d,!0),document.addEventListener("keydown",p),window.addEventListener("resize",f),()=>{document.removeEventListener("pointerdown",d,!0),document.removeEventListener("keydown",p),window.removeEventListener("resize",f)}},[e]);let o=fa.value;if(q(()=>{if(e&&!e.button.isConnected)t(null)},[o,e]),!xt.value||o.length===0)return null;let i=o.filter((d)=>!d.parentAgentId||!o.some((p)=>p.sessionId!==d.sessionId&&!p.parentAgentId&&(p.sessionId===d.parentAgentId||p.source===d.parentAgentId))),s=[...i].sort((d,p)=>(II[d.phase]??4)-(II[p.phase]??4)),a=s.slice(0,TI),l=s.slice(TI),c=i.reduce((d,p)=>(d[p.phase]=(d[p.phase]??0)+1,d),{}),u=[c["waiting-approval"]&&`${c["waiting-approval"]} waiting on approval`,c.thinking&&`${c.thinking} thinking`,c.tooling&&`${c.tooling} running tools`,c.idle&&`${c.idle} idle`].filter(Boolean).join(", ");return r(be,{children:[r("span",{class:"agent-chips",children:a.map((d)=>{let p=d.parentAgentId?0:en.value.filter((f)=>f.parentAgentId!=null&&(f.parentAgentId===d.sessionId||f.parentAgentId===d.source)).length;return r(_e,{label:`Agent session — ${d.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:r("span",{class:`agent-chip phase-${d.phase}`,"data-phase":d.phase,style:{"--identity-color":So(d.sessionId)},children:[r("button",{type:"button",class:"agent-chip-initial","aria-label":`${d.label} session details`,"aria-expanded":e?.id===d.sessionId,"aria-haspopup":"dialog",onClick:(f)=>{f.stopPropagation(),t(e?.id===d.sessionId?null:{id:d.sessionId,button:f.currentTarget})},children:[Md(d.label),r("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"agent-chip-label",children:pi(d)},void 0,!1,void 0,this),r("span",{class:"agent-chip-who hud-collapsible-text",children:d.label},void 0,!1,void 0,this),r(EI,{session:d},void 0,!1,void 0,this),p>0&&r("span",{class:"agent-chip-workers",children:["+",p," worker",p===1?"":"s"]},void 0,!0,void 0,this),r("button",{type:"button",class:"agent-chip-end","aria-label":`End ${d.label} session`,onClick:(f)=>{f.stopPropagation(),ql({source:d.source,agentId:d.agentId})},children:r(Tt,{size:14},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},d.sessionId,!1,void 0,this)})},void 0,!1,void 0,this),l.length>0&&r(_e,{label:`${i.length} agent sessions attached`,tapToOpen:!0,body:`${i.length} agents on this board — ${u}. The most active wear their own chips; the rest are here, and idle agents' cursors leave the board until they work again.`,children:r("span",{class:"agent-chip agent-chip-more","data-testid":"agent-chip-more",children:["+",l.length," · ",i.length," agents"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),e&&a.filter((d)=>d.sessionId===e.id).map((d)=>r(Ws,{children:r("div",{ref:n,class:`agent-session-popover phase-${d.phase}`,role:"dialog","aria-label":`${d.label} session details`,style:{right:`${Math.max(12,window.innerWidth-e.button.getBoundingClientRect().right)}px`,top:`${e.button.getBoundingClientRect().bottom+8}px`},children:[r("div",{class:"agent-session-popover-head",children:[r("span",{class:"agent-chip-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("strong",{children:[d.label," · ",pi(d)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),r(EI,{session:d,popover:!0},void 0,!1,void 0,this),r("button",{type:"button",class:"session-receipt-link",onClick:()=>{eo.value=!0,t(null)},children:"Open session panel"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},d.sessionId,!1,void 0,this))]},void 0,!0,void 0,this)}function EI({session:e,popover:t=!1}){let n=e.session,o=n?[["read",n.read.length],["created",n.created.length],["edited",n.edited.length],["pinned",n.pinned.length]].filter(([,l])=>l>0):[],i=Fn.value,s=i?.kind==="live"&&i.sessionId===e.sessionId;if(o.length===0&&!s&&!t)return null;let a=o.map(([l,c])=>`${c} ${l}`).join(" · ")||"nothing yet";if(t)return r(be,{children:[r("span",{class:"agent-session-counts",children:a},void 0,!1,void 0,this),r("button",{type:"button",role:"switch","aria-checked":s,class:`session-receipt-lens${s?" is-on":""}`,onClick:()=>Gl(!s,{sessionId:e.sessionId}),children:[r("span",{class:"session-receipt-lens-track","aria-hidden":"true",children:r("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);return r("button",{type:"button",class:`agent-chip-touches${s?" is-on":""}`,"aria-pressed":s,"aria-label":`This session: ${o.map(([l,c])=>`${c} ${l}`).join(", ")||"nothing yet"}. ${s?"Show all cards":"Dim untouched cards"}`,onClick:(l)=>{l.stopPropagation(),Gl(!s,{sessionId:e.sessionId})},children:a},void 0,!1,void 0,this)}function YL(){let e=Co.value.length,t=e>0,n=nr(t?1000:0);if(!t)return null;let o=Co.value.map((i)=>dp(i,n)).filter((i)=>i!==null).sort((i,s)=>i-s)[0];return r(_e,{label:"Approval gates waiting on you",body:"Open agent controls to approve or reject. Unanswered gates auto-hold when the countdown runs out, even with the session beta off.",children:r("button",{type:"button",class:"gate-badge",onClick:()=>eo.value=!0,children:[e," gate",e===1?"":"s",o!==void 0&&` · ${pp(o)}`]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function QL(){let[e,t]=E(!1);if(!xt.value||mi.value)return null;return r(_e,{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:r("button",{type:"button",class:"start-session-btn","aria-label":"Start agent session beta",disabled:e,onClick:()=>{t(!0),vi().finally(()=>t(!1))},children:[r("span",{class:"start-session-dot","aria-hidden":"true"},void 0,!1,void 0,this),r("span",{class:"start-session-label",children:"Start agent session"},void 0,!1,void 0,this),r("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 AI(){let e=D(null);Me(()=>{let g=e.current,v=g?.querySelector(".top-bar-right");if(!g||!v)return;let b=()=>{let y=g.querySelector('.top-bar-more [aria-expanded="true"]');g.classList.remove("is-folded","is-compact");let k=()=>v.getBoundingClientRect().right>g.getBoundingClientRect().right-14;if(y||k())g.classList.add("is-folded");if(k())g.classList.add("is-compact")},x=new ResizeObserver(b);x.observe(g);let C=new MutationObserver(b);return C.observe(g,{childList:!0,characterData:!0,subtree:!0}),b(),()=>{x.disconnect(),C.disconnect()}},[]);let t=ao.value,n=cn.value,o=Ee.value,i=H.value.size,s=et.value.size,a=Ds.value,l=Array.from(H.value.values()).filter((g)=>g.type==="trace").length,[c,u]=E("");q(()=>{let g=!1;return Gt("/health").then((v)=>v.ok?v.json():null).then((v)=>{if(g||typeof v?.workspace!=="string"||!v.workspace)return;let b=v.workspace.replace(/[\\/]+$/,"").split(/[\\/]/).pop();if(b)u(b)}).catch(()=>{}),()=>{g=!0}},[]);let d=kg.value,p=d??(t==="connected"&&!n?"syncing":t),f=Yn(),m=n?[`${i} node${i!==1?"s":""}`,...s>0?[`${s} edge${s!==1?"s":""}`]:[],...l>0?[`${l} trace${l!==1?"s":""}`]:a?["trace armed"]:[]].join(" · "):"Syncing canvas…",h=()=>{let g=Jt();Hs(g.width,g.height)};return r("div",{class:"top-bar",ref:e,children:[r(_e,{label:`Canvas status: ${p}`,tapToOpen:!0,body:"Live updates stream in over SSE; amber means reconnecting.",align:"start",children:r("span",{class:`connection-dot ${d??t}`,"aria-label":`Canvas status: ${p}`},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(CI,{fallbackName:c||"PMX Canvas"},void 0,!1,void 0,this),f&&!ut.value&&r(ho,{board:f},void 0,!1,void 0,this),r("span",{class:"top-bar-meta hud-collapsible-text",children:xr.value?xr.value.slice(0,12):"…"},void 0,!1,void 0,this),!ut.value&&r("span",{class:"top-bar-meta hud-collapsible-text",children:m},void 0,!1,void 0,this),r("span",{class:"top-bar-spacer"},void 0,!1,void 0,this),r("div",{class:"top-bar-right",children:[r(JL,{},void 0,!1,void 0,this),r(YL,{},void 0,!1,void 0,this),r(dT,{},void 0,!1,void 0,this),r(YT,{},void 0,!1,void 0,this),!tt()&&r(QL,{},void 0,!1,void 0,this),!ut.value&&r(be,{children:[r("div",{class:"top-bar-sep"},void 0,!1,void 0,this),r("div",{class:"top-bar-actions",children:[se.value&&r(_e,{label:"Export board",body:"One HTML file of this board that anyone can open, no install needed.",children:r("button",{type:"button",class:"present-button",onClick:()=>{cs.value=!0},children:"Export"},void 0,!1,void 0,this)},void 0,!1,void 0,this),se.value&&r(_e,{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:r("button",{type:"button",class:"present-button",onClick:()=>{fl()},children:"Present"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Zoom out",shortcut:Ft("−"),children:r("button",{type:"button",class:"top-bar-btn",onClick:()=>ti(0.8),"aria-label":"Zoom out",children:r(fS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Reset zoom",shortcut:Ft("0"),children:r("button",{type:"button",class:"top-bar-zoom-label",onClick:()=>_r({x:0,y:0,scale:1},250),"aria-label":"Reset view",children:[Math.round(o.scale*100),"%"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Zoom in",shortcut:Ft("+"),children:r("button",{type:"button",class:"top-bar-btn",onClick:()=>ti(1.25),"aria-label":"Zoom in",children:r(pS,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),r(_e,{label:"Fit all",shortcut:"F",align:"end",children:r("button",{type:"button",class:"top-bar-btn",onClick:h,"aria-label":"Fit canvas",children:r(Nu,{},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r(eO,{boardOpen:!!se.value,onFit:h},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 eO({boardOpen:e,onFit:t}){let[n,o]=E(!1),i=D(null),s=D(null);Me(()=>{if(!n)return;let l=()=>[...i.current?.querySelectorAll('[role="menuitem"]')??[]];l()[0]?.focus();let c=(d)=>{if(d.key==="Escape")o(!1),s.current?.focus();else if(d.key==="ArrowDown"||d.key==="ArrowUp"){d.preventDefault();let p=l(),f=p.indexOf(document.activeElement),m=d.key==="ArrowDown"?f+1:f-1;p[(m+p.length)%p.length]?.focus()}},u=(d)=>{if(i.current&&!i.current.contains(d.target))o(!1)};return window.addEventListener("keydown",c),window.addEventListener("pointerdown",u),()=>{window.removeEventListener("keydown",c),window.removeEventListener("pointerdown",u)}},[n]);let a=(l)=>()=>{o(!1),l()};return r("div",{class:"top-bar-more",ref:i,children:[r("button",{ref:s,type:"button",class:"top-bar-btn","aria-label":"More: export, present, zoom, fit","aria-haspopup":"menu","aria-expanded":n,onClick:()=>o(!n),children:"⋯"},void 0,!1,void 0,this),n&&r("div",{class:"toolbar-menu top-bar-more-menu",role:"menu",children:[e&&r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>{cs.value=!0}),children:"Export board"},void 0,!1,void 0,this),e&&r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>void fl()),children:"Present board"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>ti(1.25)),children:"Zoom in"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>ti(0.8)),children:"Zoom out"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(()=>_r({x:0,y:0,scale:1},250)),children:"Reset zoom"},void 0,!1,void 0,this),r("button",{type:"button",role:"menuitem",class:"toolbar-menu-item",onClick:a(t),children:"Fit all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var bi={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 rc(e,t,n,o={}){let i=bi[t];return{id:e,type:t,position:o.position??{x:i.x,y:i.y},size:o.size??{width:i.w,height:i.h},zIndex:t==="status"?0:1,collapsed:!1,pinned:!1,data:n}}var xi=null,sc=null,mp=0,wi=null,tO=3000,nO=2000,oO=1000,rO=80,RI=5000,iO=1e4,ic=!1,$r=null,ka=null,wa=null,us=0,ki=null;function sO(){if(tt())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 Sa=new Map;function ac(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 vp(e){if(!sc)return e;let t=sc.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 lc(e,t,n){return vp(rc(e,t,n))}function aO(){return sd([...H.value.values()],bi.markdown.w,bi.markdown.h)}function Ca(){if(!H.value.has("status-main"))kr(lc("status-main","status",{phase:"idle",message:"",elapsed:0}))}function lO(e,t){let n=`md-${ac(e)}`;if(H.value.get(n))Xe(n,{path:e,title:t}),gt.value=n;else{let i=aO(),s=lc(n,"markdown",{path:e,title:t,content:"",rendered:""});s.position=i,kr(s),$t(n)}}function cO(e){if(H.value.get("context-main"))Xe("context-main",{cards:e});else if(e.length>0){let o=lc("context-main","context",{cards:e});kr(o)}}function uO(e){let t=e.url,n=`mcp-${ac(t)}`;if(H.value.get(n))Xe(n,e);else kr(lc(n,"mcp-app",e)),$t(n)}function dO(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(H.value.get(o)){Xe(o,e);return}let{serverName:s,toolName:a}=e;if(s&&a){for(let[v,b]of H.value.entries())if(b.type==="mcp-app"&&b.data.mode==="ext-app"&&b.data.serverName===s&&b.data.toolName===a&&!b.data.toolResult){Xe(v,{...e});return}}let{_x:l,_y:c,_width:u,_height:d}=e,p=bi["mcp-app"],f=u??p.w,m=d??p.h,h=l===void 0||c===void 0?sd([...H.value.values()],f,m):null,g=vp(rc(o,"mcp-app",{mode:"ext-app",...e},{position:{x:l??h?.x??p.x,y:c??h?.y??p.y},size:{width:f,height:m}}));kr(g),$t(o,{recordHistory:!1})}function pO(e){let t=e.startsWith("ext-app-")?e:`ext-app-${e}`;if(H.value.has(t))return t;let n=`ext-app-${e}`;if(n!==t&&H.value.has(n))return n;for(let[o,i]of H.value.entries())if(i.type==="mcp-app"&&i.data.mode==="ext-app"&&i.data.toolCallId===e)return o;return null}function zI(e){let t=typeof e.nodeId==="string"&&e.nodeId.length>0?e.nodeId:null;if(t&&H.value.has(t))return t;if(typeof e.toolCallId!=="string"||!e.toolCallId)return null;return pO(e.toolCallId)}function $I(e,t){if(typeof e!=="string"||!e)return null;if(typeof t!=="string"||!t)return null;let n=null;for(let[o,i]of H.value.entries())if(i.type==="mcp-app"&&i.data.mode==="ext-app"&&i.data.serverName===e&&i.data.toolName===t&&!i.data.toolResult){if(n)return null;n=o}return n}function LI(e){if(H.value.get("ledger-main"))Xe("ledger-main",e);else{let o=lc("ledger-main","ledger",e);o.collapsed=!0,kr(o)}}function $g(e){if(!El(e))return;if(document.documentElement.setAttribute("data-theme",e),la(),Qt.value!==e)Qt.value=e}function fO(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 mO(e){return e==="relation"||e==="depends-on"||e==="flow"||e==="references"}function Lg(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 OI(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 hO(e){let t=Lg(e),n=OI(e);return t&&n?{...t,...n}:null}function gO(e){if(typeof e.id!=="string"||!e.id)return null;if(!fO(e.type))return null;let t=Lg(e.position),n=OI(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,linksRevision:typeof e.linksRevision==="number"?e.linksRevision:0,...yp(e.createdBy)?{createdBy:e.createdBy}:{},...yp(e.lastEditedBy)?{lastEditedBy:e.lastEditedBy}:{},data:o}}function yp(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.actor==="string"&&typeof t.source==="string"}function yO(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(!mO(e.type))return null;return{id:e.id,from:e.from,to:e.to,...typeof e.toBoardId==="string"?{toBoardId:e.toBoardId}:{},type:e.type,...typeof e.kind==="string"?{kind:e.kind}:{},...typeof e.reason==="string"?{reason:e.reason}:{},...typeof e.label==="string"?{label:e.label}:{},...e.style==="solid"||e.style==="dashed"||e.style==="dotted"?{style:e.style}:{},...e.animated===!0?{animated:!0}:{},...typeof e.revision==="number"?{revision:e.revision}:{},...yp(e.changedBy)?{changedBy:e.changedBy}:{},...typeof e.changedAt==="string"?{changedAt:e.changedAt}:{},...yp(e.createdBy)?{createdBy:e.createdBy}:{},...typeof e.createdAt==="string"?{createdAt:e.createdAt}:{}}}function vO(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)=>Lg(o)).filter((o)=>o!==null),n=hO(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 PI="pmx-canvas-version-reload";function bO(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 i=`${String(e)}::${String(t)}`;try{if(window.sessionStorage.getItem(PI)===i)return;window.sessionStorage.setItem(PI,i)}catch{return}window.location.reload()}function xO(e){let t=fi.value[0]?.id;if(aC(e),_o.value&&fi.value[0]?.id!==t)yi()}function wO(e){PC(e)}var ds=0,Mg=0,_a=null;function kO(e){Uf(e)}function SO(e){let t=_a;if(_a=null,e){if(t?.boardId===se.value)gp(t);return}let n=se.value,o=++ds;if(sc=null,cn.value=!1,su(),Hk(),pu(),hm({nodes:[],edges:[]}),t?.boardId===se.value)gp(t);if(se.value===null)Ud();if(Fn.value?.kind==="receipt")Fn.value=null;Qh({}),Lo.value=null,Og();let i=Mg,s=$o;mk(n).then((a)=>{if(o===ds&&i===Mg)gp({layout:a,boardId:n})}),pe("fetchPinnedContext","/api/canvas/pinned-context",{}).then((a)=>{if(o===ds&&s===$o)DI({nodeIds:a.nodeIds})})}Tk(SO);function _O(e){if(bo.value++,ds++,_a=null,cn.value=!1,typeof e.catalogEpoch==="string")Ck(e.catalogEpoch);if(!tt()&&typeof e.workbenchToken==="string")window.__PMX_WORKBENCH_TOKEN=e.workbenchToken;if(xr.value=e.sessionId||"",Pf(e.workspaceSettings),ao.value="connected",sl().then(Jr),Zi.value+=1,bO(e.version,e.bundleStamp),jl(),zr(),Qa(),!fu&&!tt())Qw();if(pe("fetchHumanPresence","/api/canvas/human-presence",null).then(Uf),Og().then(()=>{if(_o.value)yi()}),typeof e.theme==="string"&&!Sg())$g(e.theme);if(e.ledgerSummary)LI(e.ledgerSummary)}function CO(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(lO(t,n),e.ledgerSummary)LI(e.ledgerSummary)}function TO(e){Ca(),Xe("status-main",{message:typeof e.message==="string"?e.message:String(e.message??""),level:e.level??"ok",source:e.source})}function IO(e){Ca(),Xe("status-main",{phase:e.phase,detail:e.detail})}function EO(e){let t=e.cards??[];cO(t)}function AO(e){if(typeof e.url==="string"&&e.url)uO({url:e.url,sourceServer:e.sourceServer,sourceTool:e.sourceTool,inferredType:e.inferredType,trustedDomain:e.trustedDomain,hostMode:e.hostMode??"hosted"})}function RO(e){let t=e.sessions??[];for(let n of t){let o=n.url;if(!o)continue;let i=`mcp-${ac(o)}`;if(H.value.has(i))Xe(i,{sessionState:n.state,lastSeenAt:n.lastSeenAt})}}function PO(e){if(typeof e.url==="string"&&e.url){let t=`mcp-${ac(e.url)}`;if(H.value.has(t))Xe(t,{hostMode:"fallback",fallbackReason:e.reasonCode})}}function NO(e){let n=H.value.get("context-main");if(!n)return;let o=(n.data.auxTabs??[]).concat(e);Xe("context-main",{auxTabs:o})}function MO(e){if(H.value.has("context-main"))if(e.mode==="all")Xe("context-main",{auxTabs:[]});else{let o=H.value.get("context-main");if(!o)return;let i=(o.data.auxTabs??[]).filter((s)=>s.id!==e.id);Xe("context-main",{auxTabs:i})}}function zO(e){Ca(),Xe("status-main",{phase:"idle",lastCompletion:{tokenCount:e.tokenCount,artifactCount:e.artifactCount}})}function $O(e){Ca(),Xe("status-main",{phase:"tooling",detail:`${e.name}`,activeTool:e.name})}function LO(e){Ca(),Xe("status-main",{activeTool:null})}function OO(e){if(e.state==="active"&&e.path){let n=`md-${ac(e.path)}`;if(H.value.has(n))Xe(n,{reviewActive:!0})}}function DO(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;dO({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 BO(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=zI(e)??$I(e.serverName,e.toolName);if(!t)return;if(H.value.has(t))Xe(t,{html:e.html})}function FO(e){if(typeof e.toolCallId!=="string"||!e.toolCallId)return;let t=zI(e)??$I(e.serverName,e.toolName);if(!t)return;if(H.value.has(t)){if(e.success===!1){ei(t);return}Xe(t,{toolResult:jh({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 HO(e){Ca(),Xe("status-main",{subagent:{state:e.state,name:e.agentDisplayName??e.agentName}})}function UO(e){let t=e.nodeId;if(!t)return;let n=e.text||"",{position:o,parentNodeId:i,contextNodeIds:s}=e;if(e.threadNodeId&&H.value.has(e.threadNodeId)){let a=e.threadNodeId,l=H.value.get(a);if(!l)return;let c=Array.isArray(l.data.turns)?[...l.data.turns]:[],u=c[c.length-1];if(!u||u.role!=="user"||u.text!==n)c.push({role:"user",text:n,status:"pending"});Xe(a,{turns:c,threadStatus:"pending"});return}if(!H.value.has(t)){let a=o??bi.prompt;kr(vp(rc(t,"prompt",{text:n,turns:n?[{role:"user",text:n,status:"pending"}]:[],threadStatus:n?"pending":"draft",status:n?"pending":"draft",parentNodeId:i,contextNodeIds:s},{position:{x:a.x,y:a.y}}))),$t(t)}if(i&&H.value.has(i))zs({id:`edge-${i}-${t}`,from:i,to:t,type:"flow",style:"dashed"})}function jO(e){let{nodeId:t,status:n}=e;if(t&&H.value.has(t))Xe(t,{status:n})}function ZO(e){let{responseNodeId:t,promptNodeId:n}=e;if(!t)return;let o=n?H.value.get(n):void 0;if(o&&Array.isArray(o.data.turns)){Sa.set(t,n);let s=[...o.data.turns];s.push({role:"assistant",text:"",status:"streaming"}),Xe(n,{turns:s,threadStatus:"streaming",_activeResponseId:t}),$t(n);return}let i=o?{x:o.position.x,y:o.position.y+o.size.height+24}:{x:bi.response.x,y:bi.response.y};if(!H.value.has(t))kr(vp(rc(t,"response",{content:"",status:"streaming",promptNodeId:n},{position:i})));if(n)zs({id:`edge-${n}-${t}`,from:n,to:t,type:"flow",animated:!0});$t(t)}function WO(e){let t=e.responseNodeId;if(!t)return;let n=Sa.get(t);if(n){let o=H.value.get(n);if(o&&Array.isArray(o.data.turns)){let i=[...o.data.turns],s=i[i.length-1];if(s&&s.role==="assistant")s.text=e.content,s.status="streaming";Xe(n,{turns:i,threadStatus:"streaming"})}return}if(!H.value.has(t))return;Xe(t,{content:e.content,status:"streaming"})}function qO(e){let t=e.responseNodeId;if(!t)return;let n=Sa.get(t);if(n){let s=H.value.get(n);if(s&&Array.isArray(s.data.turns)){let a=[...s.data.turns],l=a[a.length-1];if(l&&l.role==="assistant")l.text=e.content,l.status="complete";Xe(n,{turns:a,threadStatus:"answered",_activeResponseId:void 0})}Sa.delete(t);return}if(!H.value.has(t))return;Xe(t,{content:e.content,status:"complete"});let i=H.value.get(t)?.data.promptNodeId;if(i){let s=`edge-${i}-${t}`,a=et.value.get(s);if(a)Vk(s),zs({...a,animated:!1})}}function gp(e){bo.value++;let t=e.layout;if(!t?.nodes)return;if(typeof e.boardGeneration==="number"){if(e.catalogEpoch!==Sn||Mo!==null&&e.boardGeneration<Mo)return;if(Mo===null||e.boardGeneration>Mo){_a=e;return}}if(e.boardId!==void 0&&e.boardId!==se.value){_a=e;return}Mg+=1;let n=!cn.value;cn.value=!0;let o=t.nodes.map(gO).filter((l)=>l!==null),i=Array.isArray(t.edges)?t.edges.map(yO).filter((l)=>l!==null):Array.from(et.value.values()),s=Array.isArray(t.annotations)?t.annotations.map(vO).filter((l)=>l!==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)co();hm({...a?{viewport:a}:{},nodes:o,edges:i,...s?{annotations:s}:{}},{applyViewport:n}),nl({event:"canvas-layout-update",data:e}),zr(1000)}function GO(e){if(e<=1)return 500;if(e===2)return 1000;return Math.min(2500,1500+(e-3)*500)}function KO(e){if(vm())return;let t=e.nodeId;if(t&&H.value.has(t)){if(e.noPan===!0){Sr(t);return}$t(t)}}function VO(e){if(vm()||e.clientId===Kr)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,i=typeof t.scale==="number"?t.scale:1;co(),fm({x:n,y:o,scale:i})}function XO(e){if(Oo.value)return;if(!Ln.value&&e.present!==!0)return;let t=Xc.safeParse(e.stop);if(t.success)nS(t.data)}function JO(){if(Oo.value)return;Ln.value=!1,Jo.value=""}function YO(e){if(Oo.value)return;let t=Xc.safeParse(e.stop);if(!t.success)return;try{bm(t.data,Ln.value?void 0:(n)=>{bu(n,{recordHistory:!1})})}catch{let n=Wa.safeParse(e.viewport);if(!n.success)return;co(),fm(n.data)}}function QO(e){if(H.value.get("context-main"))Xe("context-main",{currentTokens:e.currentTokens,tokenLimit:e.tokenLimit,messagesLength:e.messagesLength,utilization:e.utilization,nearLimit:e.nearLimit})}function eD(e){Ds.value=e.enabled===!0}function tD(e){if(typeof e.theme==="string"&&!Sg())$g(e.theme)}function DI(e){bo.value++;let t=Array.isArray(e.nodeIds)?e.nodeIds.filter((n)=>typeof n==="string"):[];if(ji===0)um(t);nl({event:"context-pins-changed",data:e}),jl(),zr()}function nD(){jl(),zr()}var hp=null,zg=0;async function Og(){let e=++zg,t=ds,n=await yk();if(e===zg&&t===ds)Lo.value=n}function NI(){if(hp)clearTimeout(hp);zg+=1,hp=setTimeout(()=>{if(hp=null,Og(),_o.value)yi()},150)}function oD(e){let t=e.intent;if(!t||typeof t.id!=="string"||typeof t.kind!=="string"||typeof t.expiresAt!=="number")return;jw(t)}function rD(e){let t=typeof e.id==="string"?e.id:"";if(!t)return;if(e.settled===!0)Ww(t,typeof e.nodeId==="string"?e.nodeId:void 0);else Ff(t)}var BI={connected:_O,"workbench-open":CO,"canvas-status":TO,"execution-phase":IO,"context-cards":EO,"mcp-app-candidate":AO,"mcp-app-host-snapshot":RO,"mcp-app-host-fallback":PO,"aux-open":NO,"aux-close":MO,"assistant-complete":zO,"tool-start":$O,"tool-complete":LO,"review-state":OO,"subagent-status":HO,"ext-app-open":DO,"ext-app-update":BO,"ext-app-result":FO,"context-pins-changed":DI,"context-status-changed":nD,"knowledge-changed":()=>void Kt(),"lifecycle-changed":()=>void Kt(),"boards-changed":(e)=>{Qr(e),zr()},"canvas-layout-update":gp,"canvas-focus-node":KO,"canvas-viewport-update":VO,"canvas-tour-step":XO,"canvas-tour-exit":JO,"canvas-camera-move":YO,"context-usage":QO,"trace-state":eD,"theme-changed":tD,"settings-changed":(e)=>Pf(e.workspaceSettings),"canvas-prompt-created":UO,"canvas-prompt-status":jO,"canvas-response-start":ZO,"canvas-response-delta":WO,"canvas-response-complete":qO,"ax-state-changed":NI,"ax-event-created":NI,"ax-intent":oD,"ax-intent-clear":rD,"agent-presence":xO,"human-presence":kO,"agent-session-ended":wO};function FI(e,t){let n=BI[e];if(!n)return;let o=n;try{o(t)}catch(i){console.warn(`[sse-bridge] Handler for "${e}" failed:`,i)}}function MI(){ic=!0,us+=1;let e=us;ka?.abort();let t=new AbortController;ka=t;let n=!tt();ao.value="connecting";let o=null,i=!1,s=async()=>{if(e!==us)return;let a=new AbortController,l;try{let c=new URLSearchParams;if(wa!==null){if(c.set("since",String(wa)),n)c.set("waitMs",String(oO))}let u=xr.value;if(u)c.set("session",u);let d=c.toString(),p=$o,f=await Promise.race([(async()=>{let b=await Gt(`/api/workbench/poll${d?`?${d}`:""}`,{signal:AbortSignal.any([t.signal,a.signal])});if(!b.ok)throw Error(`poll failed with HTTP ${b.status}`);return await b.json()})(),new Promise((b,x)=>{l=setTimeout(()=>{a.abort(),x(Error("poll request timed out"))},iO)})]);if(e!==us)return;if(!f.ok)throw Error("poll returned ok: false");let m=o;if(o=f.sessionId??null,m!==null&&f.sessionId&&m!==f.sessionId&&!f.snapshot){wa=null,$r=setTimeout(()=>void s(),0);return}if(f.snapshot&&i)sc=ym(),cn.value=!1,pu(),su(),Sa.clear();let h=p===$o&&ji===0,g=!1,v=new Set;if(!f.snapshot&&cn.value){let b;for(let x of f.events){let C=x.payload,y=C.catalogEpoch===Sn&&C.boardGeneration===Mo&&(x.event==="boards-changed"?C.activeBoardId:C.boardId)===se.value;if(x.event==="canvas-layout-update"&&y){if(b)v.add(b);b=x}else if(!(x.event==="boards-changed"&&y)&&!["agent-presence","human-presence","ax-intent","ax-intent-clear"].includes(x.event))b=void 0}}for(let b of f.events){if(v.has(b))continue;if(b.event==="context-pins-changed"&&!h){g=!0;continue}FI(b.event,b.payload)}if(g)dm(),jl(),zr();i=!0,wa=f.seq,Wi.value=0,qi.value=0,ao.value="connected",$r=setTimeout(()=>void s(),n?rO:nO)}catch(c){if(e!==us)return;console.warn("[sse-bridge] poll transport error:",c),ao.value="disconnected",Wi.value+=1,qi.value=RI,$r=setTimeout(()=>void s(),RI)}finally{clearTimeout(l)}};return s(),()=>{if(Qa(),us+=1,ic=!1,wa=null,t.abort(),ka===t)ka=null;if($r)clearTimeout($r),$r=null}}function Dg(){if(ds++,_a=null,hT($g),sc=ym(),cn.value=!1,pu(),su(),Sa.clear(),wi)clearTimeout(wi),wi=null;let e=sO();if(e==="poll"||ic)return MI();let t=xr.value,n=t?`/api/workbench/events?session=${t}`:"/api/workbench/events";ao.value="connecting";let o=new EventSource(n);xi=o;let i=!1;if(ki)clearTimeout(ki);if(ki=null,e!=="sse")ki=setTimeout(()=>{if(ki=null,i||xi!==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(),xi=null,MI()},tO);for(let[s]of Object.entries(BI))o.addEventListener(s,(a)=>{if(xi!==o)return;i=!0;try{FI(s,JSON.parse(a.data))}catch(l){console.warn(`[sse-bridge] Failed to parse "${s}" event:`,l)}});return o.onopen=()=>{if(xi!==o)return;mp=0,Wi.value=0,qi.value=0,ao.value="connected"},o.onerror=()=>{if(xi!==o)return;ao.value="disconnected",o.close(),xi=null,mp+=1;let s=GO(mp);Wi.value=mp,qi.value=s,wi=setTimeout(()=>{wi=null,Dg()},s)},()=>{if(Qa(),wi)clearTimeout(wi),wi=null;if(ki)clearTimeout(ki),ki=null;if(ic){if(us+=1,ic=!1,wa=null,ka?.abort(),ka=null,$r)clearTimeout($r),$r=null}o.close(),xi=null}}function ps(e,t){console.error(`[app] ${e} failed`,t)}var iD=Ve(()=>H.value.size===0),HI=Ve(()=>{let e=Ct.value;return!!e&&!ut.value&&se.value===e.boardId&&wt===e.incarnation&&H.value.has(e.nodeId)}),Bg=Ve(()=>Oe.value&&HI.value);function UI(){let[e,t]=E(()=>window.innerWidth>=700),[n,o]=E(!1),[i,s]=E(!1),[a,l]=E(!1),[c,u]=E({}),[d,p]=E(!1),[f,m]=E(null),h=D(null),g=D(null),[v,b]=E(Jt),{menu:x,openNodeMenu:C,openCanvasMenu:y,openEdgeMenu:k,closeMenu:_}=bT(),I=cn.value,w=io.value&&(se.value===null||ut.value),P=tr.value,L=xt.value,N=_o.value||Co.value.length>0||os.value.length>0||!!To.value,Y=Bg.value;Me(()=>{if(!L){if(Fn.value=null,eo.value=!1,document.activeElement?.closest(".command-bar, .session-panel, .agent-popover"))h.current?.focus({preventScroll:!0})}},[L]);let B=oe(()=>t((A)=>!A),[]),J=oe(()=>o((A)=>!A),[]),X=oe(()=>o(!1),[]),V=oe((A)=>m(A),[]),ee=oe((A)=>{Rw(A),g.current=A},[]),he=oe((A,te)=>{_r({x:A,y:te,scale:Ee.value.scale},200)},[]);return q(()=>Dg(),[]),q(()=>{let A=(te)=>{let M=te.detail;u(M??{}),l(!0)};return window.addEventListener("pmx-open-board-link",A),()=>window.removeEventListener("pmx-open-board-link",A)},[]),q(()=>{let A=null,te=()=>{if(A!==null)window.clearTimeout(A);A=window.setTimeout(()=>{A=null,Jr()},400)};return window.addEventListener("resize",te),()=>{if(A!==null)window.clearTimeout(A);window.removeEventListener("resize",te)}},[]),Me(()=>{let A=(O)=>{let Pe=(O.metaKey||O.ctrlKey)&&!O.altKey;if(d&&(O.key==="Escape"||O.key==="?"||O.key==="/"&&O.shiftKey)){O.preventDefault(),p(!1);return}if(ut.value||se.value===null)return;if(O.defaultPrevented)return;if(Pe&&O.key==="k"){O.preventDefault(),s((ve)=>!ve);return}if(O.key==="Escape"&&f){O.preventDefault(),m(null);return}if(O.key==="Escape"&&Bg.value){if(O.target?.closest('[role="menu"], [role="alertdialog"]'))return;O.preventDefault(),Ct.value=null;return}if(O.key==="Escape"&&Bt.value&&!zo.value){O.preventDefault(),Cr();return}if(O.key==="Escape"&&i){O.preventDefault(),s(!1);return}let Fe=O.target,De=Fe?.tagName;if(De==="INPUT"||De==="TEXTAREA"||Fe?.isContentEditable)return;if(Fe?.closest('[role="menu"]'))return;let Ae=Fe?.closest('[role="dialog"]');if((O.key==="Tab"||O.key.startsWith("Arrow"))&&Fe?.closest(".tool-rail, .top-bar"))return;if(O.key===" "&&!O.repeat&&!Pe&&!Ae){O.preventDefault(),dl.value=!0;return}if(O.key==="?"||O.key==="/"&&O.shiftKey){O.preventDefault(),p((ve)=>!ve);return}if(Pe&&(O.key==="z"||O.key==="Z"))O.preventDefault(),ag(O.shiftKey);else if(Pe&&(O.key==="y"||O.key==="Y"))O.preventDefault(),ag(!0);else if(Pe&&O.key==="0")O.preventDefault(),_r({x:0,y:0,scale:1},250);else if(Pe&&(O.key==="="||O.key==="+"))O.preventDefault(),ti(1.25);else if(Pe&&O.key==="-")O.preventDefault(),ti(0.8);else if(Ae)return;else if(O.key==="Escape"){if(!ir(O))return;if(O.preventDefault(),Io.value?.boardId===se.value)Io.value=null;Ro.value="All",$n(),gt.value=null,_()}else if(O.key==="Tab")O.preventDefault(),Qk(O.shiftKey?-1:1);else if(O.key==="Delete"||O.key==="Backspace"){if(br.value!==null){let z=br.value;O.preventDefault(),br.value=null,wu(z).catch((re)=>ps("delete-edge",re));return}let ve=st.value.size>0?[...st.value]:gt.value?[gt.value]:[];if(ve.length===0)return;O.preventDefault();for(let z of ve)Xr(z).catch((re)=>ps("delete",re));$n(),gt.value=null}else if(gt.value&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(O.key)){O.preventDefault();let ve=O.key.replace("Arrow","").toLowerCase();eS(ve)}else if(!Pe&&!O.altKey){let ve=O.key.toLowerCase();if(ve==="v"&&!O.shiftKey)Wn.value="select";else if(ve==="c"&&!O.shiftKey&&!Pe)O.preventDefault(),Wn.value=Wn.value==="connect"?"select":"connect";else if(ve==="m"&&!O.shiftKey)O.preventDefault(),Eo({type:"markdown",title:"New note",width:520,height:360}).catch((z)=>ps("create markdown",z));else if(ve==="a"&&!O.shiftKey)O.preventDefault(),m((z)=>z==="pen"?null:"pen");else if(ve==="g"&&!O.shiftKey){O.preventDefault();let z=Array.from(st.value);if(z.length>=2)Ns({title:"Group",childIds:z}).catch((re)=>ps("group selection",re)),$n();else Eo({type:"group",title:"Group"}).catch((re)=>ps("create group",re))}else if(ve==="g"&&O.shiftKey){O.preventDefault();for(let z of Wk())ei(z),Ms(z).catch((re)=>ps("ungroup",re));$n()}else if(ve==="i"&&!O.shiftKey)O.preventDefault(),as("image");else if(ve==="w"&&!O.shiftKey)O.preventDefault(),as("webpage");else if(ve==="h"&&!O.shiftKey)O.preventDefault(),Eo({type:"html",title:"HTML surface"}).catch((z)=>ps("create html",z));else if(ve==="f"&&O.shiftKey)O.preventDefault(),as("file");else if(ve==="f"&&!O.shiftKey){O.preventDefault();let z=Jt();Hs(z.width,z.height)}}},te=(O)=>{if(O.key===" ")dl.value=!1},M=()=>{dl.value=!1};return document.addEventListener("keydown",A),document.addEventListener("keyup",te),window.addEventListener("blur",M),()=>{document.removeEventListener("keydown",A),document.removeEventListener("keyup",te),window.removeEventListener("blur",M)}},[f,_,i,d]),q(()=>{let A=window.setTimeout(()=>void Jr(),250);return()=>window.clearTimeout(A)},[P]),Me(()=>{let A=g.current;if(!A)return;let te=new ResizeObserver(()=>{b(Jt()),Jr();let M=Ct.value;if(M&&Bg.value)$t(M.nodeId,{recordHistory:!1})});return te.observe(A),()=>te.disconnect()},[]),q(()=>{if(!I)return;let A=window.__pmxCanvasBootstrapReady;if(typeof A==="function")A()},[I]),r("div",{class:`app-shell${Ln.value?" is-presenting":""}`,"data-session-active":P?"true":"false",children:[r(iS,{},void 0,!1,void 0,this),r(tT,{},void 0,!1,void 0,this),r(ST,{minimapVisible:e,onToggleMinimap:B,snapshotOpen:n,onToggleSnapshot:J,snapshotBtnRef:h,onOpenPalette:()=>s(!0),onOpenShortcuts:()=>p((A)=>!A),annotationTool:f,onSetAnnotationTool:V},void 0,!1,void 0,this),r("div",{class:"app-main",children:[r(AI,{},void 0,!1,void 0,this),r(pT,{},void 0,!1,void 0,this),r("div",{class:`workspace${Y?" is-reviewing":""}`,children:[r("div",{class:"canvas-region",ref:ee,children:[!ut.value&&r(sT,{onNodeContextMenu:C,onCanvasContextMenu:y,onEdgeContextMenu:k,annotationMode:f!==null,annotationTool:f},void 0,!1,void 0,this),r(kS,{},void 0,!1,void 0,this),r($C,{},void 0,!1,void 0,this),!w&&r(LC,{},void 0,!1,void 0,this),!w&&r(QC,{},void 0,!1,void 0,this),r(wS,{},void 0,!1,void 0,this),r(QT,{},void 0,!1,void 0,this),r(eI,{},void 0,!1,void 0,this),w?r(XT,{},void 0,!1,void 0,this):I&&iD.value&&qt.value.size===0&&r(_T,{onOpenPalette:()=>s(!0)},void 0,!1,void 0,this),!w&&st.value.size>0&&r(uI,{},void 0,!1,void 0,this),!w&&!L&&r(uT,{},void 0,!1,void 0,this),!w&&_o.value&&!tt()&&r(aT,{},void 0,!1,void 0,this),!w&&r(xI,{onOpenSnapshots:()=>o(!0)},void 0,!1,void 0,this),r(_S,{},void 0,!1,void 0,this),!ut.value&&r(JT,{},void 0,!1,void 0,this),!w&&Bt.value&&r(iI,{},void 0,!1,void 0,this),r(_I,{open:n&&!ut.value,onClose:X,anchorRef:h},void 0,!1,void 0,this),e&&!w&&r(cI,{viewport:Ee,nodes:H,edges:et,onNavigate:he,containerWidth:v.width,containerHeight:v.height},void 0,!1,void 0,this)]},void 0,!0,void 0,this),HI.value&&r(vT,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),P&&r(yI,{},void 0,!1,void 0,this),!P&&N&&r(gI,{},void 0,!1,void 0,this),!ut.value&&x&&r(xT,{menu:x,onClose:_},void 0,!1,void 0,this),!ut.value&&i&&r(gT,{onClose:()=>s(!1),onToggleMinimap:B},void 0,!1,void 0,this),!ut.value&&a&&r(yT,{...c,onClose:()=>l(!1)},void 0,!1,void 0,this),d&&r(wI,{onClose:()=>p(!1)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}PS();var jI=document.getElementById("app");if(jI)Ra(r(UI,{},void 0,!1,void 0,this),jI);