claude-code-session-manager 0.38.3 → 0.38.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{TiptapBody-R9igz9Iz.js → TiptapBody-Dz0cPmSN.js} +1 -1
- package/dist/assets/{index-BJRUaZ96.js → index-B45c4uKJ.js} +5 -5
- package/dist/assets/index-BZeC568j.css +32 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/develop/SKILL.md +96 -28
- package/dist/assets/index-DyOGjslF.css +0 -32
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-Dz0cPmSN.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var wN=Object.defineProperty;var _N=(e,n,r)=>n in e?wN(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var Fn=(e,n,r)=>_N(e,typeof n!="symbol"?n+"":n,r);import{_ as Jm}from"./monaco-editor-BW5C4Iv1.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&i(d)}).observe(document,{childList:!0,subtree:!0});function r(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function i(o){if(o.ep)return;o.ep=!0;const l=r(o);fetch(o.href,l)}})();function Gy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var kv={exports:{}},Bp={},Sv={exports:{}},pn={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -40,7 +40,7 @@ var wN=Object.defineProperty;var _N=(e,n,r)=>n in e?wN(e,n,{enumerable:!0,config
|
|
|
40
40
|
Error generating stack: `+K.message+`
|
|
41
41
|
`+K.stack}return{value:c,source:p,stack:F,digest:null}}function Hd(c,p,k){return{value:c,source:null,stack:k??null,digest:p??null}}function Wd(c,p){try{console.error(p.value)}catch(k){setTimeout(function(){throw k})}}var Pg=typeof WeakMap=="function"?WeakMap:Map;function ap(c,p,k){k=Ji(-1,k),k.tag=3,k.payload={element:null};var M=p.value;return k.callback=function(){cu||(cu=!0,dh=M),Wd(c,p)},k}function lp(c,p,k){k=Ji(-1,k),k.tag=3;var M=c.type.getDerivedStateFromError;if(typeof M=="function"){var F=p.value;k.payload=function(){return M(F)},k.callback=function(){Wd(c,p)}}var K=c.stateNode;return K!==null&&typeof K.componentDidCatch=="function"&&(k.callback=function(){Wd(c,p),typeof M!="function"&&($o===null?$o=new Set([this]):$o.add(this));var de=p.stack;this.componentDidCatch(p.value,{componentStack:de!==null?de:""})}),k}function cp(c,p,k){var M=c.pingCache;if(M===null){M=c.pingCache=new Pg;var F=new Set;M.set(p,F)}else F=M.get(p),F===void 0&&(F=new Set,M.set(p,F));F.has(k)||(F.add(k),c=Gg.bind(null,c,p,k),p.then(c,c))}function Dg(c){do{var p;if((p=c.tag===13)&&(p=c.memoizedState,p=p!==null?p.dehydrated!==null:!0),p)return c;c=c.return}while(c!==null);return null}function Zr(c,p,k,M,F){return(c.mode&1)===0?(c===p?c.flags|=65536:(c.flags|=128,k.flags|=131072,k.flags&=-52805,k.tag===1&&(k.alternate===null?k.tag=17:(p=Ji(-1,1),p.tag=2,jo(k,p,1))),k.lanes|=1),c):(c.flags|=65536,c.lanes=F,c)}var Og=N.ReactCurrentOwner,ys=!1;function Or(c,p,k,M){p.child=c===null?kd(p,null,k,M):Ua(p,c.child,k,M)}function up(c,p,k,M,F){k=k.render;var K=p.ref;return Ha(p,F),M=Od(c,p,k,M,K,F),k=Ld(),c!==null&&!ys?(p.updateQueue=c.updateQueue,p.flags&=-2053,c.lanes&=~F,Zi(c,p,F)):(Kn&&k&&ur(p),p.flags|=1,Or(c,p,M,F),p.child)}function Fl(c,p,k,M,F){if(c===null){var K=k.type;return typeof K=="function"&&!yh(K)&&K.defaultProps===void 0&&k.compare===null&&k.defaultProps===void 0?(p.tag=15,p.type=K,dp(c,p,K,M,F)):(c=pu(k.type,null,M,p,p.mode,F),c.ref=p.ref,c.return=p,p.child=c)}if(K=c.child,(c.lanes&F)===0){var de=K.memoizedProps;if(k=k.compare,k=k!==null?k:Nl,k(de,M)&&c.ref===p.ref)return Zi(c,p,F)}return p.flags|=1,c=Mo(K,M),c.ref=p.ref,c.return=p,p.child=c}function dp(c,p,k,M,F){if(c!==null){var K=c.memoizedProps;if(Nl(K,M)&&c.ref===p.ref)if(ys=!1,p.pendingProps=M=K,(c.lanes&F)!==0)(c.flags&131072)!==0&&(ys=!0);else return p.lanes=c.lanes,Zi(c,p,F)}return qd(c,p,k,M,F)}function hp(c,p,k){var M=p.pendingProps,F=M.children,K=c!==null?c.memoizedState:null;if(M.mode==="hidden")if((p.mode&1)===0)p.memoizedState={baseLanes:0,cachePool:null,transitions:null},In(Ka,Ts),Ts|=k;else{if((k&1073741824)===0)return c=K!==null?K.baseLanes|k:k,p.lanes=p.childLanes=1073741824,p.memoizedState={baseLanes:c,cachePool:null,transitions:null},p.updateQueue=null,In(Ka,Ts),Ts|=c,null;p.memoizedState={baseLanes:0,cachePool:null,transitions:null},M=K!==null?K.baseLanes:k,In(Ka,Ts),Ts|=M}else K!==null?(M=K.baseLanes|k,p.memoizedState=null):M=k,In(Ka,Ts),Ts|=M;return Or(c,p,F,k),p.child}function fp(c,p){var k=p.ref;(c===null&&k!==null||c!==null&&c.ref!==k)&&(p.flags|=512,p.flags|=2097152)}function qd(c,p,k,M,F){var K=fs(k)?Qo:Jr.current;return K=Qr(p,K),Ha(p,F),k=Od(c,p,k,M,K,F),M=Ld(),c!==null&&!ys?(p.updateQueue=c.updateQueue,p.flags&=-2053,c.lanes&=~F,Zi(c,p,F)):(Kn&&M&&ur(p),p.flags|=1,Or(c,p,k,F),p.child)}function pp(c,p,k,M,F){if(fs(k)){var K=!0;Uc(p)}else K=!1;if(Ha(p,F),p.stateNode===null)ru(c,p),ip(p,k,M),Ud(p,k,M,F),M=!0;else if(c===null){var de=p.stateNode,_e=p.memoizedProps;de.props=_e;var $e=de.context,qe=k.contextType;typeof qe=="object"&&qe!==null?qe=Us(qe):(qe=fs(k)?Qo:Jr.current,qe=Qr(p,qe));var at=k.getDerivedStateFromProps,ct=typeof at=="function"||typeof de.getSnapshotBeforeUpdate=="function";ct||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(_e!==M||$e!==qe)&&op(p,de,M,qe),Mi=!1;var ot=p.memoizedState;de.state=ot,Yc(p,M,de,F),$e=p.memoizedState,_e!==M||ot!==$e||hs.current||Mi?(typeof at=="function"&&(Pi(p,k,at,M),$e=p.memoizedState),(_e=Mi||aa(p,k,_e,M,ot,$e,qe))?(ct||typeof de.UNSAFE_componentWillMount!="function"&&typeof de.componentWillMount!="function"||(typeof de.componentWillMount=="function"&&de.componentWillMount(),typeof de.UNSAFE_componentWillMount=="function"&&de.UNSAFE_componentWillMount()),typeof de.componentDidMount=="function"&&(p.flags|=4194308)):(typeof de.componentDidMount=="function"&&(p.flags|=4194308),p.memoizedProps=M,p.memoizedState=$e),de.props=M,de.state=$e,de.context=qe,M=_e):(typeof de.componentDidMount=="function"&&(p.flags|=4194308),M=!1)}else{de=p.stateNode,Nd(c,p),_e=p.memoizedProps,qe=p.type===p.elementType?_e:hr(p.type,_e),de.props=qe,ct=p.pendingProps,ot=de.context,$e=k.contextType,typeof $e=="object"&&$e!==null?$e=Us($e):($e=fs(k)?Qo:Jr.current,$e=Qr(p,$e));var jt=k.getDerivedStateFromProps;(at=typeof jt=="function"||typeof de.getSnapshotBeforeUpdate=="function")||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(_e!==ct||ot!==$e)&&op(p,de,M,$e),Mi=!1,ot=p.memoizedState,de.state=ot,Yc(p,M,de,F);var Pt=p.memoizedState;_e!==ct||ot!==Pt||hs.current||Mi?(typeof jt=="function"&&(Pi(p,k,jt,M),Pt=p.memoizedState),(qe=Mi||aa(p,k,qe,M,ot,Pt,$e)||!1)?(at||typeof de.UNSAFE_componentWillUpdate!="function"&&typeof de.componentWillUpdate!="function"||(typeof de.componentWillUpdate=="function"&&de.componentWillUpdate(M,Pt,$e),typeof de.UNSAFE_componentWillUpdate=="function"&&de.UNSAFE_componentWillUpdate(M,Pt,$e)),typeof de.componentDidUpdate=="function"&&(p.flags|=4),typeof de.getSnapshotBeforeUpdate=="function"&&(p.flags|=1024)):(typeof de.componentDidUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=1024),p.memoizedProps=M,p.memoizedState=Pt),de.props=M,de.state=Pt,de.context=$e,M=qe):(typeof de.componentDidUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=1024),M=!1)}return Vd(c,p,k,M,K,F)}function Vd(c,p,k,M,F,K){fp(c,p);var de=(p.flags&128)!==0;if(!M&&!de)return F&&Mf(p,k,!1),Zi(c,p,K);M=p.stateNode,Og.current=p;var _e=de&&typeof k.getDerivedStateFromError!="function"?null:M.render();return p.flags|=1,c!==null&&de?(p.child=Ua(p,c.child,null,K),p.child=Ua(p,null,_e,K)):Or(c,p,_e,K),p.memoizedState=M.state,F&&Mf(p,k,!0),p.child}function Gd(c){var p=c.stateNode;p.pendingContext?Af(c,p.pendingContext,p.pendingContext!==p.context):p.context&&Af(c,p.context,!1),Td(c,p.containerInfo)}function mp(c,p,k,M,F){return ea(),wd(F),p.flags|=256,Or(c,p,k,M),p.child}var Kd={dehydrated:null,treeContext:null,retryLane:0};function Xd(c){return{baseLanes:c,cachePool:null,transitions:null}}function gp(c,p,k){var M=p.pendingProps,F=Yn.current,K=!1,de=(p.flags&128)!==0,_e;if((_e=de)||(_e=c!==null&&c.memoizedState===null?!1:(F&2)!==0),_e?(K=!0,p.flags&=-129):(c===null||c.memoizedState!==null)&&(F|=1),In(Yn,F&1),c===null)return vd(p),c=p.memoizedState,c!==null&&(c=c.dehydrated,c!==null)?((p.mode&1)===0?p.lanes=1:c.data==="$!"?p.lanes=8:p.lanes=1073741824,null):(de=M.children,c=M.fallback,K?(M=p.mode,K=p.child,de={mode:"hidden",children:de},(M&1)===0&&K!==null?(K.childLanes=0,K.pendingProps=de):K=mu(de,M,0,null),c=Ja(c,M,k,null),K.return=p,c.return=p,K.sibling=c,p.child=K,p.child.memoizedState=Xd(k),p.memoizedState=Kd,c):Ul(p,de));if(F=c.memoizedState,F!==null&&(_e=F.dehydrated,_e!==null))return Lg(c,p,de,M,_e,F,k);if(K){K=M.fallback,de=p.mode,F=c.child,_e=F.sibling;var $e={mode:"hidden",children:M.children};return(de&1)===0&&p.child!==F?(M=p.child,M.childLanes=0,M.pendingProps=$e,p.deletions=null):(M=Mo(F,$e),M.subtreeFlags=F.subtreeFlags&14680064),_e!==null?K=Mo(_e,K):(K=Ja(K,de,k,null),K.flags|=2),K.return=p,M.return=p,M.sibling=K,p.child=M,M=K,K=p.child,de=c.child.memoizedState,de=de===null?Xd(k):{baseLanes:de.baseLanes|k,cachePool:null,transitions:de.transitions},K.memoizedState=de,K.childLanes=c.childLanes&~k,p.memoizedState=Kd,M}return K=c.child,c=K.sibling,M=Mo(K,{mode:"visible",children:M.children}),(p.mode&1)===0&&(M.lanes=k),M.return=p,M.sibling=null,c!==null&&(k=p.deletions,k===null?(p.deletions=[c],p.flags|=16):k.push(c)),p.child=M,p.memoizedState=null,M}function Ul(c,p){return p=mu({mode:"visible",children:p},c.mode,0,null),p.return=c,c.child=p}function nu(c,p,k,M){return M!==null&&wd(M),Ua(p,c.child,null,k),c=Ul(p,p.pendingProps.children),c.flags|=2,p.memoizedState=null,c}function Lg(c,p,k,M,F,K,de){if(k)return p.flags&256?(p.flags&=-257,M=Hd(Error(r(422))),nu(c,p,de,M)):p.memoizedState!==null?(p.child=c.child,p.flags|=128,null):(K=M.fallback,F=p.mode,M=mu({mode:"visible",children:M.children},F,0,null),K=Ja(K,F,de,null),K.flags|=2,M.return=p,K.return=p,M.sibling=K,p.child=M,(p.mode&1)!==0&&Ua(p,c.child,null,de),p.child.memoizedState=Xd(de),p.memoizedState=Kd,K);if((p.mode&1)===0)return nu(c,p,de,null);if(F.data==="$!"){if(M=F.nextSibling&&F.nextSibling.dataset,M)var _e=M.dgst;return M=_e,K=Error(r(419)),M=Hd(K,M,void 0),nu(c,p,de,M)}if(_e=(de&c.childLanes)!==0,ys||_e){if(M=fr,M!==null){switch(de&-de){case 4:F=2;break;case 16:F=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:F=32;break;case 536870912:F=268435456;break;default:F=0}F=(F&(M.suspendedLanes|de))!==0?0:F,F!==0&&F!==K.retryLane&&(K.retryLane=F,Yi(c,F),fi(M,c,F,-1))}return xh(),M=Hd(Error(r(421))),nu(c,p,de,M)}return F.data==="$?"?(p.flags|=128,p.child=c.child,p=Xg.bind(null,c),F._reactRetry=p,null):(c=K.treeContext,Ns=_o(F.nextSibling),gs=p,Kn=!0,xs=null,c!==null&&(Bs[ci++]=ps,Bs[ci++]=ms,Bs[ci++]=Fs,ps=c.id,ms=c.overflow,Fs=p),p=Ul(p,M.children),p.flags|=4096,p)}function xp(c,p,k){c.lanes|=p;var M=c.alternate;M!==null&&(M.lanes|=p),Of(c.return,p,k)}function Yd(c,p,k,M,F){var K=c.memoizedState;K===null?c.memoizedState={isBackwards:p,rendering:null,renderingStartTime:0,last:M,tail:k,tailMode:F}:(K.isBackwards=p,K.rendering=null,K.renderingStartTime=0,K.last=M,K.tail=k,K.tailMode=F)}function Jd(c,p,k){var M=p.pendingProps,F=M.revealOrder,K=M.tail;if(Or(c,p,M.children,k),M=Yn.current,(M&2)!==0)M=M&1|2,p.flags|=128;else{if(c!==null&&(c.flags&128)!==0)e:for(c=p.child;c!==null;){if(c.tag===13)c.memoizedState!==null&&xp(c,k,p);else if(c.tag===19)xp(c,k,p);else if(c.child!==null){c.child.return=c,c=c.child;continue}if(c===p)break e;for(;c.sibling===null;){if(c.return===null||c.return===p)break e;c=c.return}c.sibling.return=c.return,c=c.sibling}M&=1}if(In(Yn,M),(p.mode&1)===0)p.memoizedState=null;else switch(F){case"forwards":for(k=p.child,F=null;k!==null;)c=k.alternate,c!==null&&Jc(c)===null&&(F=k),k=k.sibling;k=F,k===null?(F=p.child,p.child=null):(F=k.sibling,k.sibling=null),Yd(p,!1,F,k,K);break;case"backwards":for(k=null,F=p.child,p.child=null;F!==null;){if(c=F.alternate,c!==null&&Jc(c)===null){p.child=F;break}c=F.sibling,F.sibling=k,k=F,F=c}Yd(p,!0,k,null,K);break;case"together":Yd(p,!1,null,null,void 0);break;default:p.memoizedState=null}return p.child}function ru(c,p){(p.mode&1)===0&&c!==null&&(c.alternate=null,p.alternate=null,p.flags|=2)}function Zi(c,p,k){if(c!==null&&(p.dependencies=c.dependencies),la|=p.lanes,(k&p.childLanes)===0)return null;if(c!==null&&p.child!==c.child)throw Error(r(153));if(p.child!==null){for(c=p.child,k=Mo(c,c.pendingProps),p.child=k,k.return=p;c.sibling!==null;)c=c.sibling,k=k.sibling=Mo(c,c.pendingProps),k.return=p;k.sibling=null}return p.child}function gv(c,p,k){switch(p.tag){case 3:Gd(p),ea();break;case 5:Lf(p);break;case 1:fs(p.type)&&Uc(p);break;case 4:Td(p,p.stateNode.containerInfo);break;case 10:var M=p.type._context,F=p.memoizedProps.value;In(ta,M._currentValue),M._currentValue=F;break;case 13:if(M=p.memoizedState,M!==null)return M.dehydrated!==null?(In(Yn,Yn.current&1),p.flags|=128,null):(k&p.child.childLanes)!==0?gp(c,p,k):(In(Yn,Yn.current&1),c=Zi(c,p,k),c!==null?c.sibling:null);In(Yn,Yn.current&1);break;case 19:if(M=(k&p.childLanes)!==0,(c.flags&128)!==0){if(M)return Jd(c,p,k);p.flags|=128}if(F=p.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),In(Yn,Yn.current),M)break;return null;case 22:case 23:return p.lanes=0,hp(c,p,k)}return Zi(c,p,k)}var Qd,Zd,yp,vp;Qd=function(c,p){for(var k=p.child;k!==null;){if(k.tag===5||k.tag===6)c.appendChild(k.stateNode);else if(k.tag!==4&&k.child!==null){k.child.return=k,k=k.child;continue}if(k===p)break;for(;k.sibling===null;){if(k.return===null||k.return===p)return;k=k.return}k.sibling.return=k.return,k=k.sibling}},Zd=function(){},yp=function(c,p,k,M){var F=c.memoizedProps;if(F!==M){c=p.stateNode,ra(Ii.current);var K=null;switch(k){case"input":F=Rt(c,F),M=Rt(c,M),K=[];break;case"select":F=Q({},F,{value:void 0}),M=Q({},M,{value:void 0}),K=[];break;case"textarea":F=kt(c,F),M=kt(c,M),K=[];break;default:typeof F.onClick!="function"&&typeof M.onClick=="function"&&(c.onclick=zc)}vi(k,M);var de;k=null;for(qe in F)if(!M.hasOwnProperty(qe)&&F.hasOwnProperty(qe)&&F[qe]!=null)if(qe==="style"){var _e=F[qe];for(de in _e)_e.hasOwnProperty(de)&&(k||(k={}),k[de]="")}else qe!=="dangerouslySetInnerHTML"&&qe!=="children"&&qe!=="suppressContentEditableWarning"&&qe!=="suppressHydrationWarning"&&qe!=="autoFocus"&&(o.hasOwnProperty(qe)?K||(K=[]):(K=K||[]).push(qe,null));for(qe in M){var $e=M[qe];if(_e=F!=null?F[qe]:void 0,M.hasOwnProperty(qe)&&$e!==_e&&($e!=null||_e!=null))if(qe==="style")if(_e){for(de in _e)!_e.hasOwnProperty(de)||$e&&$e.hasOwnProperty(de)||(k||(k={}),k[de]="");for(de in $e)$e.hasOwnProperty(de)&&_e[de]!==$e[de]&&(k||(k={}),k[de]=$e[de])}else k||(K||(K=[]),K.push(qe,k)),k=$e;else qe==="dangerouslySetInnerHTML"?($e=$e?$e.__html:void 0,_e=_e?_e.__html:void 0,$e!=null&&_e!==$e&&(K=K||[]).push(qe,$e)):qe==="children"?typeof $e!="string"&&typeof $e!="number"||(K=K||[]).push(qe,""+$e):qe!=="suppressContentEditableWarning"&&qe!=="suppressHydrationWarning"&&(o.hasOwnProperty(qe)?($e!=null&&qe==="onScroll"&&zn("scroll",c),K||_e===$e||(K=[])):(K=K||[]).push(qe,$e))}k&&(K=K||[]).push("style",k);var qe=K;(p.updateQueue=qe)&&(p.flags|=4)}},vp=function(c,p,k,M){k!==M&&(p.flags|=4)};function su(c,p){if(!Kn)switch(c.tailMode){case"hidden":p=c.tail;for(var k=null;p!==null;)p.alternate!==null&&(k=p),p=p.sibling;k===null?c.tail=null:k.sibling=null;break;case"collapsed":k=c.tail;for(var M=null;k!==null;)k.alternate!==null&&(M=k),k=k.sibling;M===null?p||c.tail===null?c.tail=null:c.tail.sibling=null:M.sibling=null}}function Lr(c){var p=c.alternate!==null&&c.alternate.child===c.child,k=0,M=0;if(p)for(var F=c.child;F!==null;)k|=F.lanes|F.childLanes,M|=F.subtreeFlags&14680064,M|=F.flags&14680064,F.return=c,F=F.sibling;else for(F=c.child;F!==null;)k|=F.lanes|F.childLanes,M|=F.subtreeFlags,M|=F.flags,F.return=c,F=F.sibling;return c.subtreeFlags|=M,c.childLanes=k,p}function zg(c,p,k){var M=p.pendingProps;switch(md(p),p.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Lr(p),null;case 1:return fs(p.type)&&Fc(),Lr(p),null;case 3:return M=p.stateNode,sa(),Bn(hs),Bn(Jr),Rd(),M.pendingContext&&(M.context=M.pendingContext,M.pendingContext=null),(c===null||c.child===null)&&(Dl(p)?p.flags|=4:c===null||c.memoizedState.isDehydrated&&(p.flags&256)===0||(p.flags|=1024,xs!==null&&(ph(xs),xs=null))),Zd(c,p),Lr(p),null;case 5:$d(p);var F=ra(qa.current);if(k=p.type,c!==null&&p.stateNode!=null)yp(c,p,k,M,F),c.ref!==p.ref&&(p.flags|=512,p.flags|=2097152);else{if(!M){if(p.stateNode===null)throw Error(r(166));return Lr(p),null}if(c=ra(Ii.current),Dl(p)){M=p.stateNode,k=p.type;var K=p.memoizedProps;switch(M[Ai]=p,M[Il]=K,c=(p.mode&1)!==0,k){case"dialog":zn("cancel",M),zn("close",M);break;case"iframe":case"object":case"embed":zn("load",M);break;case"video":case"audio":for(F=0;F<Al.length;F++)zn(Al[F],M);break;case"source":zn("error",M);break;case"img":case"image":case"link":zn("error",M),zn("load",M);break;case"details":zn("toggle",M);break;case"input":He(M,K),zn("invalid",M);break;case"select":M._wrapperState={wasMultiple:!!K.multiple},zn("invalid",M);break;case"textarea":Kt(M,K),zn("invalid",M)}vi(k,K),F=null;for(var de in K)if(K.hasOwnProperty(de)){var _e=K[de];de==="children"?typeof _e=="string"?M.textContent!==_e&&(K.suppressHydrationWarning!==!0&&Lc(M.textContent,_e,c),F=["children",_e]):typeof _e=="number"&&M.textContent!==""+_e&&(K.suppressHydrationWarning!==!0&&Lc(M.textContent,_e,c),F=["children",""+_e]):o.hasOwnProperty(de)&&_e!=null&&de==="onScroll"&&zn("scroll",M)}switch(k){case"input":Je(M),an(M,K,!0);break;case"textarea":Je(M),Rn(M);break;case"select":case"option":break;default:typeof K.onClick=="function"&&(M.onclick=zc)}M=F,p.updateQueue=M,M!==null&&(p.flags|=4)}else{de=F.nodeType===9?F:F.ownerDocument,c==="http://www.w3.org/1999/xhtml"&&(c=Br(k)),c==="http://www.w3.org/1999/xhtml"?k==="script"?(c=de.createElement("div"),c.innerHTML="<script><\/script>",c=c.removeChild(c.firstChild)):typeof M.is=="string"?c=de.createElement(k,{is:M.is}):(c=de.createElement(k),k==="select"&&(de=c,M.multiple?de.multiple=!0:M.size&&(de.size=M.size))):c=de.createElementNS(c,k),c[Ai]=p,c[Il]=M,Qd(c,p,!1,!1),p.stateNode=c;e:{switch(de=yn(k,M),k){case"dialog":zn("cancel",c),zn("close",c),F=M;break;case"iframe":case"object":case"embed":zn("load",c),F=M;break;case"video":case"audio":for(F=0;F<Al.length;F++)zn(Al[F],c);F=M;break;case"source":zn("error",c),F=M;break;case"img":case"image":case"link":zn("error",c),zn("load",c),F=M;break;case"details":zn("toggle",c),F=M;break;case"input":He(c,M),F=Rt(c,M),zn("invalid",c);break;case"option":F=M;break;case"select":c._wrapperState={wasMultiple:!!M.multiple},F=Q({},M,{value:void 0}),zn("invalid",c);break;case"textarea":Kt(c,M),F=kt(c,M),zn("invalid",c);break;default:F=M}vi(k,F),_e=F;for(K in _e)if(_e.hasOwnProperty(K)){var $e=_e[K];K==="style"?Ta(c,$e):K==="dangerouslySetInnerHTML"?($e=$e?$e.__html:void 0,$e!=null&&St(c,$e)):K==="children"?typeof $e=="string"?(k!=="textarea"||$e!=="")&&Tt(c,$e):typeof $e=="number"&&Tt(c,""+$e):K!=="suppressContentEditableWarning"&&K!=="suppressHydrationWarning"&&K!=="autoFocus"&&(o.hasOwnProperty(K)?$e!=null&&K==="onScroll"&&zn("scroll",c):$e!=null&&C(c,K,$e,de))}switch(k){case"input":Je(c),an(c,M,!1);break;case"textarea":Je(c),Rn(c);break;case"option":M.value!=null&&c.setAttribute("value",""+ne(M.value));break;case"select":c.multiple=!!M.multiple,K=M.value,K!=null?yt(c,!!M.multiple,K,!1):M.defaultValue!=null&&yt(c,!!M.multiple,M.defaultValue,!0);break;default:typeof F.onClick=="function"&&(c.onclick=zc)}switch(k){case"button":case"input":case"select":case"textarea":M=!!M.autoFocus;break e;case"img":M=!0;break e;default:M=!1}}M&&(p.flags|=4)}p.ref!==null&&(p.flags|=512,p.flags|=2097152)}return Lr(p),null;case 6:if(c&&p.stateNode!=null)vp(c,p,c.memoizedProps,M);else{if(typeof M!="string"&&p.stateNode===null)throw Error(r(166));if(k=ra(qa.current),ra(Ii.current),Dl(p)){if(M=p.stateNode,k=p.memoizedProps,M[Ai]=p,(K=M.nodeValue!==k)&&(c=gs,c!==null))switch(c.tag){case 3:Lc(M.nodeValue,k,(c.mode&1)!==0);break;case 5:c.memoizedProps.suppressHydrationWarning!==!0&&Lc(M.nodeValue,k,(c.mode&1)!==0)}K&&(p.flags|=4)}else M=(k.nodeType===9?k:k.ownerDocument).createTextNode(M),M[Ai]=p,p.stateNode=M}return Lr(p),null;case 13:if(Bn(Yn),M=p.memoizedState,c===null||c.memoizedState!==null&&c.memoizedState.dehydrated!==null){if(Kn&&Ns!==null&&(p.mode&1)!==0&&(p.flags&128)===0)Pf(),ea(),p.flags|=98560,K=!1;else if(K=Dl(p),M!==null&&M.dehydrated!==null){if(c===null){if(!K)throw Error(r(318));if(K=p.memoizedState,K=K!==null?K.dehydrated:null,!K)throw Error(r(317));K[Ai]=p}else ea(),(p.flags&128)===0&&(p.memoizedState=null),p.flags|=4;Lr(p),K=!1}else xs!==null&&(ph(xs),xs=null),K=!0;if(!K)return p.flags&65536?p:null}return(p.flags&128)!==0?(p.lanes=k,p):(M=M!==null,M!==(c!==null&&c.memoizedState!==null)&&M&&(p.child.flags|=8192,(p.mode&1)!==0&&(c===null||(Yn.current&1)!==0?br===0&&(br=3):xh())),p.updateQueue!==null&&(p.flags|=4),Lr(p),null);case 4:return sa(),Zd(c,p),c===null&&Rl(p.stateNode.containerInfo),Lr(p),null;case 10:return jd(p.type._context),Lr(p),null;case 17:return fs(p.type)&&Fc(),Lr(p),null;case 19:if(Bn(Yn),K=p.memoizedState,K===null)return Lr(p),null;if(M=(p.flags&128)!==0,de=K.rendering,de===null)if(M)su(K,!1);else{if(br!==0||c!==null&&(c.flags&128)!==0)for(c=p.child;c!==null;){if(de=Jc(c),de!==null){for(p.flags|=128,su(K,!1),M=de.updateQueue,M!==null&&(p.updateQueue=M,p.flags|=4),p.subtreeFlags=0,M=k,k=p.child;k!==null;)K=k,c=M,K.flags&=14680066,de=K.alternate,de===null?(K.childLanes=0,K.lanes=c,K.child=null,K.subtreeFlags=0,K.memoizedProps=null,K.memoizedState=null,K.updateQueue=null,K.dependencies=null,K.stateNode=null):(K.childLanes=de.childLanes,K.lanes=de.lanes,K.child=de.child,K.subtreeFlags=0,K.deletions=null,K.memoizedProps=de.memoizedProps,K.memoizedState=de.memoizedState,K.updateQueue=de.updateQueue,K.type=de.type,c=de.dependencies,K.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext}),k=k.sibling;return In(Yn,Yn.current&1|2),p.child}c=c.sibling}K.tail!==null&&kn()>Xa&&(p.flags|=128,M=!0,su(K,!1),p.lanes=4194304)}else{if(!M)if(c=Jc(de),c!==null){if(p.flags|=128,M=!0,k=c.updateQueue,k!==null&&(p.updateQueue=k,p.flags|=4),su(K,!0),K.tail===null&&K.tailMode==="hidden"&&!de.alternate&&!Kn)return Lr(p),null}else 2*kn()-K.renderingStartTime>Xa&&k!==1073741824&&(p.flags|=128,M=!0,su(K,!1),p.lanes=4194304);K.isBackwards?(de.sibling=p.child,p.child=de):(k=K.last,k!==null?k.sibling=de:p.child=de,K.last=de)}return K.tail!==null?(p=K.tail,K.rendering=p,K.tail=p.sibling,K.renderingStartTime=kn(),p.sibling=null,k=Yn.current,In(Yn,M?k&1|2:k&1),p):(Lr(p),null);case 22:case 23:return gh(),M=p.memoizedState!==null,c!==null&&c.memoizedState!==null!==M&&(p.flags|=8192),M&&(p.mode&1)!==0?(Ts&1073741824)!==0&&(Lr(p),p.subtreeFlags&6&&(p.flags|=8192)):Lr(p),null;case 24:return null;case 25:return null}throw Error(r(156,p.tag))}function Bg(c,p){switch(md(p),p.tag){case 1:return fs(p.type)&&Fc(),c=p.flags,c&65536?(p.flags=c&-65537|128,p):null;case 3:return sa(),Bn(hs),Bn(Jr),Rd(),c=p.flags,(c&65536)!==0&&(c&128)===0?(p.flags=c&-65537|128,p):null;case 5:return $d(p),null;case 13:if(Bn(Yn),c=p.memoizedState,c!==null&&c.dehydrated!==null){if(p.alternate===null)throw Error(r(340));ea()}return c=p.flags,c&65536?(p.flags=c&-65537|128,p):null;case 19:return Bn(Yn),null;case 4:return sa(),null;case 10:return jd(p.type._context),null;case 22:case 23:return gh(),null;case 24:return null;default:return null}}var eh=!1,zr=!1,Fg=typeof WeakSet=="function"?WeakSet:Set,It=null;function Ga(c,p){var k=c.ref;if(k!==null)if(typeof k=="function")try{k(null)}catch(M){Jn(c,p,M)}else k.current=null}function th(c,p,k){try{k()}catch(M){Jn(c,p,M)}}var bp=!1;function Ug(c,p){if(ad=bo,c=Zu(),ed(c)){if("selectionStart"in c)var k={start:c.selectionStart,end:c.selectionEnd};else e:{k=(k=c.ownerDocument)&&k.defaultView||window;var M=k.getSelection&&k.getSelection();if(M&&M.rangeCount!==0){k=M.anchorNode;var F=M.anchorOffset,K=M.focusNode;M=M.focusOffset;try{k.nodeType,K.nodeType}catch{k=null;break e}var de=0,_e=-1,$e=-1,qe=0,at=0,ct=c,ot=null;t:for(;;){for(var jt;ct!==k||F!==0&&ct.nodeType!==3||(_e=de+F),ct!==K||M!==0&&ct.nodeType!==3||($e=de+M),ct.nodeType===3&&(de+=ct.nodeValue.length),(jt=ct.firstChild)!==null;)ot=ct,ct=jt;for(;;){if(ct===c)break t;if(ot===k&&++qe===F&&(_e=de),ot===K&&++at===M&&($e=de),(jt=ct.nextSibling)!==null)break;ct=ot,ot=ct.parentNode}ct=jt}k=_e===-1||$e===-1?null:{start:_e,end:$e}}else k=null}k=k||{start:0,end:0}}else k=null;for(ld={focusedElem:c,selectionRange:k},bo=!1,It=p;It!==null;)if(p=It,c=p.child,(p.subtreeFlags&1028)!==0&&c!==null)c.return=p,It=c;else for(;It!==null;){p=It;try{var Pt=p.alternate;if((p.flags&1024)!==0)switch(p.tag){case 0:case 11:case 15:break;case 1:if(Pt!==null){var Dt=Pt.memoizedProps,Pn=Pt.memoizedState,Ue=p.stateNode,Ie=Ue.getSnapshotBeforeUpdate(p.elementType===p.type?Dt:hr(p.type,Dt),Pn);Ue.__reactInternalSnapshotBeforeUpdate=Ie}break;case 3:var Ve=p.stateNode.containerInfo;Ve.nodeType===1?Ve.textContent="":Ve.nodeType===9&&Ve.documentElement&&Ve.removeChild(Ve.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(r(163))}}catch(ht){Jn(p,p.return,ht)}if(c=p.sibling,c!==null){c.return=p.return,It=c;break}It=p.return}return Pt=bp,bp=!1,Pt}function Hl(c,p,k){var M=p.updateQueue;if(M=M!==null?M.lastEffect:null,M!==null){var F=M=M.next;do{if((F.tag&c)===c){var K=F.destroy;F.destroy=void 0,K!==void 0&&th(p,k,K)}F=F.next}while(F!==M)}}function nh(c,p){if(p=p.updateQueue,p=p!==null?p.lastEffect:null,p!==null){var k=p=p.next;do{if((k.tag&c)===c){var M=k.create;k.destroy=M()}k=k.next}while(k!==p)}}function rh(c){var p=c.ref;if(p!==null){var k=c.stateNode;switch(c.tag){case 5:c=k;break;default:c=k}typeof p=="function"?p(c):p.current=c}}function wp(c){var p=c.alternate;p!==null&&(c.alternate=null,wp(p)),c.child=null,c.deletions=null,c.sibling=null,c.tag===5&&(p=c.stateNode,p!==null&&(delete p[Ai],delete p[Il],delete p[hd],delete p[Tf],delete p[$f])),c.stateNode=null,c.return=null,c.dependencies=null,c.memoizedProps=null,c.memoizedState=null,c.pendingProps=null,c.stateNode=null,c.updateQueue=null}function _p(c){return c.tag===5||c.tag===3||c.tag===4}function kp(c){e:for(;;){for(;c.sibling===null;){if(c.return===null||_p(c.return))return null;c=c.return}for(c.sibling.return=c.return,c=c.sibling;c.tag!==5&&c.tag!==6&&c.tag!==18;){if(c.flags&2||c.child===null||c.tag===4)continue e;c.child.return=c,c=c.child}if(!(c.flags&2))return c.stateNode}}function sh(c,p,k){var M=c.tag;if(M===5||M===6)c=c.stateNode,p?k.nodeType===8?k.parentNode.insertBefore(c,p):k.insertBefore(c,p):(k.nodeType===8?(p=k.parentNode,p.insertBefore(c,k)):(p=k,p.appendChild(c)),k=k._reactRootContainer,k!=null||p.onclick!==null||(p.onclick=zc));else if(M!==4&&(c=c.child,c!==null))for(sh(c,p,k),c=c.sibling;c!==null;)sh(c,p,k),c=c.sibling}function ih(c,p,k){var M=c.tag;if(M===5||M===6)c=c.stateNode,p?k.insertBefore(c,p):k.appendChild(c);else if(M!==4&&(c=c.child,c!==null))for(ih(c,p,k),c=c.sibling;c!==null;)ih(c,p,k),c=c.sibling}var Cr=null,di=!1;function No(c,p,k){for(k=k.child;k!==null;)Hg(c,p,k),k=k.sibling}function Hg(c,p,k){if(gr&&typeof gr.onCommitFiberUnmount=="function")try{gr.onCommitFiberUnmount(cs,k)}catch{}switch(k.tag){case 5:zr||Ga(k,p);case 6:var M=Cr,F=di;Cr=null,No(c,p,k),Cr=M,di=F,Cr!==null&&(di?(c=Cr,k=k.stateNode,c.nodeType===8?c.parentNode.removeChild(k):c.removeChild(k)):Cr.removeChild(k.stateNode));break;case 18:Cr!==null&&(di?(c=Cr,k=k.stateNode,c.nodeType===8?dd(c.parentNode,k):c.nodeType===1&&dd(c,k),Vi(c)):dd(Cr,k.stateNode));break;case 4:M=Cr,F=di,Cr=k.stateNode.containerInfo,di=!0,No(c,p,k),Cr=M,di=F;break;case 0:case 11:case 14:case 15:if(!zr&&(M=k.updateQueue,M!==null&&(M=M.lastEffect,M!==null))){F=M=M.next;do{var K=F,de=K.destroy;K=K.tag,de!==void 0&&((K&2)!==0||(K&4)!==0)&&th(k,p,de),F=F.next}while(F!==M)}No(c,p,k);break;case 1:if(!zr&&(Ga(k,p),M=k.stateNode,typeof M.componentWillUnmount=="function"))try{M.props=k.memoizedProps,M.state=k.memoizedState,M.componentWillUnmount()}catch(_e){Jn(k,p,_e)}No(c,p,k);break;case 21:No(c,p,k);break;case 22:k.mode&1?(zr=(M=zr)||k.memoizedState!==null,No(c,p,k),zr=M):No(c,p,k);break;default:No(c,p,k)}}function Wl(c){var p=c.updateQueue;if(p!==null){c.updateQueue=null;var k=c.stateNode;k===null&&(k=c.stateNode=new Fg),p.forEach(function(M){var F=Yg.bind(null,c,M);k.has(M)||(k.add(M),M.then(F,F))})}}function Ws(c,p){var k=p.deletions;if(k!==null)for(var M=0;M<k.length;M++){var F=k[M];try{var K=c,de=p,_e=de;e:for(;_e!==null;){switch(_e.tag){case 5:Cr=_e.stateNode,di=!1;break e;case 3:Cr=_e.stateNode.containerInfo,di=!0;break e;case 4:Cr=_e.stateNode.containerInfo,di=!0;break e}_e=_e.return}if(Cr===null)throw Error(r(160));Hg(K,de,F),Cr=null,di=!1;var $e=F.alternate;$e!==null&&($e.return=null),F.return=null}catch(qe){Jn(F,p,qe)}}if(p.subtreeFlags&12854)for(p=p.child;p!==null;)oh(p,c),p=p.sibling}function oh(c,p){var k=c.alternate,M=c.flags;switch(c.tag){case 0:case 11:case 14:case 15:if(Ws(p,c),hi(c),M&4){try{Hl(3,c,c.return),nh(3,c)}catch(Dt){Jn(c,c.return,Dt)}try{Hl(5,c,c.return)}catch(Dt){Jn(c,c.return,Dt)}}break;case 1:Ws(p,c),hi(c),M&512&&k!==null&&Ga(k,k.return);break;case 5:if(Ws(p,c),hi(c),M&512&&k!==null&&Ga(k,k.return),c.flags&32){var F=c.stateNode;try{Tt(F,"")}catch(Dt){Jn(c,c.return,Dt)}}if(M&4&&(F=c.stateNode,F!=null)){var K=c.memoizedProps,de=k!==null?k.memoizedProps:K,_e=c.type,$e=c.updateQueue;if(c.updateQueue=null,$e!==null)try{_e==="input"&&K.type==="radio"&&K.name!=null&&bt(F,K),yn(_e,de);var qe=yn(_e,K);for(de=0;de<$e.length;de+=2){var at=$e[de],ct=$e[de+1];at==="style"?Ta(F,ct):at==="dangerouslySetInnerHTML"?St(F,ct):at==="children"?Tt(F,ct):C(F,at,ct,qe)}switch(_e){case"input":st(F,K);break;case"textarea":On(F,K);break;case"select":var ot=F._wrapperState.wasMultiple;F._wrapperState.wasMultiple=!!K.multiple;var jt=K.value;jt!=null?yt(F,!!K.multiple,jt,!1):ot!==!!K.multiple&&(K.defaultValue!=null?yt(F,!!K.multiple,K.defaultValue,!0):yt(F,!!K.multiple,K.multiple?[]:"",!1))}F[Il]=K}catch(Dt){Jn(c,c.return,Dt)}}break;case 6:if(Ws(p,c),hi(c),M&4){if(c.stateNode===null)throw Error(r(162));F=c.stateNode,K=c.memoizedProps;try{F.nodeValue=K}catch(Dt){Jn(c,c.return,Dt)}}break;case 3:if(Ws(p,c),hi(c),M&4&&k!==null&&k.memoizedState.isDehydrated)try{Vi(p.containerInfo)}catch(Dt){Jn(c,c.return,Dt)}break;case 4:Ws(p,c),hi(c);break;case 13:Ws(p,c),hi(c),F=c.child,F.flags&8192&&(K=F.memoizedState!==null,F.stateNode.isHidden=K,!K||F.alternate!==null&&F.alternate.memoizedState!==null||(uh=kn())),M&4&&Wl(c);break;case 22:if(at=k!==null&&k.memoizedState!==null,c.mode&1?(zr=(qe=zr)||at,Ws(p,c),zr=qe):Ws(p,c),hi(c),M&8192){if(qe=c.memoizedState!==null,(c.stateNode.isHidden=qe)&&!at&&(c.mode&1)!==0)for(It=c,at=c.child;at!==null;){for(ct=It=at;It!==null;){switch(ot=It,jt=ot.child,ot.tag){case 0:case 11:case 14:case 15:Hl(4,ot,ot.return);break;case 1:Ga(ot,ot.return);var Pt=ot.stateNode;if(typeof Pt.componentWillUnmount=="function"){M=ot,k=ot.return;try{p=M,Pt.props=p.memoizedProps,Pt.state=p.memoizedState,Pt.componentWillUnmount()}catch(Dt){Jn(M,k,Dt)}}break;case 5:Ga(ot,ot.return);break;case 22:if(ot.memoizedState!==null){ah(ct);continue}}jt!==null?(jt.return=ot,It=jt):ah(ct)}at=at.sibling}e:for(at=null,ct=c;;){if(ct.tag===5){if(at===null){at=ct;try{F=ct.stateNode,qe?(K=F.style,typeof K.setProperty=="function"?K.setProperty("display","none","important"):K.display="none"):(_e=ct.stateNode,$e=ct.memoizedProps.style,de=$e!=null&&$e.hasOwnProperty("display")?$e.display:null,_e.style.display=$r("display",de))}catch(Dt){Jn(c,c.return,Dt)}}}else if(ct.tag===6){if(at===null)try{ct.stateNode.nodeValue=qe?"":ct.memoizedProps}catch(Dt){Jn(c,c.return,Dt)}}else if((ct.tag!==22&&ct.tag!==23||ct.memoizedState===null||ct===c)&&ct.child!==null){ct.child.return=ct,ct=ct.child;continue}if(ct===c)break e;for(;ct.sibling===null;){if(ct.return===null||ct.return===c)break e;at===ct&&(at=null),ct=ct.return}at===ct&&(at=null),ct.sibling.return=ct.return,ct=ct.sibling}}break;case 19:Ws(p,c),hi(c),M&4&&Wl(c);break;case 21:break;default:Ws(p,c),hi(c)}}function hi(c){var p=c.flags;if(p&2){try{e:{for(var k=c.return;k!==null;){if(_p(k)){var M=k;break e}k=k.return}throw Error(r(160))}switch(M.tag){case 5:var F=M.stateNode;M.flags&32&&(Tt(F,""),M.flags&=-33);var K=kp(c);ih(c,K,F);break;case 3:case 4:var de=M.stateNode.containerInfo,_e=kp(c);sh(c,_e,de);break;default:throw Error(r(161))}}catch($e){Jn(c,c.return,$e)}c.flags&=-3}p&4096&&(c.flags&=-4097)}function Sp(c,p,k){It=c,Cp(c)}function Cp(c,p,k){for(var M=(c.mode&1)!==0;It!==null;){var F=It,K=F.child;if(F.tag===22&&M){var de=F.memoizedState!==null||eh;if(!de){var _e=F.alternate,$e=_e!==null&&_e.memoizedState!==null||zr;_e=eh;var qe=zr;if(eh=de,(zr=$e)&&!qe)for(It=F;It!==null;)de=It,$e=de.child,de.tag===22&&de.memoizedState!==null?lh(F):$e!==null?($e.return=de,It=$e):lh(F);for(;K!==null;)It=K,Cp(K),K=K.sibling;It=F,eh=_e,zr=qe}jp(c)}else(F.subtreeFlags&8772)!==0&&K!==null?(K.return=F,It=K):jp(c)}}function jp(c){for(;It!==null;){var p=It;if((p.flags&8772)!==0){var k=p.alternate;try{if((p.flags&8772)!==0)switch(p.tag){case 0:case 11:case 15:zr||nh(5,p);break;case 1:var M=p.stateNode;if(p.flags&4&&!zr)if(k===null)M.componentDidMount();else{var F=p.elementType===p.type?k.memoizedProps:hr(p.type,k.memoizedProps);M.componentDidUpdate(F,k.memoizedState,M.__reactInternalSnapshotBeforeUpdate)}var K=p.updateQueue;K!==null&&Eg(p,K,M);break;case 3:var de=p.updateQueue;if(de!==null){if(k=null,p.child!==null)switch(p.child.tag){case 5:k=p.child.stateNode;break;case 1:k=p.child.stateNode}Eg(p,de,k)}break;case 5:var _e=p.stateNode;if(k===null&&p.flags&4){k=_e;var $e=p.memoizedProps;switch(p.type){case"button":case"input":case"select":case"textarea":$e.autoFocus&&k.focus();break;case"img":$e.src&&(k.src=$e.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(p.memoizedState===null){var qe=p.alternate;if(qe!==null){var at=qe.memoizedState;if(at!==null){var ct=at.dehydrated;ct!==null&&Vi(ct)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(r(163))}zr||p.flags&512&&rh(p)}catch(ot){Jn(p,p.return,ot)}}if(p===c){It=null;break}if(k=p.sibling,k!==null){k.return=p.return,It=k;break}It=p.return}}function ah(c){for(;It!==null;){var p=It;if(p===c){It=null;break}var k=p.sibling;if(k!==null){k.return=p.return,It=k;break}It=p.return}}function lh(c){for(;It!==null;){var p=It;try{switch(p.tag){case 0:case 11:case 15:var k=p.return;try{nh(4,p)}catch($e){Jn(p,k,$e)}break;case 1:var M=p.stateNode;if(typeof M.componentDidMount=="function"){var F=p.return;try{M.componentDidMount()}catch($e){Jn(p,F,$e)}}var K=p.return;try{rh(p)}catch($e){Jn(p,K,$e)}break;case 5:var de=p.return;try{rh(p)}catch($e){Jn(p,de,$e)}}}catch($e){Jn(p,p.return,$e)}if(p===c){It=null;break}var _e=p.sibling;if(_e!==null){_e.return=p.return,It=_e;break}It=p.return}}var Wg=Math.ceil,iu=N.ReactCurrentDispatcher,ou=N.ReactCurrentOwner,qs=N.ReactCurrentBatchConfig,gn=0,fr=null,ar=null,jr=0,Ts=0,Ka=Ki(0),br=0,ql=null,la=0,au=0,ch=0,lu=null,vs=null,uh=0,Xa=1/0,To=null,cu=!1,dh=null,$o=null,uu=!1,ca=null,du=0,Vl=0,hh=null,Gl=-1,hu=0;function es(){return(gn&6)!==0?kn():Gl!==-1?Gl:Gl=kn()}function Ao(c){return(c.mode&1)===0?1:(gn&2)!==0&&jr!==0?jr&-jr:_d.transition!==null?(hu===0&&(hu=Es()),hu):(c=Pe,c!==0||(c=window.event,c=c===void 0?16:fe(c.type)),c)}function fi(c,p,k,M){if(50<Vl)throw Vl=0,hh=null,Error(r(185));qr(c,k,M),((gn&2)===0||c!==fr)&&(c===fr&&((gn&2)===0&&(au|=k),br===4&&Ro(c,jr)),bs(c,M),k===1&&gn===0&&(p.mode&1)===0&&(Xa=kn()+500,Hc&&So()))}function bs(c,p){var k=c.callbackNode;ds(c,p);var M=ji(c,c===fr?jr:0);if(M===0)k!==null&&Sr(k),c.callbackNode=null,c.callbackPriority=0;else if(p=M&-M,c.callbackPriority!==p){if(k!=null&&Sr(k),p===1)c.tag===0?fv(Tp.bind(null,c)):If(Tp.bind(null,c)),kg(function(){(gn&6)===0&&So()}),k=null;else{switch(Qe(M)){case 1:k=Vn;break;case 4:k=Ir;break;case 16:k=ni;break;case 536870912:k=ki;break;default:k=ni}k=Pp(k,Ep.bind(null,c))}c.callbackPriority=p,c.callbackNode=k}}function Ep(c,p){if(Gl=-1,hu=0,(gn&6)!==0)throw Error(r(327));var k=c.callbackNode;if(Ya()&&c.callbackNode!==k)return null;var M=ji(c,c===fr?jr:0);if(M===0)return null;if((M&30)!==0||(M&c.expiredLanes)!==0||p)p=fu(c,M);else{p=M;var F=gn;gn|=2;var K=qg();(fr!==c||jr!==p)&&(To=null,Xa=kn()+500,da(c,p));do try{xv();break}catch(_e){$p(c,_e)}while(!0);Cd(),iu.current=K,gn=F,ar!==null?p=0:(fr=null,jr=0,p=br)}if(p!==0){if(p===2&&(F=Wi(c),F!==0&&(M=F,p=fh(c,F))),p===1)throw k=ql,da(c,0),Ro(c,M),bs(c,kn()),k;if(p===6)Ro(c,M);else{if(F=c.current.alternate,(M&30)===0&&!Np(F)&&(p=fu(c,M),p===2&&(K=Wi(c),K!==0&&(M=K,p=fh(c,K))),p===1))throw k=ql,da(c,0),Ro(c,M),bs(c,kn()),k;switch(c.finishedWork=F,c.finishedLanes=M,p){case 0:case 1:throw Error(r(345));case 2:ha(c,vs,To);break;case 3:if(Ro(c,M),(M&130023424)===M&&(p=uh+500-kn(),10<p)){if(ji(c,0)!==0)break;if(F=c.suspendedLanes,(F&M)!==M){es(),c.pingedLanes|=c.suspendedLanes&F;break}c.timeoutHandle=ud(ha.bind(null,c,vs,To),p);break}ha(c,vs,To);break;case 4:if(Ro(c,M),(M&4194240)===M)break;for(p=c.eventTimes,F=-1;0<M;){var de=31-Gn(M);K=1<<de,de=p[de],de>F&&(F=de),M&=~K}if(M=F,M=kn()-M,M=(120>M?120:480>M?480:1080>M?1080:1920>M?1920:3e3>M?3e3:4320>M?4320:1960*Wg(M/1960))-M,10<M){c.timeoutHandle=ud(ha.bind(null,c,vs,To),M);break}ha(c,vs,To);break;case 5:ha(c,vs,To);break;default:throw Error(r(329))}}}return bs(c,kn()),c.callbackNode===k?Ep.bind(null,c):null}function fh(c,p){var k=lu;return c.current.memoizedState.isDehydrated&&(da(c,p).flags|=256),c=fu(c,p),c!==2&&(p=vs,vs=k,p!==null&&ph(p)),c}function ph(c){vs===null?vs=c:vs.push.apply(vs,c)}function Np(c){for(var p=c;;){if(p.flags&16384){var k=p.updateQueue;if(k!==null&&(k=k.stores,k!==null))for(var M=0;M<k.length;M++){var F=k[M],K=F.getSnapshot;F=F.value;try{if(!li(K(),F))return!1}catch{return!1}}}if(k=p.child,p.subtreeFlags&16384&&k!==null)k.return=p,p=k;else{if(p===c)break;for(;p.sibling===null;){if(p.return===null||p.return===c)return!0;p=p.return}p.sibling.return=p.return,p=p.sibling}}return!0}function Ro(c,p){for(p&=~ch,p&=~au,c.suspendedLanes|=p,c.pingedLanes&=~p,c=c.expirationTimes;0<p;){var k=31-Gn(p),M=1<<k;c[k]=-1,p&=~M}}function Tp(c){if((gn&6)!==0)throw Error(r(327));Ya();var p=ji(c,0);if((p&1)===0)return bs(c,kn()),null;var k=fu(c,p);if(c.tag!==0&&k===2){var M=Wi(c);M!==0&&(p=M,k=fh(c,M))}if(k===1)throw k=ql,da(c,0),Ro(c,p),bs(c,kn()),k;if(k===6)throw Error(r(345));return c.finishedWork=c.current.alternate,c.finishedLanes=p,ha(c,vs,To),bs(c,kn()),null}function mh(c,p){var k=gn;gn|=1;try{return c(p)}finally{gn=k,gn===0&&(Xa=kn()+500,Hc&&So())}}function ua(c){ca!==null&&ca.tag===0&&(gn&6)===0&&Ya();var p=gn;gn|=1;var k=qs.transition,M=Pe;try{if(qs.transition=null,Pe=1,c)return c()}finally{Pe=M,qs.transition=k,gn=p,(gn&6)===0&&So()}}function gh(){Ts=Ka.current,Bn(Ka)}function da(c,p){c.finishedWork=null,c.finishedLanes=0;var k=c.timeoutHandle;if(k!==-1&&(c.timeoutHandle=-1,_g(k)),ar!==null)for(k=ar.return;k!==null;){var M=k;switch(md(M),M.tag){case 1:M=M.type.childContextTypes,M!=null&&Fc();break;case 3:sa(),Bn(hs),Bn(Jr),Rd();break;case 5:$d(M);break;case 4:sa();break;case 13:Bn(Yn);break;case 19:Bn(Yn);break;case 10:jd(M.type._context);break;case 22:case 23:gh()}k=k.return}if(fr=c,ar=c=Mo(c.current,null),jr=Ts=p,br=0,ql=null,ch=au=la=0,vs=lu=null,Wa!==null){for(p=0;p<Wa.length;p++)if(k=Wa[p],M=k.interleaved,M!==null){k.interleaved=null;var F=M.next,K=k.pending;if(K!==null){var de=K.next;K.next=F,M.next=de}k.pending=M}Wa=null}return c}function $p(c,p){do{var k=ar;try{if(Cd(),Md.current=tu,Pd){for(var M=Xn.memoizedState;M!==null;){var F=M.queue;F!==null&&(F.pending=null),M=M.next}Pd=!1}if(ia=0,vr=dr=Xn=null,oa=!1,Eo=0,ou.current=null,k===null||k.return===null){br=1,ql=p,ar=null;break}e:{var K=c,de=k.return,_e=k,$e=p;if(p=jr,_e.flags|=32768,$e!==null&&typeof $e=="object"&&typeof $e.then=="function"){var qe=$e,at=_e,ct=at.tag;if((at.mode&1)===0&&(ct===0||ct===11||ct===15)){var ot=at.alternate;ot?(at.updateQueue=ot.updateQueue,at.memoizedState=ot.memoizedState,at.lanes=ot.lanes):(at.updateQueue=null,at.memoizedState=null)}var jt=Dg(de);if(jt!==null){jt.flags&=-257,Zr(jt,de,_e,K,p),jt.mode&1&&cp(K,qe,p),p=jt,$e=qe;var Pt=p.updateQueue;if(Pt===null){var Dt=new Set;Dt.add($e),p.updateQueue=Dt}else Pt.add($e);break e}else{if((p&1)===0){cp(K,qe,p),xh();break e}$e=Error(r(426))}}else if(Kn&&_e.mode&1){var Pn=Dg(de);if(Pn!==null){(Pn.flags&65536)===0&&(Pn.flags|=256),Zr(Pn,de,_e,K,p),wd(Va($e,_e));break e}}K=$e=Va($e,_e),br!==4&&(br=2),lu===null?lu=[K]:lu.push(K),K=de;do{switch(K.tag){case 3:K.flags|=65536,p&=-p,K.lanes|=p;var Ue=ap(K,$e,p);jg(K,Ue);break e;case 1:_e=$e;var Ie=K.type,Ve=K.stateNode;if((K.flags&128)===0&&(typeof Ie.getDerivedStateFromError=="function"||Ve!==null&&typeof Ve.componentDidCatch=="function"&&($o===null||!$o.has(Ve)))){K.flags|=65536,p&=-p,K.lanes|=p;var ht=lp(K,_e,p);jg(K,ht);break e}}K=K.return}while(K!==null)}Kl(k)}catch(Ft){p=Ft,ar===k&&k!==null&&(ar=k=k.return);continue}break}while(!0)}function qg(){var c=iu.current;return iu.current=tu,c===null?tu:c}function xh(){(br===0||br===3||br===2)&&(br=4),fr===null||(la&268435455)===0&&(au&268435455)===0||Ro(fr,jr)}function fu(c,p){var k=gn;gn|=2;var M=qg();(fr!==c||jr!==p)&&(To=null,da(c,p));do try{Vg();break}catch(F){$p(c,F)}while(!0);if(Cd(),gn=k,iu.current=M,ar!==null)throw Error(r(261));return fr=null,jr=0,br}function Vg(){for(;ar!==null;)Ap(ar)}function xv(){for(;ar!==null&&!Aa();)Ap(ar)}function Ap(c){var p=Ip(c.alternate,c,Ts);c.memoizedProps=c.pendingProps,p===null?Kl(c):ar=p,ou.current=null}function Kl(c){var p=c;do{var k=p.alternate;if(c=p.return,(p.flags&32768)===0){if(k=zg(k,p,Ts),k!==null){ar=k;return}}else{if(k=Bg(k,p),k!==null){k.flags&=32767,ar=k;return}if(c!==null)c.flags|=32768,c.subtreeFlags=0,c.deletions=null;else{br=6,ar=null;return}}if(p=p.sibling,p!==null){ar=p;return}ar=p=c}while(p!==null);br===0&&(br=5)}function ha(c,p,k){var M=Pe,F=qs.transition;try{qs.transition=null,Pe=1,Rp(c,p,k,M)}finally{qs.transition=F,Pe=M}return null}function Rp(c,p,k,M){do Ya();while(ca!==null);if((gn&6)!==0)throw Error(r(327));k=c.finishedWork;var F=c.finishedLanes;if(k===null)return null;if(c.finishedWork=null,c.finishedLanes=0,k===c.current)throw Error(r(177));c.callbackNode=null,c.callbackPriority=0;var K=k.lanes|k.childLanes;if(ft(c,K),c===fr&&(ar=fr=null,jr=0),(k.subtreeFlags&2064)===0&&(k.flags&2064)===0||uu||(uu=!0,Pp(ni,function(){return Ya(),null})),K=(k.flags&15990)!==0,(k.subtreeFlags&15990)!==0||K){K=qs.transition,qs.transition=null;var de=Pe;Pe=1;var _e=gn;gn|=4,ou.current=null,Ug(c,k),oh(k,c),xg(ld),bo=!!ad,ld=ad=null,c.current=k,Sp(k),Ra(),gn=_e,Pe=de,qs.transition=K}else c.current=k;if(uu&&(uu=!1,ca=c,du=F),K=c.pendingLanes,K===0&&($o=null),Bt(k.stateNode),bs(c,kn()),p!==null)for(M=c.onRecoverableError,k=0;k<p.length;k++)F=p[k],M(F.value,{componentStack:F.stack,digest:F.digest});if(cu)throw cu=!1,c=dh,dh=null,c;return(du&1)!==0&&c.tag!==0&&Ya(),K=c.pendingLanes,(K&1)!==0?c===hh?Vl++:(Vl=0,hh=c):Vl=0,So(),null}function Ya(){if(ca!==null){var c=Qe(du),p=qs.transition,k=Pe;try{if(qs.transition=null,Pe=16>c?16:c,ca===null)var M=!1;else{if(c=ca,ca=null,du=0,(gn&6)!==0)throw Error(r(331));var F=gn;for(gn|=4,It=c.current;It!==null;){var K=It,de=K.child;if((It.flags&16)!==0){var _e=K.deletions;if(_e!==null){for(var $e=0;$e<_e.length;$e++){var qe=_e[$e];for(It=qe;It!==null;){var at=It;switch(at.tag){case 0:case 11:case 15:Hl(8,at,K)}var ct=at.child;if(ct!==null)ct.return=at,It=ct;else for(;It!==null;){at=It;var ot=at.sibling,jt=at.return;if(wp(at),at===qe){It=null;break}if(ot!==null){ot.return=jt,It=ot;break}It=jt}}}var Pt=K.alternate;if(Pt!==null){var Dt=Pt.child;if(Dt!==null){Pt.child=null;do{var Pn=Dt.sibling;Dt.sibling=null,Dt=Pn}while(Dt!==null)}}It=K}}if((K.subtreeFlags&2064)!==0&&de!==null)de.return=K,It=de;else e:for(;It!==null;){if(K=It,(K.flags&2048)!==0)switch(K.tag){case 0:case 11:case 15:Hl(9,K,K.return)}var Ue=K.sibling;if(Ue!==null){Ue.return=K.return,It=Ue;break e}It=K.return}}var Ie=c.current;for(It=Ie;It!==null;){de=It;var Ve=de.child;if((de.subtreeFlags&2064)!==0&&Ve!==null)Ve.return=de,It=Ve;else e:for(de=Ie;It!==null;){if(_e=It,(_e.flags&2048)!==0)try{switch(_e.tag){case 0:case 11:case 15:nh(9,_e)}}catch(Ft){Jn(_e,_e.return,Ft)}if(_e===de){It=null;break e}var ht=_e.sibling;if(ht!==null){ht.return=_e.return,It=ht;break e}It=_e.return}}if(gn=F,So(),gr&&typeof gr.onPostCommitFiberRoot=="function")try{gr.onPostCommitFiberRoot(cs,c)}catch{}M=!0}return M}finally{Pe=k,qs.transition=p}}return!1}function Mp(c,p,k){p=Va(k,p),p=ap(c,p,1),c=jo(c,p,1),p=es(),c!==null&&(qr(c,1,p),bs(c,p))}function Jn(c,p,k){if(c.tag===3)Mp(c,c,k);else for(;p!==null;){if(p.tag===3){Mp(p,c,k);break}else if(p.tag===1){var M=p.stateNode;if(typeof p.type.getDerivedStateFromError=="function"||typeof M.componentDidCatch=="function"&&($o===null||!$o.has(M))){c=Va(k,c),c=lp(p,c,1),p=jo(p,c,1),c=es(),p!==null&&(qr(p,1,c),bs(p,c));break}}p=p.return}}function Gg(c,p,k){var M=c.pingCache;M!==null&&M.delete(p),p=es(),c.pingedLanes|=c.suspendedLanes&k,fr===c&&(jr&k)===k&&(br===4||br===3&&(jr&130023424)===jr&&500>kn()-uh?da(c,0):ch|=k),bs(c,p)}function Kg(c,p){p===0&&((c.mode&1)===0?p=1:(p=Wr,Wr<<=1,(Wr&130023424)===0&&(Wr=4194304)));var k=es();c=Yi(c,p),c!==null&&(qr(c,p,k),bs(c,k))}function Xg(c){var p=c.memoizedState,k=0;p!==null&&(k=p.retryLane),Kg(c,k)}function Yg(c,p){var k=0;switch(c.tag){case 13:var M=c.stateNode,F=c.memoizedState;F!==null&&(k=F.retryLane);break;case 19:M=c.stateNode;break;default:throw Error(r(314))}M!==null&&M.delete(p),Kg(c,k)}var Ip;Ip=function(c,p,k){if(c!==null)if(c.memoizedProps!==p.pendingProps||hs.current)ys=!0;else{if((c.lanes&k)===0&&(p.flags&128)===0)return ys=!1,gv(c,p,k);ys=(c.flags&131072)!==0}else ys=!1,Kn&&(p.flags&1048576)!==0&&Zo(p,qc,p.index);switch(p.lanes=0,p.tag){case 2:var M=p.type;ru(c,p),c=p.pendingProps;var F=Qr(p,Jr.current);Ha(p,k),F=Od(null,p,M,c,F,k);var K=Ld();return p.flags|=1,typeof F=="object"&&F!==null&&typeof F.render=="function"&&F.$$typeof===void 0?(p.tag=1,p.memoizedState=null,p.updateQueue=null,fs(M)?(K=!0,Uc(p)):K=!1,p.memoizedState=F.state!==null&&F.state!==void 0?F.state:null,Xc(p),F.updater=Qi,p.stateNode=F,F._reactInternals=p,Ud(p,M,c,k),p=Vd(null,p,M,!0,K,k)):(p.tag=0,Kn&&K&&ur(p),Or(null,p,F,k),p=p.child),p;case 16:M=p.elementType;e:{switch(ru(c,p),c=p.pendingProps,F=M._init,M=F(M._payload),p.type=M,F=p.tag=Jg(M),c=hr(M,c),F){case 0:p=qd(null,p,M,c,k);break e;case 1:p=pp(null,p,M,c,k);break e;case 11:p=up(null,p,M,c,k);break e;case 14:p=Fl(null,p,M,hr(M.type,c),k);break e}throw Error(r(306,M,""))}return p;case 0:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),qd(c,p,M,F,k);case 1:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),pp(c,p,M,F,k);case 3:e:{if(Gd(p),c===null)throw Error(r(387));M=p.pendingProps,K=p.memoizedState,F=K.element,Nd(c,p),Yc(p,M,null,k);var de=p.memoizedState;if(M=de.element,K.isDehydrated)if(K={element:M,isDehydrated:!1,cache:de.cache,pendingSuspenseBoundaries:de.pendingSuspenseBoundaries,transitions:de.transitions},p.updateQueue.baseState=K,p.memoizedState=K,p.flags&256){F=Va(Error(r(423)),p),p=mp(c,p,M,k,F);break e}else if(M!==F){F=Va(Error(r(424)),p),p=mp(c,p,M,k,F);break e}else for(Ns=_o(p.stateNode.containerInfo.firstChild),gs=p,Kn=!0,xs=null,k=kd(p,null,M,k),p.child=k;k;)k.flags=k.flags&-3|4096,k=k.sibling;else{if(ea(),M===F){p=Zi(c,p,k);break e}Or(c,p,M,k)}p=p.child}return p;case 5:return Lf(p),c===null&&vd(p),M=p.type,F=p.pendingProps,K=c!==null?c.memoizedProps:null,de=F.children,cd(M,F)?de=null:K!==null&&cd(M,K)&&(p.flags|=32),fp(c,p),Or(c,p,de,k),p.child;case 6:return c===null&&vd(p),null;case 13:return gp(c,p,k);case 4:return Td(p,p.stateNode.containerInfo),M=p.pendingProps,c===null?p.child=Ua(p,null,M,k):Or(c,p,M,k),p.child;case 11:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),up(c,p,M,F,k);case 7:return Or(c,p,p.pendingProps,k),p.child;case 8:return Or(c,p,p.pendingProps.children,k),p.child;case 12:return Or(c,p,p.pendingProps.children,k),p.child;case 10:e:{if(M=p.type._context,F=p.pendingProps,K=p.memoizedProps,de=F.value,In(ta,M._currentValue),M._currentValue=de,K!==null)if(li(K.value,de)){if(K.children===F.children&&!hs.current){p=Zi(c,p,k);break e}}else for(K=p.child,K!==null&&(K.return=p);K!==null;){var _e=K.dependencies;if(_e!==null){de=K.child;for(var $e=_e.firstContext;$e!==null;){if($e.context===M){if(K.tag===1){$e=Ji(-1,k&-k),$e.tag=2;var qe=K.updateQueue;if(qe!==null){qe=qe.shared;var at=qe.pending;at===null?$e.next=$e:($e.next=at.next,at.next=$e),qe.pending=$e}}K.lanes|=k,$e=K.alternate,$e!==null&&($e.lanes|=k),Of(K.return,k,p),_e.lanes|=k;break}$e=$e.next}}else if(K.tag===10)de=K.type===p.type?null:K.child;else if(K.tag===18){if(de=K.return,de===null)throw Error(r(341));de.lanes|=k,_e=de.alternate,_e!==null&&(_e.lanes|=k),Of(de,k,p),de=K.sibling}else de=K.child;if(de!==null)de.return=K;else for(de=K;de!==null;){if(de===p){de=null;break}if(K=de.sibling,K!==null){K.return=de.return,de=K;break}de=de.return}K=de}Or(c,p,F.children,k),p=p.child}return p;case 9:return F=p.type,M=p.pendingProps.children,Ha(p,k),F=Us(F),M=M(F),p.flags|=1,Or(c,p,M,k),p.child;case 14:return M=p.type,F=hr(M,p.pendingProps),F=hr(M.type,F),Fl(c,p,M,F,k);case 15:return dp(c,p,p.type,p.pendingProps,k);case 17:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),ru(c,p),p.tag=1,fs(M)?(c=!0,Uc(p)):c=!1,Ha(p,k),ip(p,M,F),Ud(p,M,F,k),Vd(null,p,M,!0,c,k);case 19:return Jd(c,p,k);case 22:return hp(c,p,k)}throw Error(r(156,p.tag))};function Pp(c,p){return Go(c,p)}function yv(c,p,k,M){this.tag=c,this.key=k,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=p,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=M,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function $s(c,p,k,M){return new yv(c,p,k,M)}function yh(c){return c=c.prototype,!(!c||!c.isReactComponent)}function Jg(c){if(typeof c=="function")return yh(c)?1:0;if(c!=null){if(c=c.$$typeof,c===Y)return 11;if(c===te)return 14}return 2}function Mo(c,p){var k=c.alternate;return k===null?(k=$s(c.tag,p,c.key,c.mode),k.elementType=c.elementType,k.type=c.type,k.stateNode=c.stateNode,k.alternate=c,c.alternate=k):(k.pendingProps=p,k.type=c.type,k.flags=0,k.subtreeFlags=0,k.deletions=null),k.flags=c.flags&14680064,k.childLanes=c.childLanes,k.lanes=c.lanes,k.child=c.child,k.memoizedProps=c.memoizedProps,k.memoizedState=c.memoizedState,k.updateQueue=c.updateQueue,p=c.dependencies,k.dependencies=p===null?null:{lanes:p.lanes,firstContext:p.firstContext},k.sibling=c.sibling,k.index=c.index,k.ref=c.ref,k}function pu(c,p,k,M,F,K){var de=2;if(M=c,typeof c=="function")yh(c)&&(de=1);else if(typeof c=="string")de=5;else e:switch(c){case O:return Ja(k.children,F,K,p);case I:de=8,F|=8;break;case z:return c=$s(12,k,p,F|2),c.elementType=z,c.lanes=K,c;case V:return c=$s(13,k,p,F),c.elementType=V,c.lanes=K,c;case H:return c=$s(19,k,p,F),c.elementType=H,c.lanes=K,c;case oe:return mu(k,F,K,p);default:if(typeof c=="object"&&c!==null)switch(c.$$typeof){case U:de=10;break e;case W:de=9;break e;case Y:de=11;break e;case te:de=14;break e;case ae:de=16,M=null;break e}throw Error(r(130,c==null?c:typeof c,""))}return p=$s(de,k,p,F),p.elementType=c,p.type=M,p.lanes=K,p}function Ja(c,p,k,M){return c=$s(7,c,M,p),c.lanes=k,c}function mu(c,p,k,M){return c=$s(22,c,M,p),c.elementType=oe,c.lanes=k,c.stateNode={isHidden:!1},c}function vh(c,p,k){return c=$s(6,c,null,p),c.lanes=k,c}function bh(c,p,k){return p=$s(4,c.children!==null?c.children:[],c.key,p),p.lanes=k,p.stateNode={containerInfo:c.containerInfo,pendingChildren:null,implementation:c.implementation},p}function vv(c,p,k,M,F){this.tag=p,this.containerInfo=c,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ke(0),this.expirationTimes=Ke(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ke(0),this.identifierPrefix=M,this.onRecoverableError=F,this.mutableSourceEagerHydrationData=null}function wh(c,p,k,M,F,K,de,_e,$e){return c=new vv(c,p,k,_e,$e),p===1?(p=1,K===!0&&(p|=8)):p=0,K=$s(3,null,null,p),c.current=K,K.stateNode=c,K.memoizedState={element:M,isDehydrated:k,cache:null,transitions:null,pendingSuspenseBoundaries:null},Xc(K),c}function bv(c,p,k){var M=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:R,key:M==null?null:""+M,children:c,containerInfo:p,implementation:k}}function Dp(c){if(!c)return ko;c=c._reactInternals;e:{if(Ct(c)!==c||c.tag!==1)throw Error(r(170));var p=c;do{switch(p.tag){case 3:p=p.stateNode.context;break e;case 1:if(fs(p.type)){p=p.stateNode.__reactInternalMemoizedMergedChildContext;break e}}p=p.return}while(p!==null);throw Error(r(171))}if(c.tag===1){var k=c.type;if(fs(k))return Rf(c,k,p)}return p}function Qg(c,p,k,M,F,K,de,_e,$e){return c=wh(k,M,!0,c,F,K,de,_e,$e),c.context=Dp(null),k=c.current,M=es(),F=Ao(k),K=Ji(M,F),K.callback=p??null,jo(k,K,F),c.current.lanes=F,qr(c,F,M),bs(c,M),c}function gu(c,p,k,M){var F=p.current,K=es(),de=Ao(F);return k=Dp(k),p.context===null?p.context=k:p.pendingContext=k,p=Ji(K,de),p.payload={element:c},M=M===void 0?null:M,M!==null&&(p.callback=M),c=jo(F,p,de),c!==null&&(fi(c,F,de,K),Ol(c,F,de)),de}function xu(c){if(c=c.current,!c.child)return null;switch(c.child.tag){case 5:return c.child.stateNode;default:return c.child.stateNode}}function Op(c,p){if(c=c.memoizedState,c!==null&&c.dehydrated!==null){var k=c.retryLane;c.retryLane=k!==0&&k<p?k:p}}function _h(c,p){Op(c,p),(c=c.alternate)&&Op(c,p)}function Zg(){return null}var ex=typeof reportError=="function"?reportError:function(c){console.error(c)};function kh(c){this._internalRoot=c}Qa.prototype.render=kh.prototype.render=function(c){var p=this._internalRoot;if(p===null)throw Error(r(409));gu(c,p,null,null)},Qa.prototype.unmount=kh.prototype.unmount=function(){var c=this._internalRoot;if(c!==null){this._internalRoot=null;var p=c.containerInfo;ua(function(){gu(null,c,null,null)}),p[Ri]=null}};function Qa(c){this._internalRoot=c}Qa.prototype.unstable_scheduleHydration=function(c){if(c){var p=$n();c={blockedOn:null,target:c,priority:p};for(var k=0;k<ri.length&&p!==0&&p<ri[k].priority;k++);ri.splice(k,0,c),k===0&&bl(c)}};function Sh(c){return!(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11)}function yu(c){return!(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11&&(c.nodeType!==8||c.nodeValue!==" react-mount-point-unstable "))}function tx(){}function nx(c,p,k,M,F){if(F){if(typeof M=="function"){var K=M;M=function(){var qe=xu(de);K.call(qe)}}var de=Qg(p,M,c,0,null,!1,!1,"",tx);return c._reactRootContainer=de,c[Ri]=de.current,Rl(c.nodeType===8?c.parentNode:c),ua(),de}for(;F=c.lastChild;)c.removeChild(F);if(typeof M=="function"){var _e=M;M=function(){var qe=xu($e);_e.call(qe)}}var $e=wh(c,0,!1,null,null,!1,!1,"",tx);return c._reactRootContainer=$e,c[Ri]=$e.current,Rl(c.nodeType===8?c.parentNode:c),ua(function(){gu(p,$e,k,M)}),$e}function Xl(c,p,k,M,F){var K=k._reactRootContainer;if(K){var de=K;if(typeof F=="function"){var _e=F;F=function(){var $e=xu(de);_e.call($e)}}gu(p,de,c,F)}else de=nx(k,p,c,F,M);return xu(de)}Et=function(c){switch(c.tag){case 3:var p=c.stateNode;if(p.current.memoizedState.isDehydrated){var k=Ps(p.pendingLanes);k!==0&&(be(p,k|1),bs(p,kn()),(gn&6)===0&&(Xa=kn()+500,So()))}break;case 13:ua(function(){var M=Yi(c,1);if(M!==null){var F=es();fi(M,c,1,F)}}),_h(c,1)}},en=function(c){if(c.tag===13){var p=Yi(c,134217728);if(p!==null){var k=es();fi(p,c,134217728,k)}_h(c,134217728)}},ln=function(c){if(c.tag===13){var p=Ao(c),k=Yi(c,p);if(k!==null){var M=es();fi(k,c,p,M)}_h(c,p)}},$n=function(){return Pe},En=function(c,p){var k=Pe;try{return Pe=c,p()}finally{Pe=k}},bi=function(c,p,k){switch(p){case"input":if(st(c,k),p=k.name,k.type==="radio"&&p!=null){for(k=c;k.parentNode;)k=k.parentNode;for(k=k.querySelectorAll("input[name="+JSON.stringify(""+p)+'][type="radio"]'),p=0;p<k.length;p++){var M=k[p];if(M!==c&&M.form===c.form){var F=Bc(M);if(!F)throw Error(r(90));lt(M),st(M,F)}}}break;case"textarea":On(c,k);break;case"select":p=k.value,p!=null&&yt(c,!!k.multiple,p,!1)}},Is=mh,Ar=ua;var Lp={usingClientEntryPoint:!1,Events:[Pl,Oa,Bc,wi,_i,mh]},pi={findFiberByHostInstance:Jo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},rx={bundleType:pi.bundleType,version:pi.version,rendererPackageName:pi.rendererPackageName,rendererConfig:pi.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:N.ReactCurrentDispatcher,findHostInstanceByFiber:function(c){return c=po(c),c===null?null:c.stateNode},findFiberByHostInstance:pi.findFiberByHostInstance||Zg,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Yl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Yl.isDisabled&&Yl.supportsFiber)try{cs=Yl.inject(rx),gr=Yl}catch{}}return mi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Lp,mi.createPortal=function(c,p){var k=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Sh(p))throw Error(r(200));return bv(c,p,null,k)},mi.createRoot=function(c,p){if(!Sh(c))throw Error(r(299));var k=!1,M="",F=ex;return p!=null&&(p.unstable_strictMode===!0&&(k=!0),p.identifierPrefix!==void 0&&(M=p.identifierPrefix),p.onRecoverableError!==void 0&&(F=p.onRecoverableError)),p=wh(c,1,!1,null,null,k,!1,M,F),c[Ri]=p.current,Rl(c.nodeType===8?c.parentNode:c),new kh(p)},mi.findDOMNode=function(c){if(c==null)return null;if(c.nodeType===1)return c;var p=c._reactInternals;if(p===void 0)throw typeof c.render=="function"?Error(r(188)):(c=Object.keys(c).join(","),Error(r(268,c)));return c=po(p),c=c===null?null:c.stateNode,c},mi.flushSync=function(c){return ua(c)},mi.hydrate=function(c,p,k){if(!yu(p))throw Error(r(200));return Xl(null,c,p,!0,k)},mi.hydrateRoot=function(c,p,k){if(!Sh(c))throw Error(r(405));var M=k!=null&&k.hydratedSources||null,F=!1,K="",de=ex;if(k!=null&&(k.unstable_strictMode===!0&&(F=!0),k.identifierPrefix!==void 0&&(K=k.identifierPrefix),k.onRecoverableError!==void 0&&(de=k.onRecoverableError)),p=Qg(p,null,c,1,k??null,F,!1,K,de),c[Ri]=p.current,Rl(c),M)for(c=0;c<M.length;c++)k=M[c],F=k._getVersion,F=F(k._source),p.mutableSourceEagerHydrationData==null?p.mutableSourceEagerHydrationData=[k,F]:p.mutableSourceEagerHydrationData.push(k,F);return new Qa(p)},mi.render=function(c,p,k){if(!yu(p))throw Error(r(200));return Xl(null,c,p,!1,k)},mi.unmountComponentAtNode=function(c){if(!yu(c))throw Error(r(40));return c._reactRootContainer?(ua(function(){Xl(null,null,c,!1,function(){c._reactRootContainer=null,c[Ri]=null})}),!0):!1},mi.unstable_batchedUpdates=mh,mi.unstable_renderSubtreeIntoContainer=function(c,p,k,M){if(!yu(k))throw Error(r(200));if(c==null||c._reactInternals===void 0)throw Error(r(38));return Xl(c,p,k,!1,M)},mi.version="18.3.1-next-f1338f8080-20240426",mi}var n_;function k2(){if(n_)return Cv.exports;n_=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(n){console.error(n)}}return e(),Cv.exports=NN(),Cv.exports}var r_;function TN(){if(r_)return ix;r_=1;var e=k2();return ix.createRoot=e.createRoot,ix.hydrateRoot=e.hydrateRoot,ix}var $N=TN();const AN=Gy($N);var L=Xw();const co=Gy(L),s_=e=>{let n;const r=new Set,i=(m,x)=>{const g=typeof m=="function"?m(n):m;if(!Object.is(g,n)){const v=n;n=x??(typeof g!="object"||g===null)?g:Object.assign({},n,g),r.forEach(S=>S(n,v))}},o=()=>n,u={setState:i,getState:o,getInitialState:()=>h,subscribe:m=>(r.add(m),()=>r.delete(m))},h=n=e(i,o,u);return u},RN=(e=>e?s_(e):s_),MN=e=>e;function IN(e,n=MN){const r=co.useSyncExternalStore(e.subscribe,co.useCallback(()=>n(e.getState()),[e,n]),co.useCallback(()=>n(e.getInitialState()),[e,n]));return co.useDebugValue(r),r}const i_=e=>{const n=RN(e),r=i=>IN(n,i);return Object.assign(r,n),r},cr=(e=>e?i_(e):i_);function Ho(e){return"'"+e.replace(/'/g,"'\\''")+"'"}const Nv=({sessionId:e})=>`claude --dangerously-skip-permissions --session-id ${Ho(e)}`,o_=({sessionId:e})=>`claude --session-id ${Ho(e)}`,PN=()=>"claude --resume",S2=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:Nv},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:o_},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:Nv},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:Nv},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:o_},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:PN},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let to=null;async function DN(){if(to)return to;try{const e=await window.api.app.engageRulesPath();if(!e)return to=[],to;const n=await window.api.config.readJson(e);if(!n.exists||n.parseError||!n.data)return to=[],to;const r=n.data;if(!r.presets||!Array.isArray(r.presets))return to=[],to;const i=r.projectPath;return to=r.presets.map(o=>({id:o.id,label:o.label,description:o.description,category:"engage",cwd:i,platform:o.platform,pipeline:o.pipeline,rules:o.rules,command:()=>`cd ${Ho(i)} && ${o.cliEntry}`})),to}catch(e){return console.warn("[presets] Failed to load engage presets:",e),to=[],to}}async function C2(e){const n=S2.find(i=>i.id===e);return n||((await DN()).find(i=>i.id===e)??null)}async function a_(e){return e.cwd==="app-cwd"?window.api.app.cwd():e.cwd==="home"?window.api.app.homeDir():e.cwd==="pick"?window.api.app.pickDirectory():e.cwd}function j2(e,n){return e.command?e.command(n):null}const Yw=["opus","sonnet","haiku"],E2="sm.rawSessionModel",ON="opus";function LN(e){return Yw.includes(e)}function zN(){try{const e=localStorage.getItem(E2);if(e&&LN(e))return e}catch{}return ON}let zh=zN();const Pb=new Set;function N2(){return zh}function BN(e){if(e!==zh){zh=e;try{localStorage.setItem(E2,e)}catch{}Pb.forEach(n=>n(e))}}function FN(){const[e,n]=L.useState(zh);L.useEffect(()=>{const i=o=>n(o);return Pb.add(i),zh!==e&&n(zh),()=>{Pb.delete(i)}},[]);const r=L.useCallback(i=>BN(i),[]);return{model:e,setModel:r}}async function T2(e,n){const r=await window.api.transcripts.pathFor(e,n);return window.api.config.exists(r)}const UN=5,l_=100,HN=5e3,Db=new Map;function c_(e){const n=Db.get(e);n!==void 0&&(clearTimeout(n),Db.delete(e))}function WN(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const Eu=cr((e,n)=>({toasts:[],history:[],unreadCount:0,show:(r,i)=>{const o=WN(),l=Date.now();e(u=>{const h=[...u.toasts,{id:o,kind:r,message:i,createdAt:l}];for(;h.length>UN;){const g=h.shift();g&&c_(g.id)}const x=[{id:o,kind:r,message:i,createdAt:l,read:!1},...u.history];return x.length>l_&&(x.length=l_),{toasts:h,history:x,unreadCount:u.unreadCount+1}});const d=setTimeout(()=>n().dismiss(o),HN);return Db.set(o,d),o},dismiss:r=>{c_(r),e(i=>({toasts:i.toasts.filter(o=>o.id!==r)}))},markAllRead:()=>{e(r=>r.unreadCount===0?r:{history:r.history.map(i=>i.read?i:{...i,read:!0}),unreadCount:0})},clearHistory:()=>{e({history:[],unreadCount:0})},dismissHistoryEntry:r=>{e(i=>{const o=i.history.filter(d=>d.id!==r);if(o.length===i.history.length)return i;const l=i.history.find(d=>d.id===r&&!d.read);return{history:o,unreadCount:l?Math.max(0,i.unreadCount-1):i.unreadCount}})}})),Le={info:e=>Eu.getState().show("info",e),warn:e=>Eu.getState().show("warn",e),error:e=>Eu.getState().show("error",e),fromOutcome:e=>Eu.getState().show(e.kind??(e.ok?"info":"warn"),e.message)},$2=Object.freeze(Object.defineProperty({__proto__:null,toast:Le,useToast:Eu},Symbol.toStringTag,{value:"Module"}));async function qN(e){var n,r;if(typeof window>"u"||typeof((r=(n=window.api)==null?void 0:n.chat)==null?void 0:r.classifyTicket)!="function")return"inline";try{return await window.api.chat.classifyTicket({text:e})==="develop"?"develop":"inline"}catch{return"inline"}}const Nu={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},u_=20;function Jw(e,n){const r=[...e,n];return r.length>u_?r.slice(r.length-u_):r}let d_=0;function fl(){return d_+=1,`t${Date.now().toString(36)}-${d_}`}const Gs=cr((e,n)=>({chats:{},hydratedTabs:{},get:r=>n().chats[r]??Nu,hydrate:async({tabId:r,cwd:i,sessionId:o})=>{var l,d,u;if(!n().hydratedTabs[r]&&(e({hydratedTabs:{...n().hydratedTabs,[r]:!0}}),!(typeof window>"u"||!((l=window.api)!=null&&l.exchanges))))try{const h=await window.api.exchanges.list({cwd:i,sessionId:o});if(!h.length)return;const m=[];for(const g of[...h].reverse()){const v=new Date(g.ts).getTime();m.push({id:fl(),role:"user",text:g.prompt,at:v}),m.push({id:fl(),role:"assistant",text:g.result,at:v})}const x=n().chats[r]??Nu;e({chats:{...n().chats,[r]:{...x,turns:[...m,...x.turns],started:!0}}})}catch(h){const m=h instanceof Error?h.message:String(h);(u=(d=window.api)==null?void 0:d.logs)==null||u.write("chat","warn",`exchange hydration failed for tab ${r}: ${m}`)}},send:({tabId:r,sessionId:i,cwd:o,prompt:l})=>{const d=l.trim();if(!d)return;const u=n().chats[r]??Nu;if(u.running){const h={id:crypto.randomUUID(),tabId:r,sessionId:i,cwd:o,text:d,status:"queued",createdAt:Date.now()};e({chats:{...n().chats,[r]:{...u,queue:[...u.queue,h]}}});return}A2({tabId:r,sessionId:i,cwd:o,text:d})},resetThread:r=>{e({chats:{...n().chats,[r]:{...Nu}}})},pushNotice:(r,i)=>{Qw(r,"",i)}}));function zo(e,n){const r=Gs.getState().chats[e]??Nu;Gs.setState({chats:{...Gs.getState().chats,[e]:n(r)}})}function Gx(e,n,r={}){zo(e,i=>{const o=i.activeTicket?Jw(i.ticketHistory??[],{...i.activeTicket,status:"done",completedAt:Date.now()}):i.ticketHistory??[];return{...i,turns:[...i.turns,{...n,toolUses:i.liveToolUses}],running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:o,...r}}),R2(e)}function A2(e){const{tabId:n,sessionId:r,cwd:i,text:o,promptId:l}=e,d=Gs.getState().chats[n]??Nu,u={id:fl(),role:"user",text:o,at:Date.now()},h=d.activeTicket??{id:l??crypto.randomUUID(),tabId:n,sessionId:r,cwd:i,text:o,status:"running",createdAt:Date.now(),startedAt:Date.now()};Gs.setState({chats:{...Gs.getState().chats,[n]:{...d,turns:[...d.turns,u],running:!0,queuedPosition:0,stream:"",activeTicket:h}}}),T2(i,r).catch(m=>{var g,v;const x=m instanceof Error?m.message:String(m);return(v=(g=window.api)==null?void 0:g.logs)==null||v.write("chat","warn",`transcript-exists check failed for tab ${n}: ${x}`),d.started}).then(m=>window.api.chat.run({tabId:n,sessionId:r,prompt:o,cwd:i,resume:m,promptId:l})).catch(m=>{const x=m instanceof Error?m.message:String(m);M2(n,r,x)})}function R2(e){const n=Gs.getState().chats[e]??Nu;if(n.queue.length===0)return;const[r,...i]=n.queue;zo(e,o=>({...o,queue:i,running:!0,queuedPosition:0,activeTicket:r})),qN(r.text).then(o=>{if(o==="develop"){const d={...r,status:"dispatched-to-prd",completedAt:Date.now()};Qw(e,d.sessionId,`→ dispatched to /develop for PRD decomposition (ticket ${d.id})`),zo(e,u=>({...u,running:!1,queuedPosition:0,activeTicket:null,ticketHistory:Jw(u.ticketHistory??[],d)})),R2(e);return}const l={...r,status:"running",startedAt:Date.now()};zo(e,d=>({...d,activeTicket:l})),A2({tabId:l.tabId,sessionId:l.sessionId,cwd:l.cwd,text:l.text,promptId:l.id})})}function M2(e,n,r){zo(e,i=>i.activeTicket?{...i,activeTicket:null,ticketHistory:Jw(i.ticketHistory??[],{...i.activeTicket,status:"failed",completedAt:Date.now()})}:i),Gx(e,{id:fl(),role:"error",text:r,at:Date.now()}),Le.error(r)}function Qw(e,n,r){zo(e,i=>({...i,turns:[...i.turns,{id:fl(),role:"notice",text:r,at:Date.now()}]}))}var _2;typeof window<"u"&&((_2=window.api)!=null&&_2.chat)&&(window.api.chat.onQueued(({tabId:e,position:n})=>{zo(e,r=>({...r,running:!0,queuedPosition:n}))}),window.api.chat.onRunStarted(({tabId:e})=>{zo(e,n=>({...n,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:e,delta:n})=>{zo(e,r=>({...r,stream:r.stream+n}))}),window.api.chat.onToolUse(({tabId:e,id:n,kind:r,label:i})=>{zo(e,o=>({...o,liveToolUses:[...o.liveToolUses,{id:n,kind:r,label:i}]}))}),window.api.chat.onComplete(({tabId:e,finalMessage:n})=>{Gx(e,{id:fl(),role:"assistant",text:n,at:Date.now()})}),window.api.chat.onNeedsInput(({tabId:e,questions:n,answerBody:r})=>{if(r&&r.trim()){zo(e,i=>({...i,turns:[...i.turns,{id:fl(),role:"assistant",text:r,at:Date.now(),toolUses:i.liveToolUses}],liveToolUses:[]})),Gx(e,{id:fl(),role:"question",text:n.join(`
|
|
42
42
|
`),questions:n,at:Date.now()});return}Gx(e,{id:fl(),role:"question",text:n.join(`
|
|
43
|
-
`),questions:n,at:Date.now()})}),window.api.chat.onError(({tabId:e,sessionId:n,message:r})=>{M2(e,n,r)}),window.api.chat.onNotice(({tabId:e,sessionId:n,message:r})=>{Qw(e,n,r)}),window.api.chat.onExternalSend(({tabId:e,prompt:n})=>{var i,o;const r=vt.getState().tabs.find(l=>l.id===e);if(!r){(o=(i=window.api)==null?void 0:i.logs)==null||o.write("chat","warn",`external send ignored: tab ${e} is not open`);return}Gs.getState().send({tabId:e,sessionId:r.sessionId,cwd:r.cwd,prompt:n})}));function VN(e){const n=e.split("/").filter(Boolean);return n[n.length-1]||e}async function I2(e,n=!1,r=N2()){let i=!n;i&&(i=await T2(e.cwd,e.sessionId));const o=n&&!i?crypto.randomUUID():e.sessionId,l=i?`claude --dangerously-skip-permissions --resume ${Ho(o)} --model ${r}`:`claude --dangerously-skip-permissions --session-id ${Ho(o)} --model ${r}`;return{sessionId:o,startupCommand:l}}const vt=cr((e,n)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(r,i)=>{e(o=>({pendingRawCommand:{...o.pendingRawCommand,[r]:i}}))},consumeRawCommand:r=>{const i=n().pendingRawCommand[r];return i===void 0?null:(e(o=>{const l={...o.pendingRawCommand};return delete l[r],{pendingRawCommand:l}}),i)},addTab:({id:r,cwd:i,startupCommand:o,presetId:l=null,label:d})=>{const u=r??crypto.randomUUID();if(n().tabs.find(x=>x.id===u))return e({activeTabId:u}),u;const m={id:u,sessionId:u,label:d??VN(i),cwd:i,pid:null,status:"spawning",exitCode:null,startupCommand:o,presetId:l,generation:0};return e({tabs:[...n().tabs,m],activeTabId:u}),u},setTabRunning:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:i,status:"running"}:o)}),setTabExited:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,status:"exited",exitCode:i}:o)}),closeTab:r=>{var l;window.api.pty.kill(r),window.api.watchers.killTab(r).catch(()=>{}),window.api.transcripts.closeTab(r).catch(()=>{});const i=n().tabs.filter(d=>d.id!==r),o=n().activeTabId===r?((l=i[i.length-1])==null?void 0:l.id)??null:n().activeTabId;e({tabs:i,activeTabId:o})},setActive:r=>e({activeTabId:r}),restartTab:r=>{const i=n().tabs.find(d=>d.id===r);if(!i)return;window.api.pty.kill(r);const o=crypto.randomUUID(),l=d=>{e({tabs:n().tabs.map(u=>u.id===r?{...u,sessionId:o,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:u.generation+1}:u)})};i.presetId?C2(i.presetId).then(d=>{l(d?j2(d,{sessionId:o,cwd:i.cwd}):`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)}):l(`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)},reorderTab:(r,i)=>{const o=[...n().tabs];if(r<0||r>=o.length||i<0||i>=o.length||r===i)return;const[l]=o.splice(r,1);o.splice(i,0,l),e({tabs:o})},restoreTabs:(r,i)=>e({tabs:r,activeTabId:i,hydrated:!0}),wakeTab:async(r,i)=>{var u;const o=n().tabs.find(h=>h.id===r);if(!o||o.status!=="dormant")return;(u=Gs.getState().chats[r])!=null&&u.running&&(await window.api.chat.cancel(r),Le.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:l,startupCommand:d}=await I2({cwd:o.cwd,sessionId:o.sessionId},!1,i??N2());e({tabs:n().tabs.map(h=>h.id===r?{...h,sessionId:l,status:"spawning",startupCommand:d,generation:h.generation+1}:h)})},sleepTab:r=>{const i=n().tabs.find(o=>o.id===r);!i||i.status==="dormant"||(window.api.pty.kill(r),e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:null,status:"dormant"}:o)}))},newSession:r=>{n().tabs.find(o=>o.id===r)&&e({tabs:n().tabs.map(o=>o.id===r?{...o,sessionId:crypto.randomUUID()}:o)})}}));async function Ob(){var r;if(vt.getState().hydrated)return;try{const{tabs:i,activeTabId:o,freshStart:l}=await window.api.sessions.load();if(i.length>0){const u=(await Promise.all(i.map(async m=>{try{const{sessionId:x}=await I2(m,l);return{id:m.id,sessionId:x,cwd:m.cwd,label:m.label,presetId:m.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(x){return console.warn("[sessions] dropping malformed persisted tab:",m==null?void 0:m.id,x),null}}))).filter(m=>m!==null),h=o&&u.find(m=>m.id===o)?o:((r=u[0])==null?void 0:r.id)??null;vt.getState().restoreTabs(u,h)}else vt.setState({hydrated:!0})}catch(i){console.warn("[sessions] hydrate failed:",i),vt.setState({hydrated:!0})}const e=()=>{const{tabs:i,activeTabId:o}=vt.getState(),l=i.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:l,activeTabId:o}).catch(d=>{console.warn("[sessions] save failed:",d)})};let n=null;vt.subscribe((i,o)=>{i.hydrated&&(i.tabs===o.tabs&&i.activeTabId===o.activeTabId||(n!==null&&window.clearTimeout(n),n=window.setTimeout(e,200)))}),e()}const GN=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:Ob,useSessions:vt},Symbol.toStringTag,{value:"Module"})),h_=200,KN=/\x1b\[[0-9;]*m/g;function XN(e){return e.replace(KN,"")}const Tm=cr((e,n)=>({watchers:{},initialized:!1,init:()=>{n().initialized||(e({initialized:!0}),window.api.watchers.onLine(r=>n().ingestLine(r)),window.api.watchers.onClosed(({watcherId:r})=>n().closed(r)))},add:async({tabId:r,label:i,command:o,cwd:l})=>{try{const d=await window.api.watchers.add({tabId:r,label:i,command:o,cwd:l??null}),u={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return e({watchers:{...n().watchers,[u.watcherId]:u}}),u}catch(d){return console.error("[watchers] add failed:",d),Le.error("Failed to add watcher"),null}},remove:async r=>{try{await window.api.watchers.remove(r)}catch(o){console.error("[watchers] remove failed:",o);const l=o instanceof Error?o.message:String(o);Le.error(`Could not remove watcher: ${l}`)}const i={...n().watchers};delete i[r],e({watchers:i})},watchersForTab:r=>Object.values(n().watchers).filter(i=>i.tabId===r),ingestLine:r=>{const i=n().watchers[r.watcherId];if(!i)return;const o=XN(r.line),l=i.lines.length>=h_?[...i.lines.slice(i.lines.length-h_+1),{line:o,ts:r.ts}]:[...i.lines,{line:o,ts:r.ts}];e({watchers:{...n().watchers,[r.watcherId]:{...i,lines:l,lineCount:i.lineCount+1,lastLineAt:r.ts}}})},closed:r=>{if(!n().watchers[r])return;const i={...n().watchers};delete i[r],e({watchers:i})}})),YN="~/.claude/session-manager/browser/history.json",f_="~/.claude/session-manager/browser/bookmarks.json",JN=.25,QN=3,p_=.1,m_=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let g_=0;function ZN(){const e=m_[g_%m_.length];return g_+=1,e}const hy=new Map;function eT(e){if(hy.has(e))return;const n=window.api.browser.onNavState(e,r=>{Mt.setState(i=>({tabs:i.tabs.map(o=>o.viewId===e?{...o,url:r.url,title:r.title||o.title,canGoBack:r.canGoBack,canGoForward:r.canGoForward,loading:r.loading,isSecure:r.isSecure}:o)}))});hy.set(e,n)}function tT(e){const n=hy.get(e);n&&(n(),hy.delete(e))}const Lb=new Map;let Kx=null;function x_(e){const n=Lb.get(e);n&&(n(),Lb.delete(e))}function y_(){Kx&&(clearInterval(Kx),Kx=null)}const zb=new Map;function Tv(e){const n=zb.get(e);n&&(n(),zb.delete(e))}const Mt=cr((e,n)=>({tabs:[],activeTabId:null,openTab:r=>{const i=crypto.randomUUID(),o=i,l={id:i,viewId:o,title:"New Tab",url:(r==null?void 0:r.url)??"about:blank",color:(r==null?void 0:r.color)??ZN(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return e(d=>({tabs:[...d.tabs,l],activeTabId:i})),eT(o),window.api.browser.create({viewId:o,partition:"persist:browser"}).then(()=>{r!=null&&r.url&&window.api.browser.navigate({viewId:o,url:r.url}).catch(()=>{})}).catch(d=>{var h,m;const u=d instanceof Error?d.message:String(d);(m=(h=window.api)==null?void 0:h.logs)==null||m.write("browser","error",`browser:create failed for viewId ${o}: ${u}`)}),i},closeTab:r=>{const i=n().tabs.find(o=>o.id===r);i&&(tT(i.viewId),Tv(i.viewId),window.api.browser.destroy(i.viewId).catch(()=>{}),e(o=>{const l=o.tabs.filter(u=>u.id!==r),d=o.activeTabId===r?l.length?l[l.length-1].id:null:o.activeTabId;return{tabs:l,activeTabId:d}}))},setActive:r=>{e({activeTabId:r})},navigate:(r,i)=>{const o=n().tabs.find(l=>l.id===r);o&&window.api.browser.navigate({viewId:o.viewId,url:i}).catch(()=>{})},back:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.back(i.viewId).catch(()=>{})},forward:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.forward(i.viewId).catch(()=>{})},reload:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.reload(i.viewId).catch(()=>{})},stop:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.stop(i.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:r=>e(i=>({mode:r,captured:r==="capture"?i.captured:null})),setCaptureMode:r=>e({captureMode:r,captured:null}),onVerb:r=>{const{mode:i}=n();if(r==="shot"){e({mode:"capture",captureMode:"shot",captured:null});return}if(i===r){e({mode:"browse",captured:r==="capture"?null:n().captured});return}e({mode:r,captureMode:r==="capture"?"agent":n().captureMode,captured:r==="capture"?n().captured:null})},captured:null,capture:async r=>{const{activeTabId:i,tabs:o,captureMode:l}=n(),d=o.find(h=>h.id===i);if(!d)throw new Error("No active browser tab");if(l==="shot"){const h=await window.api.browser.captureShot(d.viewId);if(!h.ok)throw new Error(h.error);e({captured:{mode:l,url:h.url,title:h.title,dataUrl:h.dataUrl,at:Date.now()}});return}if(!r||!r.length)throw new Error("No element selected");const u=await window.api.browser.capture({viewId:d.viewId,selectors:r,mode:l});if(!u.ok)throw new Error(u.error);e({captured:{mode:l,url:d.url,title:d.title,text:u.text,meta:u.meta,selectors:r,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:r=>{if(n().recorderActive)return;e({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(r).catch(()=>{}),x_(r);const i=window.api.browser.onRecordStep(r,o=>{Mt.getState().recording&&Mt.setState(l=>({recorderSteps:[...l.recorderSteps,o]}))});Lb.set(r,i),y_(),Kx=setInterval(()=>{Mt.getState().recording&&Mt.setState(o=>({recorderElapsedSec:o.recorderElapsedSec+1}))},1e3)},stopRecording:r=>{n().recorderActive&&(window.api.browser.recordStop(r).catch(()=>{}),x_(r),y_(),e({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{n().recorderActive&&e(r=>({recording:!r.recording}))},toggleStepVariable:r=>{e(i=>({recorderSteps:i.recorderSteps.map(o=>o.n===r?{...o,variable:o.variable?null:o.variableSuggestion||"value"}:o)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!n().bookmarksHydrated)try{const r=await window.api.config.readJson(f_),i=r.exists&&Array.isArray(r.data)?r.data:[];e({bookmarks:i,bookmarksHydrated:!0})}catch{e({bookmarksHydrated:!0})}},toggleBookmark:r=>{const i=n().tabs.find(u=>u.id===r);if(!i||!i.url||i.url==="about:blank")return;const o=n().bookmarks,d=o.some(u=>u.url===i.url)?o.filter(u=>u.url!==i.url):[{url:i.url,title:i.title,ts:Date.now()},...o];e({bookmarks:d}),window.api.config.writeJson(f_,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const r=await window.api.config.readJson(YN),i=r.exists&&Array.isArray(r.data)?r.data:[];e({historyEntries:i})}catch{}},setZoom:(r,i)=>{const o=n().tabs.find(d=>d.id===r);if(!o)return;const l=Math.min(QN,Math.max(JN,i));e(d=>({tabs:d.tabs.map(u=>u.id===r?{...u,zoomFactor:l}:u)})),window.api.browser.setZoom({viewId:o.viewId,factor:l}).catch(()=>{})},zoomIn:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor+p_)},zoomOut:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor-p_)},zoomReset:r=>n().setZoom(r,1),findOpen:!1,findText:"",findMatches:null,openFind:r=>{const i=n().tabs.find(l=>l.id===r);if(!i)return;e({findOpen:!0,findText:"",findMatches:null}),Tv(i.viewId);const o=window.api.browser.onFindResult(i.viewId,l=>{Mt.setState({findMatches:l})});zb.set(i.viewId,o)},closeFind:r=>{const i=n().tabs.find(o=>o.id===r);e({findOpen:!1,findText:"",findMatches:null}),i&&(Tv(i.viewId),window.api.browser.stopFind(i.viewId).catch(()=>{}))},setFindText:(r,i)=>{const o=n().tabs.find(l=>l.id===r);if(e({findText:i}),!!o){if(!i){window.api.browser.find({viewId:o.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:o.viewId,text:i,forward:!0}).catch(()=>{})}},findNext:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!0}).catch(()=>{})},findPrev:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!1}).catch(()=>{})}})),nT=4,v_=40,b_=6;function rT(e){const{onReorder:n,onActivate:r}=e,i=L.useRef(null),o=L.useRef(null),l=L.useRef(0),d=L.useRef(0),[u,h]=L.useState(!1),[,m]=L.useState(0),x=L.useRef(r);x.current=r;const g=L.useCallback(()=>i.current?Array.from(i.current.querySelectorAll("[data-drag-index]")):[],[]),v=L.useCallback((y,b,_)=>{for(let C=0;C<b.length;C++){const N=b[C].left+b[C].width/2;if(y<N)return C<=_?C:C-1}return b.length-1},[]),S=L.useCallback(()=>{const y=o.current,b=i.current;if(!(y!=null&&y.active)||!b)return;const _=b.getBoundingClientRect(),C=y.startX+y.deltaX,N=C-_.left,$=_.right-C;N<v_?b.scrollLeft-=b_:$<v_&&(b.scrollLeft+=b_),l.current=requestAnimationFrame(S)},[]);L.useEffect(()=>{const y=i.current;if(!y)return;let b=!1;const _=()=>{b||(b=!0,d.current=requestAnimationFrame(()=>{b=!1,m($=>$+1)}))},C=$=>{var U;const R=o.current;if(!R)return;const O=$.clientX-R.startX;if(!R.active&&Math.abs(O)<nT)return;if(!R.active){R.active=!0,R.tabRects=g().map(W=>W.getBoundingClientRect()),h(!0);try{(U=i.current)==null||U.setPointerCapture(R.pointerId)}catch{}l.current=requestAnimationFrame(S)}R.deltaX=O;const I=R.tabRects[R.fromIndex],z=I.left+I.width/2+O;R.currentIndex=v(z,R.tabRects,R.fromIndex),_()},N=$=>{const R=o.current;if(R&&R.pointerId===$.pointerId){cancelAnimationFrame(l.current),cancelAnimationFrame(d.current);try{y.releasePointerCapture(R.pointerId)}catch{}R.active&&R.fromIndex!==R.currentIndex?n(R.fromIndex,R.currentIndex):x.current(R.fromIndex),o.current=null,h(!1),m(O=>O+1)}};return y.addEventListener("pointermove",C),y.addEventListener("pointerup",N),y.addEventListener("pointercancel",N),()=>{y.removeEventListener("pointermove",C),y.removeEventListener("pointerup",N),y.removeEventListener("pointercancel",N),cancelAnimationFrame(l.current),cancelAnimationFrame(d.current)}},[n,g,v,S]);const E=L.useCallback((y,b)=>{y.button!==0||y.target.closest("button")||(o.current={active:!1,fromIndex:b,currentIndex:b,startX:y.clientX,deltaX:0,tabRects:[],pointerId:y.pointerId})},[]);return{getTabDragProps:L.useCallback(y=>{var C;const b=o.current,_={};if(b!=null&&b.active)if(y===b.fromIndex)_.transform=`translateX(${b.deltaX}px) scale(1.03)`,_.zIndex=10,_.opacity=.85,_.boxShadow="0 2px 8px rgba(0,0,0,0.4)",_.position="relative",_.pointerEvents="none";else{const N=b.fromIndex,$=b.currentIndex,O=(((C=b.tabRects[N])==null?void 0:C.width)??0)+4;_.transition="transform 0.15s ease",N<$&&y>N&&y<=$?_.transform=`translateX(-${O}px)`:N>$&&y>=$&&y<N?_.transform=`translateX(${O}px)`:_.transform="translateX(0)"}return{onPointerDown:N=>E(N,y),style:_,"data-drag-index":y}},[E]),isDragging:u,containerRef:i}}const sT=3e4;function iT({onToggleSplitView:e,splitViewActive:n}={}){const r=vt(b=>b.tabs),i=vt(b=>b.activeTabId),o=vt(b=>b.closeTab),l=vt(b=>b.setActive),d=vt(b=>b.reorderTab),u=Tm(b=>b.watchers),h=Mt(b=>b.tabs.length>0),m=i!=null&&h,[x,g]=L.useState(()=>Date.now());L.useEffect(()=>{const b=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(b)},[]);const v=b=>{for(const _ of Object.values(u))if(_.tabId===b&&_.lastLineAt&&x-_.lastLineAt<sT)return!0;return!1},{getTabDragProps:S,isDragging:E,containerRef:j}=rT({tabCount:r.length,onReorder:d,onActivate:b=>{const _=r[b];_&&l(_.id)}}),y=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return s.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[s.jsx("div",{ref:j,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${E?"cursor-grabbing":""}`,children:r.map((b,_)=>{const C=b.id===i,N=S(_),$=y[_%y.length];return s.jsxs("div",{...N,style:N.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${E?"":"cursor-grab"} ${C?"bg-bg text-fg font-medium relative z-10 -mb-px border border-b-0 border-line":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:b.cwd,"aria-current":C?"true":void 0,children:[s.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:$,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:b.status==="spawning"?.55:1}}),s.jsx("span",{className:"truncate max-w-[200px]",children:b.label}),b.status==="spawning"&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),v(b.id)&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),s.jsx("button",{onClick:R=>{R.stopPropagation(),o(b.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${b.label}`,children:"×"})]},b.id)})}),s.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[m&&e&&s.jsxs("button",{onClick:e,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${n?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":n??!1,children:[s.jsx("span",{"aria-hidden":"true",children:"⇄"}),s.jsx("span",{children:"Split view"})]}),s.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),s.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.38.3"]})]})]})}function oT(e,n,r){return n?e.map(i=>i.id===n?{...i,lastActivityAt:r}:i):e}function aT(e,n,r){return{tabId:e,sessionUuid:r,cwd:n,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const $m=cr((e,n)=>({tabs:{},refs:{},unsubs:{},subscribe:(r,i,o)=>{const l={...n().refs};if(l[r]=(l[r]??0)+1,e({refs:l}),l[r]>1)return;e({tabs:{...n().tabs,[r]:aT(r,i,o)}});const d=window.api.transcripts.onEvent(r,u=>n().ingest(r,u));e({unsubs:{...n().unsubs,[r]:d}}),window.api.transcripts.subscribe({tabId:r,cwd:i,sessionUuid:o}).then(async u=>{const h=n().tabs[r];if(!h)return;if(!u.ok){const{toast:x}=await Jm(async()=>{const{toast:g}=await Promise.resolve().then(()=>$2);return{toast:g}},void 0,import.meta.url);x.error(`Live view unavailable: ${u.error??"subscribe failed"}`),e({tabs:{...n().tabs,[r]:{...h,path:null}}});return}e({tabs:{...n().tabs,[r]:{...h,path:u.path}}});const m=await window.api.transcripts.buffer(r);for(const x of m)n().ingest(r,x,{replay:!0})}).catch(u=>console.error("[live] transcripts.subscribe failed:",r,u))},unsubscribe:r=>{const i={...n().refs};if(!i[r])return;if(i[r]--,i[r]>0){e({refs:i});return}delete i[r];const o=n().unsubs[r];o==null||o();const l={...n().unsubs};delete l[r];const d={...n().tabs};delete d[r],window.api.transcripts.unsubscribe(r),e({refs:i,unsubs:l,tabs:d})},ingest:(r,i,o)=>{const l=n().tabs[r];if(!l)return;const d=Date.now(),u={...l,lastEventAt:o!=null&&o.replay?l.lastEventAt:d},h=[],m=(x,g)=>x.length>g?x.slice(0,g-1)+"…":x;switch(i.kind){case"todo_write":{const x=Array.isArray(i.data)?i.data:[];u.todos=x,o!=null&&o.replay||h.push({id:0,kind:"todo-update",at:d,label:`Todos · ${x.length} item${x.length!==1?"s":""}`});break}case"tool_use":{const x=i.data,g=x.input,v={};for(const S of["command","file_path","pattern","url","query","subagent_type","description"])g&&S in g&&(v[S]=g[S]);if(u.lastToolUses=[{id:x.id,name:x.name,input:v,at:d},...l.lastToolUses].slice(0,50),!(o!=null&&o.replay)){const S=x.input,E=["Edit","Write","NotebookEdit"].includes(x.name),j=typeof(S==null?void 0:S.file_path)=="string"?S.file_path:void 0,y=typeof(S==null?void 0:S.command)=="string"?S.command:void 0,b=j?j.split("/").pop()??j:y?m(y,28):"";h.push({id:0,kind:"tool-use",at:d,label:b?`${x.name} · ${b}`:x.name,target:j??y,toolName:x.name}),E&&j&&h.push({id:0,kind:"file-edit",at:d,label:`${x.name} · ${m(j.split("/").pop()??j,34)}`,target:j,toolName:x.name})}break}case"plan":{const x=i.data,g=typeof x=="string"?x:(x==null?void 0:x.plan)??JSON.stringify(x);u.plans=[{at:d,content:g??""},...l.plans].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const x=i.data;u.agents=[{id:x==null?void 0:x.toolUseId,at:d,subagentType:x==null?void 0:x.subagent_type,description:x==null?void 0:x.description,lastActivityAt:d},...l.agents].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"agent-spawn",at:d,label:x!=null&&x.subagent_type?`Agent: ${m(x.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const x=i.data,g=(l.usage.inputTokens||0)+(l.usage.outputTokens||0),v=x.input_tokens??x.inputTokens??0,S=x.output_tokens??x.outputTokens??0,E=g+v+S;u.usage={inputTokens:(l.usage.inputTokens||0)+v,outputTokens:(l.usage.outputTokens||0)+S,cacheCreationInputTokens:(l.usage.cacheCreationInputTokens||0)+(x.cache_creation_input_tokens??x.cacheCreationInputTokens??0),cacheReadInputTokens:(l.usage.cacheReadInputTokens||0)+(x.cache_read_input_tokens??x.cacheReadInputTokens??0)},!(o!=null&&o.replay)&&Math.floor(E/1e3)>Math.floor(g/1e3)&&h.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(E/1e3)}k tokens`});break}case"tool_result":{const x=i.data;u.agents=oT(l.agents,x==null?void 0:x.toolUseId,d);break}}if(h.length>0){let x=l.activitySeq;const g=h.map(v=>({...v,id:++x}));u.activitySeq=x,u.activityRing=[...l.activityRing,...g].slice(-32)}e({tabs:{...n().tabs,[r]:u}})}}));function P2(e){const n=$m(o=>o.subscribe),r=$m(o=>o.unsubscribe),i=$m(o=>e?o.tabs[e.id]:void 0);return L.useEffect(()=>{if(e)return n(e.id,e.cwd,e.sessionId),()=>r(e.id)},[e==null?void 0:e.id,e==null?void 0:e.cwd,e==null?void 0:e.sessionId,n,r]),i}var $v={},Fp={},w_;function D2(){if(w_)return Fp;w_=1,Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.baseAssetPath=void 0;const n=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let r="/";return n&&(r=n.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Fp.baseAssetPath=r,Fp}var Up={},__;function Zw(){if(__)return Up;__=1,Object.defineProperty(Up,"__esModule",{value:!0}),Up.defaultModelFetcher=void 0;const e=n=>fetch(n).then(r=>r.arrayBuffer());return Up.defaultModelFetcher=e,Up}var tl={},Hp={},k_;function Qm(){if(k_)return Hp;k_=1,Object.defineProperty(Hp,"__esModule",{value:!0}),Hp.log=void 0;const e=n=>r=>{console.log(`VAD | ${n} >`,r)};return Hp.log={error:e("error"),debug:e("debug"),warn:e("warn")},Hp}var Wp={},S_;function Ky(){if(S_)return Wp;S_=1,Object.defineProperty(Wp,"__esModule",{value:!0}),Wp.Message=void 0;var e;return(function(n){n.AudioFrame="AUDIO_FRAME",n.SpeechStart="SPEECH_START",n.VADMisfire="VAD_MISFIRE",n.SpeechEnd="SPEECH_END",n.SpeechStop="SPEECH_STOP",n.SpeechRealStart="SPEECH_REAL_START",n.FrameProcessed="FRAME_PROCESSED"})(e||(Wp.Message=e={})),Wp}var C_;function e0(){if(C_)return tl;C_=1,Object.defineProperty(tl,"__esModule",{value:!0}),tl.FrameProcessor=tl.validateOptions=tl.defaultFrameProcessorOptions=void 0;const e=Qm(),n=Ky();tl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function r(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&e.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&e.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&e.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&e.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&e.log.error("minSpeechMs should be positive")}tl.validateOptions=r;const i=d=>{const u=d.reduce((m,x)=>(m.push(m.at(-1)+x.length),m),[0]),h=new Float32Array(u.at(-1));return d.forEach((m,x)=>{const g=u[x];h.set(m,g)}),h};function o(d,u){const h=Math.floor(d.redemptionMs/u),m=Math.floor(d.preSpeechPadMs/u),x=Math.floor(d.minSpeechMs/u);return{redemptionFrames:h,preSpeechPadFrames:m,minSpeechFrames:x}}class l{constructor(u,h,m,x){this.modelProcessFunc=u,this.modelResetFunc=h,this.options=m,this.msPerFrame=x,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=E=>{this.options={...this.options,...E};const{redemptionFrames:j,preSpeechPadFrames:y,minSpeechFrames:b}=o(this.options,this.msPerFrame);this.redemptionFrames=j,this.preSpeechPadFrames=y,this.minSpeechFrames=b},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=E=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(E):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=E=>{const j=this.audioBuffer;this.audioBuffer=[];const y=this.speaking;if(this.reset(),y)if(j.reduce((_,C)=>C.isSpeech?_+1:_,0)>=this.minSpeechFrames){const _=i(j.map(C=>C.frame));E({msg:n.Message.SpeechEnd,audio:_})}else E({msg:n.Message.VADMisfire});return{}},this.process=async(E,j)=>{if(!this.active)return;const y=await this.modelProcessFunc(E),b=y.isSpeech>=this.options.positiveSpeechThreshold;if(j({probs:y,msg:n.Message.FrameProcessed,frame:E}),this.audioBuffer.push({frame:E,isSpeech:b}),b&&(this.speechFrameCount++,this.redemptionCounter=0),b&&!this.speaking&&(this.speaking=!0,j({msg:n.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,j({msg:n.Message.SpeechRealStart})),y.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const _=this.audioBuffer;if(this.audioBuffer=[],_.reduce((N,$)=>$.isSpeech?N+1:N,0)>=this.minSpeechFrames){const N=i(_.map($=>$.frame));j({msg:n.Message.SpeechEnd,audio:N})}else j({msg:n.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:g,preSpeechPadFrames:v,minSpeechFrames:S}=o(this.options,this.msPerFrame);this.redemptionFrames=g,this.preSpeechPadFrames=v,this.minSpeechFrames=S,this.reset()}}return tl.FrameProcessor=l,tl}var nl={};function oo(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Av={exports:{}};/*!
|
|
43
|
+
`),questions:n,at:Date.now()})}),window.api.chat.onError(({tabId:e,sessionId:n,message:r})=>{M2(e,n,r)}),window.api.chat.onNotice(({tabId:e,sessionId:n,message:r})=>{Qw(e,n,r)}),window.api.chat.onExternalSend(({tabId:e,prompt:n})=>{var i,o;const r=vt.getState().tabs.find(l=>l.id===e);if(!r){(o=(i=window.api)==null?void 0:i.logs)==null||o.write("chat","warn",`external send ignored: tab ${e} is not open`);return}Gs.getState().send({tabId:e,sessionId:r.sessionId,cwd:r.cwd,prompt:n})}));function VN(e){const n=e.split("/").filter(Boolean);return n[n.length-1]||e}async function I2(e,n=!1,r=N2()){let i=!n;i&&(i=await T2(e.cwd,e.sessionId));const o=n&&!i?crypto.randomUUID():e.sessionId,l=i?`claude --dangerously-skip-permissions --resume ${Ho(o)} --model ${r}`:`claude --dangerously-skip-permissions --session-id ${Ho(o)} --model ${r}`;return{sessionId:o,startupCommand:l}}const vt=cr((e,n)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(r,i)=>{e(o=>({pendingRawCommand:{...o.pendingRawCommand,[r]:i}}))},consumeRawCommand:r=>{const i=n().pendingRawCommand[r];return i===void 0?null:(e(o=>{const l={...o.pendingRawCommand};return delete l[r],{pendingRawCommand:l}}),i)},addTab:({id:r,cwd:i,startupCommand:o,presetId:l=null,label:d})=>{const u=r??crypto.randomUUID();if(n().tabs.find(x=>x.id===u))return e({activeTabId:u}),u;const m={id:u,sessionId:u,label:d??VN(i),cwd:i,pid:null,status:"spawning",exitCode:null,startupCommand:o,presetId:l,generation:0};return e({tabs:[...n().tabs,m],activeTabId:u}),u},setTabRunning:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:i,status:"running"}:o)}),setTabExited:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,status:"exited",exitCode:i}:o)}),closeTab:r=>{var l;window.api.pty.kill(r),window.api.watchers.killTab(r).catch(()=>{}),window.api.transcripts.closeTab(r).catch(()=>{});const i=n().tabs.filter(d=>d.id!==r),o=n().activeTabId===r?((l=i[i.length-1])==null?void 0:l.id)??null:n().activeTabId;e({tabs:i,activeTabId:o})},setActive:r=>e({activeTabId:r}),restartTab:r=>{const i=n().tabs.find(d=>d.id===r);if(!i)return;window.api.pty.kill(r);const o=crypto.randomUUID(),l=d=>{e({tabs:n().tabs.map(u=>u.id===r?{...u,sessionId:o,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:u.generation+1}:u)})};i.presetId?C2(i.presetId).then(d=>{l(d?j2(d,{sessionId:o,cwd:i.cwd}):`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)}):l(`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)},reorderTab:(r,i)=>{const o=[...n().tabs];if(r<0||r>=o.length||i<0||i>=o.length||r===i)return;const[l]=o.splice(r,1);o.splice(i,0,l),e({tabs:o})},restoreTabs:(r,i)=>e({tabs:r,activeTabId:i,hydrated:!0}),wakeTab:async(r,i)=>{var u;const o=n().tabs.find(h=>h.id===r);if(!o||o.status!=="dormant")return;(u=Gs.getState().chats[r])!=null&&u.running&&(await window.api.chat.cancel(r),Le.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:l,startupCommand:d}=await I2({cwd:o.cwd,sessionId:o.sessionId},!1,i??N2());e({tabs:n().tabs.map(h=>h.id===r?{...h,sessionId:l,status:"spawning",startupCommand:d,generation:h.generation+1}:h)})},sleepTab:r=>{const i=n().tabs.find(o=>o.id===r);!i||i.status==="dormant"||(window.api.pty.kill(r),e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:null,status:"dormant"}:o)}))},newSession:r=>{n().tabs.find(o=>o.id===r)&&e({tabs:n().tabs.map(o=>o.id===r?{...o,sessionId:crypto.randomUUID()}:o)})}}));async function Ob(){var r;if(vt.getState().hydrated)return;try{const{tabs:i,activeTabId:o,freshStart:l}=await window.api.sessions.load();if(i.length>0){const u=(await Promise.all(i.map(async m=>{try{const{sessionId:x}=await I2(m,l);return{id:m.id,sessionId:x,cwd:m.cwd,label:m.label,presetId:m.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(x){return console.warn("[sessions] dropping malformed persisted tab:",m==null?void 0:m.id,x),null}}))).filter(m=>m!==null),h=o&&u.find(m=>m.id===o)?o:((r=u[0])==null?void 0:r.id)??null;vt.getState().restoreTabs(u,h)}else vt.setState({hydrated:!0})}catch(i){console.warn("[sessions] hydrate failed:",i),vt.setState({hydrated:!0})}const e=()=>{const{tabs:i,activeTabId:o}=vt.getState(),l=i.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:l,activeTabId:o}).catch(d=>{console.warn("[sessions] save failed:",d)})};let n=null;vt.subscribe((i,o)=>{i.hydrated&&(i.tabs===o.tabs&&i.activeTabId===o.activeTabId||(n!==null&&window.clearTimeout(n),n=window.setTimeout(e,200)))}),e()}const GN=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:Ob,useSessions:vt},Symbol.toStringTag,{value:"Module"})),h_=200,KN=/\x1b\[[0-9;]*m/g;function XN(e){return e.replace(KN,"")}const Tm=cr((e,n)=>({watchers:{},initialized:!1,init:()=>{n().initialized||(e({initialized:!0}),window.api.watchers.onLine(r=>n().ingestLine(r)),window.api.watchers.onClosed(({watcherId:r})=>n().closed(r)))},add:async({tabId:r,label:i,command:o,cwd:l})=>{try{const d=await window.api.watchers.add({tabId:r,label:i,command:o,cwd:l??null}),u={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return e({watchers:{...n().watchers,[u.watcherId]:u}}),u}catch(d){return console.error("[watchers] add failed:",d),Le.error("Failed to add watcher"),null}},remove:async r=>{try{await window.api.watchers.remove(r)}catch(o){console.error("[watchers] remove failed:",o);const l=o instanceof Error?o.message:String(o);Le.error(`Could not remove watcher: ${l}`)}const i={...n().watchers};delete i[r],e({watchers:i})},watchersForTab:r=>Object.values(n().watchers).filter(i=>i.tabId===r),ingestLine:r=>{const i=n().watchers[r.watcherId];if(!i)return;const o=XN(r.line),l=i.lines.length>=h_?[...i.lines.slice(i.lines.length-h_+1),{line:o,ts:r.ts}]:[...i.lines,{line:o,ts:r.ts}];e({watchers:{...n().watchers,[r.watcherId]:{...i,lines:l,lineCount:i.lineCount+1,lastLineAt:r.ts}}})},closed:r=>{if(!n().watchers[r])return;const i={...n().watchers};delete i[r],e({watchers:i})}})),YN="~/.claude/session-manager/browser/history.json",f_="~/.claude/session-manager/browser/bookmarks.json",JN=.25,QN=3,p_=.1,m_=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let g_=0;function ZN(){const e=m_[g_%m_.length];return g_+=1,e}const hy=new Map;function eT(e){if(hy.has(e))return;const n=window.api.browser.onNavState(e,r=>{Mt.setState(i=>({tabs:i.tabs.map(o=>o.viewId===e?{...o,url:r.url,title:r.title||o.title,canGoBack:r.canGoBack,canGoForward:r.canGoForward,loading:r.loading,isSecure:r.isSecure}:o)}))});hy.set(e,n)}function tT(e){const n=hy.get(e);n&&(n(),hy.delete(e))}const Lb=new Map;let Kx=null;function x_(e){const n=Lb.get(e);n&&(n(),Lb.delete(e))}function y_(){Kx&&(clearInterval(Kx),Kx=null)}const zb=new Map;function Tv(e){const n=zb.get(e);n&&(n(),zb.delete(e))}const Mt=cr((e,n)=>({tabs:[],activeTabId:null,openTab:r=>{const i=crypto.randomUUID(),o=i,l={id:i,viewId:o,title:"New Tab",url:(r==null?void 0:r.url)??"about:blank",color:(r==null?void 0:r.color)??ZN(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return e(d=>({tabs:[...d.tabs,l],activeTabId:i})),eT(o),window.api.browser.create({viewId:o,partition:"persist:browser"}).then(()=>{r!=null&&r.url&&window.api.browser.navigate({viewId:o,url:r.url}).catch(()=>{})}).catch(d=>{var h,m;const u=d instanceof Error?d.message:String(d);(m=(h=window.api)==null?void 0:h.logs)==null||m.write("browser","error",`browser:create failed for viewId ${o}: ${u}`)}),i},closeTab:r=>{const i=n().tabs.find(o=>o.id===r);i&&(tT(i.viewId),Tv(i.viewId),window.api.browser.destroy(i.viewId).catch(()=>{}),e(o=>{const l=o.tabs.filter(u=>u.id!==r),d=o.activeTabId===r?l.length?l[l.length-1].id:null:o.activeTabId;return{tabs:l,activeTabId:d}}))},setActive:r=>{e({activeTabId:r})},navigate:(r,i)=>{const o=n().tabs.find(l=>l.id===r);o&&window.api.browser.navigate({viewId:o.viewId,url:i}).catch(()=>{})},back:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.back(i.viewId).catch(()=>{})},forward:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.forward(i.viewId).catch(()=>{})},reload:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.reload(i.viewId).catch(()=>{})},stop:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.stop(i.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:r=>e(i=>({mode:r,captured:r==="capture"?i.captured:null})),setCaptureMode:r=>e({captureMode:r,captured:null}),onVerb:r=>{const{mode:i}=n();if(r==="shot"){e({mode:"capture",captureMode:"shot",captured:null});return}if(i===r){e({mode:"browse",captured:r==="capture"?null:n().captured});return}e({mode:r,captureMode:r==="capture"?"agent":n().captureMode,captured:r==="capture"?n().captured:null})},captured:null,capture:async r=>{const{activeTabId:i,tabs:o,captureMode:l}=n(),d=o.find(h=>h.id===i);if(!d)throw new Error("No active browser tab");if(l==="shot"){const h=await window.api.browser.captureShot(d.viewId);if(!h.ok)throw new Error(h.error);e({captured:{mode:l,url:h.url,title:h.title,dataUrl:h.dataUrl,at:Date.now()}});return}if(!r||!r.length)throw new Error("No element selected");const u=await window.api.browser.capture({viewId:d.viewId,selectors:r,mode:l});if(!u.ok)throw new Error(u.error);e({captured:{mode:l,url:d.url,title:d.title,text:u.text,meta:u.meta,selectors:r,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:r=>{if(n().recorderActive)return;e({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(r).catch(()=>{}),x_(r);const i=window.api.browser.onRecordStep(r,o=>{Mt.getState().recording&&Mt.setState(l=>({recorderSteps:[...l.recorderSteps,o]}))});Lb.set(r,i),y_(),Kx=setInterval(()=>{Mt.getState().recording&&Mt.setState(o=>({recorderElapsedSec:o.recorderElapsedSec+1}))},1e3)},stopRecording:r=>{n().recorderActive&&(window.api.browser.recordStop(r).catch(()=>{}),x_(r),y_(),e({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{n().recorderActive&&e(r=>({recording:!r.recording}))},toggleStepVariable:r=>{e(i=>({recorderSteps:i.recorderSteps.map(o=>o.n===r?{...o,variable:o.variable?null:o.variableSuggestion||"value"}:o)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!n().bookmarksHydrated)try{const r=await window.api.config.readJson(f_),i=r.exists&&Array.isArray(r.data)?r.data:[];e({bookmarks:i,bookmarksHydrated:!0})}catch{e({bookmarksHydrated:!0})}},toggleBookmark:r=>{const i=n().tabs.find(u=>u.id===r);if(!i||!i.url||i.url==="about:blank")return;const o=n().bookmarks,d=o.some(u=>u.url===i.url)?o.filter(u=>u.url!==i.url):[{url:i.url,title:i.title,ts:Date.now()},...o];e({bookmarks:d}),window.api.config.writeJson(f_,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const r=await window.api.config.readJson(YN),i=r.exists&&Array.isArray(r.data)?r.data:[];e({historyEntries:i})}catch{}},setZoom:(r,i)=>{const o=n().tabs.find(d=>d.id===r);if(!o)return;const l=Math.min(QN,Math.max(JN,i));e(d=>({tabs:d.tabs.map(u=>u.id===r?{...u,zoomFactor:l}:u)})),window.api.browser.setZoom({viewId:o.viewId,factor:l}).catch(()=>{})},zoomIn:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor+p_)},zoomOut:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor-p_)},zoomReset:r=>n().setZoom(r,1),findOpen:!1,findText:"",findMatches:null,openFind:r=>{const i=n().tabs.find(l=>l.id===r);if(!i)return;e({findOpen:!0,findText:"",findMatches:null}),Tv(i.viewId);const o=window.api.browser.onFindResult(i.viewId,l=>{Mt.setState({findMatches:l})});zb.set(i.viewId,o)},closeFind:r=>{const i=n().tabs.find(o=>o.id===r);e({findOpen:!1,findText:"",findMatches:null}),i&&(Tv(i.viewId),window.api.browser.stopFind(i.viewId).catch(()=>{}))},setFindText:(r,i)=>{const o=n().tabs.find(l=>l.id===r);if(e({findText:i}),!!o){if(!i){window.api.browser.find({viewId:o.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:o.viewId,text:i,forward:!0}).catch(()=>{})}},findNext:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!0}).catch(()=>{})},findPrev:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!1}).catch(()=>{})}})),nT=4,v_=40,b_=6;function rT(e){const{onReorder:n,onActivate:r}=e,i=L.useRef(null),o=L.useRef(null),l=L.useRef(0),d=L.useRef(0),[u,h]=L.useState(!1),[,m]=L.useState(0),x=L.useRef(r);x.current=r;const g=L.useCallback(()=>i.current?Array.from(i.current.querySelectorAll("[data-drag-index]")):[],[]),v=L.useCallback((y,b,_)=>{for(let C=0;C<b.length;C++){const N=b[C].left+b[C].width/2;if(y<N)return C<=_?C:C-1}return b.length-1},[]),S=L.useCallback(()=>{const y=o.current,b=i.current;if(!(y!=null&&y.active)||!b)return;const _=b.getBoundingClientRect(),C=y.startX+y.deltaX,N=C-_.left,$=_.right-C;N<v_?b.scrollLeft-=b_:$<v_&&(b.scrollLeft+=b_),l.current=requestAnimationFrame(S)},[]);L.useEffect(()=>{const y=i.current;if(!y)return;let b=!1;const _=()=>{b||(b=!0,d.current=requestAnimationFrame(()=>{b=!1,m($=>$+1)}))},C=$=>{var U;const R=o.current;if(!R)return;const O=$.clientX-R.startX;if(!R.active&&Math.abs(O)<nT)return;if(!R.active){R.active=!0,R.tabRects=g().map(W=>W.getBoundingClientRect()),h(!0);try{(U=i.current)==null||U.setPointerCapture(R.pointerId)}catch{}l.current=requestAnimationFrame(S)}R.deltaX=O;const I=R.tabRects[R.fromIndex],z=I.left+I.width/2+O;R.currentIndex=v(z,R.tabRects,R.fromIndex),_()},N=$=>{const R=o.current;if(R&&R.pointerId===$.pointerId){cancelAnimationFrame(l.current),cancelAnimationFrame(d.current);try{y.releasePointerCapture(R.pointerId)}catch{}R.active&&R.fromIndex!==R.currentIndex?n(R.fromIndex,R.currentIndex):x.current(R.fromIndex),o.current=null,h(!1),m(O=>O+1)}};return y.addEventListener("pointermove",C),y.addEventListener("pointerup",N),y.addEventListener("pointercancel",N),()=>{y.removeEventListener("pointermove",C),y.removeEventListener("pointerup",N),y.removeEventListener("pointercancel",N),cancelAnimationFrame(l.current),cancelAnimationFrame(d.current)}},[n,g,v,S]);const E=L.useCallback((y,b)=>{y.button!==0||y.target.closest("button")||(o.current={active:!1,fromIndex:b,currentIndex:b,startX:y.clientX,deltaX:0,tabRects:[],pointerId:y.pointerId})},[]);return{getTabDragProps:L.useCallback(y=>{var C;const b=o.current,_={};if(b!=null&&b.active)if(y===b.fromIndex)_.transform=`translateX(${b.deltaX}px) scale(1.03)`,_.zIndex=10,_.opacity=.85,_.boxShadow="0 2px 8px rgba(0,0,0,0.4)",_.position="relative",_.pointerEvents="none";else{const N=b.fromIndex,$=b.currentIndex,O=(((C=b.tabRects[N])==null?void 0:C.width)??0)+4;_.transition="transform 0.15s ease",N<$&&y>N&&y<=$?_.transform=`translateX(-${O}px)`:N>$&&y>=$&&y<N?_.transform=`translateX(${O}px)`:_.transform="translateX(0)"}return{onPointerDown:N=>E(N,y),style:_,"data-drag-index":y}},[E]),isDragging:u,containerRef:i}}const sT=3e4;function iT({onToggleSplitView:e,splitViewActive:n}={}){const r=vt(b=>b.tabs),i=vt(b=>b.activeTabId),o=vt(b=>b.closeTab),l=vt(b=>b.setActive),d=vt(b=>b.reorderTab),u=Tm(b=>b.watchers),h=Mt(b=>b.tabs.length>0),m=i!=null&&h,[x,g]=L.useState(()=>Date.now());L.useEffect(()=>{const b=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(b)},[]);const v=b=>{for(const _ of Object.values(u))if(_.tabId===b&&_.lastLineAt&&x-_.lastLineAt<sT)return!0;return!1},{getTabDragProps:S,isDragging:E,containerRef:j}=rT({tabCount:r.length,onReorder:d,onActivate:b=>{const _=r[b];_&&l(_.id)}}),y=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return s.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[s.jsx("div",{ref:j,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${E?"cursor-grabbing":""}`,children:r.map((b,_)=>{const C=b.id===i,N=S(_),$=y[_%y.length];return s.jsxs("div",{...N,style:N.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${E?"":"cursor-grab"} ${C?"bg-bg text-fg font-medium relative z-10 -mb-px border border-b-0 border-line":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:b.cwd,"aria-current":C?"true":void 0,children:[s.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:$,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:b.status==="spawning"?.55:1}}),s.jsx("span",{className:"truncate max-w-[200px]",children:b.label}),b.status==="spawning"&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),v(b.id)&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),s.jsx("button",{onClick:R=>{R.stopPropagation(),o(b.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${b.label}`,children:"×"})]},b.id)})}),s.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[m&&e&&s.jsxs("button",{onClick:e,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${n?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":n??!1,children:[s.jsx("span",{"aria-hidden":"true",children:"⇄"}),s.jsx("span",{children:"Split view"})]}),s.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),s.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.38.4"]})]})]})}function oT(e,n,r){return n?e.map(i=>i.id===n?{...i,lastActivityAt:r}:i):e}function aT(e,n,r){return{tabId:e,sessionUuid:r,cwd:n,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const $m=cr((e,n)=>({tabs:{},refs:{},unsubs:{},subscribe:(r,i,o)=>{const l={...n().refs};if(l[r]=(l[r]??0)+1,e({refs:l}),l[r]>1)return;e({tabs:{...n().tabs,[r]:aT(r,i,o)}});const d=window.api.transcripts.onEvent(r,u=>n().ingest(r,u));e({unsubs:{...n().unsubs,[r]:d}}),window.api.transcripts.subscribe({tabId:r,cwd:i,sessionUuid:o}).then(async u=>{const h=n().tabs[r];if(!h)return;if(!u.ok){const{toast:x}=await Jm(async()=>{const{toast:g}=await Promise.resolve().then(()=>$2);return{toast:g}},void 0,import.meta.url);x.error(`Live view unavailable: ${u.error??"subscribe failed"}`),e({tabs:{...n().tabs,[r]:{...h,path:null}}});return}e({tabs:{...n().tabs,[r]:{...h,path:u.path}}});const m=await window.api.transcripts.buffer(r);for(const x of m)n().ingest(r,x,{replay:!0})}).catch(u=>console.error("[live] transcripts.subscribe failed:",r,u))},unsubscribe:r=>{const i={...n().refs};if(!i[r])return;if(i[r]--,i[r]>0){e({refs:i});return}delete i[r];const o=n().unsubs[r];o==null||o();const l={...n().unsubs};delete l[r];const d={...n().tabs};delete d[r],window.api.transcripts.unsubscribe(r),e({refs:i,unsubs:l,tabs:d})},ingest:(r,i,o)=>{const l=n().tabs[r];if(!l)return;const d=Date.now(),u={...l,lastEventAt:o!=null&&o.replay?l.lastEventAt:d},h=[],m=(x,g)=>x.length>g?x.slice(0,g-1)+"…":x;switch(i.kind){case"todo_write":{const x=Array.isArray(i.data)?i.data:[];u.todos=x,o!=null&&o.replay||h.push({id:0,kind:"todo-update",at:d,label:`Todos · ${x.length} item${x.length!==1?"s":""}`});break}case"tool_use":{const x=i.data,g=x.input,v={};for(const S of["command","file_path","pattern","url","query","subagent_type","description"])g&&S in g&&(v[S]=g[S]);if(u.lastToolUses=[{id:x.id,name:x.name,input:v,at:d},...l.lastToolUses].slice(0,50),!(o!=null&&o.replay)){const S=x.input,E=["Edit","Write","NotebookEdit"].includes(x.name),j=typeof(S==null?void 0:S.file_path)=="string"?S.file_path:void 0,y=typeof(S==null?void 0:S.command)=="string"?S.command:void 0,b=j?j.split("/").pop()??j:y?m(y,28):"";h.push({id:0,kind:"tool-use",at:d,label:b?`${x.name} · ${b}`:x.name,target:j??y,toolName:x.name}),E&&j&&h.push({id:0,kind:"file-edit",at:d,label:`${x.name} · ${m(j.split("/").pop()??j,34)}`,target:j,toolName:x.name})}break}case"plan":{const x=i.data,g=typeof x=="string"?x:(x==null?void 0:x.plan)??JSON.stringify(x);u.plans=[{at:d,content:g??""},...l.plans].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const x=i.data;u.agents=[{id:x==null?void 0:x.toolUseId,at:d,subagentType:x==null?void 0:x.subagent_type,description:x==null?void 0:x.description,lastActivityAt:d},...l.agents].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"agent-spawn",at:d,label:x!=null&&x.subagent_type?`Agent: ${m(x.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const x=i.data,g=(l.usage.inputTokens||0)+(l.usage.outputTokens||0),v=x.input_tokens??x.inputTokens??0,S=x.output_tokens??x.outputTokens??0,E=g+v+S;u.usage={inputTokens:(l.usage.inputTokens||0)+v,outputTokens:(l.usage.outputTokens||0)+S,cacheCreationInputTokens:(l.usage.cacheCreationInputTokens||0)+(x.cache_creation_input_tokens??x.cacheCreationInputTokens??0),cacheReadInputTokens:(l.usage.cacheReadInputTokens||0)+(x.cache_read_input_tokens??x.cacheReadInputTokens??0)},!(o!=null&&o.replay)&&Math.floor(E/1e3)>Math.floor(g/1e3)&&h.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(E/1e3)}k tokens`});break}case"tool_result":{const x=i.data;u.agents=oT(l.agents,x==null?void 0:x.toolUseId,d);break}}if(h.length>0){let x=l.activitySeq;const g=h.map(v=>({...v,id:++x}));u.activitySeq=x,u.activityRing=[...l.activityRing,...g].slice(-32)}e({tabs:{...n().tabs,[r]:u}})}}));function P2(e){const n=$m(o=>o.subscribe),r=$m(o=>o.unsubscribe),i=$m(o=>e?o.tabs[e.id]:void 0);return L.useEffect(()=>{if(e)return n(e.id,e.cwd,e.sessionId),()=>r(e.id)},[e==null?void 0:e.id,e==null?void 0:e.cwd,e==null?void 0:e.sessionId,n,r]),i}var $v={},Fp={},w_;function D2(){if(w_)return Fp;w_=1,Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.baseAssetPath=void 0;const n=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let r="/";return n&&(r=n.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Fp.baseAssetPath=r,Fp}var Up={},__;function Zw(){if(__)return Up;__=1,Object.defineProperty(Up,"__esModule",{value:!0}),Up.defaultModelFetcher=void 0;const e=n=>fetch(n).then(r=>r.arrayBuffer());return Up.defaultModelFetcher=e,Up}var tl={},Hp={},k_;function Qm(){if(k_)return Hp;k_=1,Object.defineProperty(Hp,"__esModule",{value:!0}),Hp.log=void 0;const e=n=>r=>{console.log(`VAD | ${n} >`,r)};return Hp.log={error:e("error"),debug:e("debug"),warn:e("warn")},Hp}var Wp={},S_;function Ky(){if(S_)return Wp;S_=1,Object.defineProperty(Wp,"__esModule",{value:!0}),Wp.Message=void 0;var e;return(function(n){n.AudioFrame="AUDIO_FRAME",n.SpeechStart="SPEECH_START",n.VADMisfire="VAD_MISFIRE",n.SpeechEnd="SPEECH_END",n.SpeechStop="SPEECH_STOP",n.SpeechRealStart="SPEECH_REAL_START",n.FrameProcessed="FRAME_PROCESSED"})(e||(Wp.Message=e={})),Wp}var C_;function e0(){if(C_)return tl;C_=1,Object.defineProperty(tl,"__esModule",{value:!0}),tl.FrameProcessor=tl.validateOptions=tl.defaultFrameProcessorOptions=void 0;const e=Qm(),n=Ky();tl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function r(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&e.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&e.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&e.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&e.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&e.log.error("minSpeechMs should be positive")}tl.validateOptions=r;const i=d=>{const u=d.reduce((m,x)=>(m.push(m.at(-1)+x.length),m),[0]),h=new Float32Array(u.at(-1));return d.forEach((m,x)=>{const g=u[x];h.set(m,g)}),h};function o(d,u){const h=Math.floor(d.redemptionMs/u),m=Math.floor(d.preSpeechPadMs/u),x=Math.floor(d.minSpeechMs/u);return{redemptionFrames:h,preSpeechPadFrames:m,minSpeechFrames:x}}class l{constructor(u,h,m,x){this.modelProcessFunc=u,this.modelResetFunc=h,this.options=m,this.msPerFrame=x,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=E=>{this.options={...this.options,...E};const{redemptionFrames:j,preSpeechPadFrames:y,minSpeechFrames:b}=o(this.options,this.msPerFrame);this.redemptionFrames=j,this.preSpeechPadFrames=y,this.minSpeechFrames=b},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=E=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(E):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=E=>{const j=this.audioBuffer;this.audioBuffer=[];const y=this.speaking;if(this.reset(),y)if(j.reduce((_,C)=>C.isSpeech?_+1:_,0)>=this.minSpeechFrames){const _=i(j.map(C=>C.frame));E({msg:n.Message.SpeechEnd,audio:_})}else E({msg:n.Message.VADMisfire});return{}},this.process=async(E,j)=>{if(!this.active)return;const y=await this.modelProcessFunc(E),b=y.isSpeech>=this.options.positiveSpeechThreshold;if(j({probs:y,msg:n.Message.FrameProcessed,frame:E}),this.audioBuffer.push({frame:E,isSpeech:b}),b&&(this.speechFrameCount++,this.redemptionCounter=0),b&&!this.speaking&&(this.speaking=!0,j({msg:n.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,j({msg:n.Message.SpeechRealStart})),y.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const _=this.audioBuffer;if(this.audioBuffer=[],_.reduce((N,$)=>$.isSpeech?N+1:N,0)>=this.minSpeechFrames){const N=i(_.map($=>$.frame));j({msg:n.Message.SpeechEnd,audio:N})}else j({msg:n.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:g,preSpeechPadFrames:v,minSpeechFrames:S}=o(this.options,this.msPerFrame);this.redemptionFrames=g,this.preSpeechPadFrames=v,this.minSpeechFrames=S,this.reset()}}return tl.FrameProcessor=l,tl}var nl={};function oo(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Av={exports:{}};/*!
|
|
44
44
|
* ONNX Runtime Web v1.26.0
|
|
45
45
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
46
46
|
* Licensed under the MIT License.
|
|
@@ -2894,7 +2894,7 @@ ${P}`,B=w.createShaderModule({code:D,label:a.name});on("verbose",()=>`[WebGPU] $
|
|
|
2894
2894
|
* ONNX Runtime Web v1.26.0
|
|
2895
2895
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2896
2896
|
* Licensed under the MIT License.
|
|
2897
|
-
*/var I_;function pT(){return I_||(I_=1,(function(e,n){var r=(()=>{var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,u=(re=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(re,{get:(fe,ve)=>(typeof oo<"u"?oo:fe)[ve]}):re)(function(re){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+re+'" is not supported')}),h=(re,fe)=>()=>(re&&(fe=re(re=0)),fe),m=(re,fe)=>{for(var ve in fe)i(re,ve,{get:fe[ve],enumerable:!0})},x=(re,fe,ve,Te)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ce of l(fe))!d.call(re,Ce)&&Ce!==ve&&i(re,Ce,{get:()=>fe[Ce],enumerable:!(Te=o(fe,Ce))||Te.enumerable});return re},g=re=>x(i({},"__esModule",{value:!0}),re),v,S,E,j,y,b=h(()=>{v=new Map,S=[],E=(re,fe,ve)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let Te=v.get(re);if(Te===void 0)v.set(re,{backend:fe,priority:ve});else{if(Te.priority>ve)return;if(Te.priority===ve&&Te.backend!==fe)throw new Error(`cannot register backend "${re}" using priority ${ve}`)}if(ve>=0){let Ce=S.indexOf(re);Ce!==-1&&S.splice(Ce,1);for(let Be=0;Be<S.length;Be++)if(v.get(S[Be]).priority<=ve){S.splice(Be,0,re);return}S.push(re)}return}throw new TypeError("not a valid backend")},j=async re=>{let fe=v.get(re);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let ve=!!fe.initPromise;try{return ve||(fe.initPromise=fe.backend.init(re)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(Te){return ve||(fe.error=`${Te}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},y=async re=>{let fe=re.executionProviders||[],ve=fe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),Te=ve.length===0?S:ve,Ce,Be=[],Re=new Set;for(let Fe of Te){let et=await j(Fe);typeof et=="string"?Be.push({name:Fe,err:et}):(Ce||(Ce=et),Ce===et&&Re.add(Fe))}if(!Ce)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:et}of Be)ve.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${et}`);let Me=fe.filter(Fe=>Re.has(typeof Fe=="string"?Fe:Fe.name));return[Ce,new Proxy(re,{get:(Fe,et)=>et==="executionProviders"?Me:Reflect.get(Fe,et)})]}}),_=h(()=>{b()}),C,N=h(()=>{C="1.26.0"}),$,R,O=h(()=>{N(),$="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(re){if(re!==void 0){if(typeof re!="string"||["verbose","info","warning","error","fatal"].indexOf(re)===-1)throw new Error(`Unsupported logging level: ${re}`);$=re}},get logLevel(){return $}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),I,z=h(()=>{O(),I=R}),U,W,Y=h(()=>{U=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ve.width=re.dims[3],ve.height=re.dims[2];let Te=ve.getContext("2d");if(Te!=null){let Ce,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2]);let Re=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Me=fe==null?void 0:fe.norm,Fe,et;Me===void 0||Me.mean===void 0?Fe=[255,255,255,255]:typeof Me.mean=="number"?Fe=[Me.mean,Me.mean,Me.mean,Me.mean]:(Fe=[Me.mean[0],Me.mean[1],Me.mean[2],0],Me.mean[3]!==void 0&&(Fe[3]=Me.mean[3])),Me===void 0||Me.bias===void 0?et=[0,0,0,0]:typeof Me.bias=="number"?et=[Me.bias,Me.bias,Me.bias,Me.bias]:(et=[Me.bias[0],Me.bias[1],Me.bias[2],0],Me.bias[3]!==void 0&&(et[3]=Me.bias[3]));let it=Be*Ce,tt=0,Xe=it,At=it*2,ze=-1;Re==="RGBA"?(tt=0,Xe=it,At=it*2,ze=it*3):Re==="RGB"?(tt=0,Xe=it,At=it*2):Re==="RBG"&&(tt=0,At=it,Xe=it*2);for(let ut=0;ut<Be;ut++)for(let Cn=0;Cn<Ce;Cn++){let Jt=(re.data[tt++]-et[0])*Fe[0],Qt=(re.data[Xe++]-et[1])*Fe[1],jn=(re.data[At++]-et[2])*Fe[2],Ot=ze===-1?255:(re.data[ze++]-et[3])*Fe[3];Te.fillStyle="rgba("+Jt+","+Qt+","+jn+","+Ot+")",Te.fillRect(Cn,ut,1,1)}if("toDataURL"in ve)return ve.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},W=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(ve!=null){let Ce,Be,Re;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[1],Re=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2],Re=re.dims[1]);let Me=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Fe=fe==null?void 0:fe.norm,et,it;Fe===void 0||Fe.mean===void 0?et=[255,255,255,255]:typeof Fe.mean=="number"?et=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(et=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(et[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?it=[0,0,0,0]:typeof Fe.bias=="number"?it=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(it=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(it[3]=Fe.bias[3]));let tt=Be*Ce;if(fe!==void 0&&(fe.format!==void 0&&Re===4&&fe.format!=="RGBA"||Re===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,At=0,ze=1,ut=2,Cn=3,Jt=0,Qt=tt,jn=tt*2,Ot=-1;Me==="RGBA"?(Jt=0,Qt=tt,jn=tt*2,Ot=tt*3):Me==="RGB"?(Jt=0,Qt=tt,jn=tt*2):Me==="RBG"&&(Jt=0,jn=tt,Qt=tt*2),Te=ve.createImageData(Ce,Be);for(let Mn=0;Mn<Be*Ce;At+=Xe,ze+=Xe,ut+=Xe,Cn+=Xe,Mn++)Te.data[At]=(re.data[Jt++]-it[0])*et[0],Te.data[ze]=(re.data[Qt++]-it[1])*et[1],Te.data[ut]=(re.data[jn++]-it[2])*et[2],Te.data[Cn]=Ot===-1?255:(re.data[Ot++]-it[3])*et[3]}else throw new Error("Can not access image data");return Te}}),V,H,te,ae,oe,ie,X=h(()=>{we(),V=(re,fe)=>{if(re===void 0)throw new Error("Image buffer must be defined");if(fe.height===void 0||fe.width===void 0)throw new Error("Image height and width must be defined");if(fe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ve,width:Te}=fe,Ce=fe.norm??{mean:255,bias:0},Be,Re;typeof Ce.mean=="number"?Be=[Ce.mean,Ce.mean,Ce.mean,Ce.mean]:Be=[Ce.mean[0],Ce.mean[1],Ce.mean[2],Ce.mean[3]??255],typeof Ce.bias=="number"?Re=[Ce.bias,Ce.bias,Ce.bias,Ce.bias]:Re=[Ce.bias[0],Ce.bias[1],Ce.bias[2],Ce.bias[3]??0];let Me=fe.format!==void 0?fe.format:"RGBA",Fe=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",et=ve*Te,it=Fe==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Xe=0,At=1,ze=2,ut=3,Cn=0,Jt=et,Qt=et*2,jn=-1;Me==="RGB"&&(tt=3,Xe=0,At=1,ze=2,ut=-1),Fe==="RGBA"?jn=et*3:Fe==="RBG"?(Cn=0,Qt=et,Jt=et*2):Fe==="BGR"&&(Qt=0,Jt=et,Cn=et*2);for(let Ot=0;Ot<et;Ot++,Xe+=tt,ze+=tt,At+=tt,ut+=tt)it[Cn++]=(re[Xe]+Re[0])/Be[0],it[Jt++]=(re[At]+Re[1])/Be[1],it[Qt++]=(re[ze]+Re[2])/Be[2],jn!==-1&&ut!==-1&&(it[jn++]=(re[ut]+Re[3])/Be[3]);return Fe==="RGBA"?new ne("float32",it,[1,4,ve,Te]):new ne("float32",it,[1,3,ve,Te])},H=async(re,fe)=>{let ve=typeof HTMLImageElement<"u"&&re instanceof HTMLImageElement,Te=typeof ImageData<"u"&&re instanceof ImageData,Ce=typeof ImageBitmap<"u"&&re instanceof ImageBitmap,Be=typeof re=="string",Re,Me=fe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},et=it=>typeof HTMLCanvasElement<"u"&&it instanceof HTMLCanvasElement||it instanceof OffscreenCanvas?it.getContext("2d"):null;if(ve){let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,At=fe.resizedWidth),fe!==void 0){if(Me=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At}else Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At;tt.drawImage(re,0,0),Re=tt.getImageData(0,0,At,Xe).data}else throw new Error("Can not access image data")}else if(Te){let it,tt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(it=fe.resizedHeight,tt=fe.resizedWidth):(it=re.height,tt=re.width),fe!==void 0&&(Me=fe),Me.format="RGBA",Me.height=it,Me.width=tt,fe!==void 0){let Xe=Fe();Xe.width=tt,Xe.height=it;let At=et(Xe);if(At!=null)At.putImageData(re,0,0),Re=At.getImageData(0,0,tt,it).data;else throw new Error("Can not access image data")}else Re=re.data}else if(Ce){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;return tt.drawImage(re,0,0,At,Xe),Re=tt.getImageData(0,0,At,Xe).data,Me.height=Xe,Me.width=At,V(Re,Me)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((it,tt)=>{let Xe=Fe(),At=et(Xe);if(!re||!At)return tt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=re,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,At.drawImage(ze,0,0,Xe.width,Xe.height);let ut=At.getImageData(0,0,Xe.width,Xe.height);Me.height=Xe.height,Me.width=Xe.width,it(V(ut.data,Me))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Re!==void 0)return V(Re,Me);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(re,fe)=>{let{width:ve,height:Te,download:Ce,dispose:Be}=fe,Re=[1,Te,ve,4];return new ne({location:"texture",type:"float32",texture:re,dims:Re,download:Ce,dispose:Be})},ae=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"gpu-buffer",type:ve??"float32",gpuBuffer:re,dims:Te,download:Ce,dispose:Be})},oe=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"ml-tensor",type:ve??"float32",mlTensor:re,dims:Te,download:Ce,dispose:Be})},ie=(re,fe,ve)=>new ne({location:"cpu-pinned",type:re,data:fe,dims:ve??[fe.length]})}),Q,J,le,ce,pe=h(()=>{Q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ce=()=>{if(!le){le=!0;let re=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,ve=globalThis.Float16Array,Te=typeof ve<"u"&&ve.from;re&&(Q.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),fe&&(Q.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),Te?(Q.set("float16",ve),J.set(ve,"float16")):Q.set("float16",Uint16Array)}}}),Ae,Se,ye=h(()=>{we(),Ae=re=>{let fe=1;for(let ve=0;ve<re.length;ve++){let Te=re[ve];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${ve}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${ve}] must be a non-negative integer, got: ${Te}`);fe*=Te}return fe},Se=(re,fe)=>{switch(re.location){case"cpu":return new ne(re.type,re.data,fe);case"cpu-pinned":return new ne({location:"cpu-pinned",data:re.data,type:re.type,dims:fe});case"texture":return new ne({location:"texture",texture:re.texture,type:re.type,dims:fe});case"gpu-buffer":return new ne({location:"gpu-buffer",gpuBuffer:re.gpuBuffer,type:re.type,dims:fe});case"ml-tensor":return new ne({location:"ml-tensor",mlTensor:re.mlTensor,type:re.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${re.location} is not supported`)}}}),ne,we=h(()=>{Y(),X(),pe(),ye(),ne=class{constructor(re,fe,ve){ce();let Te,Ce;if(typeof re=="object"&&"location"in re)switch(this.dataLocation=re.location,Te=re.type,Ce=re.dims,re.location){case"cpu-pinned":{let Re=Q.get(Te);if(!Re)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(re.data instanceof Re))throw new TypeError(`buffer should be of type ${Re.name}`);this.cpuData=re.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=re.texture,this.downloader=re.download,this.disposer=re.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=re.gpuBuffer,this.downloader=re.download,this.disposer=re.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=re.mlTensor,this.downloader=re.download,this.disposer=re.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Re,Me;if(typeof re=="string")if(Te=re,Me=ve,re==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");Re=fe}else{let Fe=Q.get(re);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${re}.`);if(Array.isArray(fe)){if(re==="float16"&&Fe===Uint16Array||re==="uint4"||re==="int4")throw new TypeError(`Creating a ${re} tensor from number array is not supported. Please use ${Fe.name} as data.`);re==="uint64"||re==="int64"?Re=Fe.from(fe,BigInt):Re=Fe.from(fe)}else if(fe instanceof Fe)Re=fe;else if(fe instanceof Uint8ClampedArray)if(re==="uint8")Re=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(re==="float16"&&fe instanceof Uint16Array&&Fe!==Uint16Array)Re=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Fe}`)}else if(Me=fe,Array.isArray(re)){if(re.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof re[0];if(Fe==="string")Te="string",Re=re;else if(Fe==="boolean")Te="bool",Re=Uint8Array.from(re);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(re instanceof Uint8ClampedArray)Te="uint8",Re=Uint8Array.from(re);else{let Fe=J.get(re.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${re.constructor}.`);Te=Fe,Re=re}if(Me===void 0)Me=[Re.length];else if(!Array.isArray(Me))throw new TypeError("A tensor's dims must be a number array");Ce=Me,this.cpuData=Re,this.dataLocation="cpu"}let Be=Ae(Ce);if(this.cpuData&&Be!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=Ce,this.size=Be}static async fromImage(re,fe){return H(re,fe)}static fromTexture(re,fe){return te(re,fe)}static fromGpuBuffer(re,fe){return ae(re,fe)}static fromMLTensor(re,fe){return oe(re,fe)}static fromPinnedBuffer(re,fe,ve){return ie(re,fe,ve)}toDataURL(re){return U(this,re)}toImageData(re){return W(this,re)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(re){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let fe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=fe,re&&this.disposer&&(this.disposer(),this.disposer=void 0),fe}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(re){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,re)}}}),Ne,Je=h(()=>{we(),Ne=ne}),lt,xt,Rt,He,bt,st,an=h(()=>{O(),lt=(re,fe)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${re}::ORT::${fe}`)},xt=(re,fe)=>{var Ce;let ve=((Ce=new Error().stack)==null?void 0:Ce.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Be=0;Be<ve.length;Be++){if(Te&&!ve[Be].includes("TRACE_FUNC")){let Re=`FUNC_${re}::${ve[Be].trim().split(" ")[1]}`;fe&&(Re+=`::${fe}`),lt("CPU",Re);return}ve[Be].includes("TRACE_FUNC")&&(Te=!0)}},Rt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("BEGIN",re)},He=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("END",re)},bt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${re}`)},st=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${re}`)}}),sn,Ye=h(()=>{b(),Je(),an(),sn=class F2{constructor(fe){this.handler=fe}async run(fe,ve,Te){Rt(),bt("InferenceSession.run");let Ce={},Be={};if(typeof fe!="object"||fe===null||fe instanceof Ne||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Re=!0;if(typeof ve=="object"){if(ve===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ve instanceof Ne)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ve)){if(ve.length===0)throw new TypeError("'fetches' cannot be an empty array.");Re=!1;for(let et of ve){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Ce[et]=null}if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,it=Object.getOwnPropertyNames(ve);for(let tt of this.outputNames)if(it.indexOf(tt)!==-1){let Xe=ve[tt];(Xe===null||Xe instanceof Ne)&&(et=!0,Re=!1,Ce[tt]=Xe)}if(et){if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Be=ve}}else if(typeof ve<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof fe[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Re)for(let et of this.outputNames)Ce[et]=null;let Me=await this.handler.run(fe,Ce,Be),Fe={};for(let et in Me)if(Object.hasOwnProperty.call(Me,et)){let it=Me[et];it instanceof Ne?Fe[et]=it:Fe[et]=new Ne(it.type,it.data,it.dims)}return st("InferenceSession.run"),He(),Fe}async release(){return this.handler.dispose()}static async create(fe,ve,Te,Ce){Rt(),bt("InferenceSession.create");let Be,Re={};if(typeof fe=="string"){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let it=fe,tt=0,Xe=fe.byteLength;if(typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve=="number"){if(tt=ve,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=it.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${it.byteLength}).`);if(Xe=fe.byteLength-tt,typeof Te=="number"){if(Xe=Te,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||tt+Xe>it.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${it.byteLength-tt}].`);if(typeof Ce=="object"&&Ce!==null)Re=Ce;else if(typeof Ce<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ve<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(it,tt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Me,Fe]=await y(Re),et=await Me.createInferenceSessionHandler(Be,Fe);return st("InferenceSession.create"),He(),new F2(et)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),yt,kt=h(()=>{Ye(),yt=sn}),Kt=h(()=>{}),On=h(()=>{}),Rn=h(()=>{}),Br=h(()=>{}),Tr={};m(Tr,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>bt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,env:()=>I,registerBackend:()=>E});var nt=h(()=>{_(),z(),kt(),Je(),Kt(),On(),an(),Rn(),Br()}),St=h(()=>{}),Tt={};m(Tt,{default:()=>$r});var cn,nn,$r,Ta=h(()=>{var re;be(),Hr(),Ur(),cn="ort-wasm-proxy-worker",nn=((re=globalThis.self)==null?void 0:re.name)===cn,nn&&(self.onmessage=fe=>{let{type:ve,in:Te}=fe.data;try{switch(ve){case"init-wasm":ti(Te.wasm).then(()=>{Ko(Te).then(()=>{postMessage({type:ve})},Ce=>{postMessage({type:ve,err:Ce})})},Ce=>{postMessage({type:ve,err:Ce})});break;case"init-ep":{let{epName:Ce,env:Be}=Te;Ci(Be,Ce).then(()=>{postMessage({type:ve})},Re=>{postMessage({type:ve,err:Re})});break}case"copy-from":{let{buffer:Ce}=Te,Be=on(Ce);postMessage({type:ve,out:Be});break}case"create":{let{model:Ce,options:Be}=Te;ds(Ce,Be).then(Re=>{postMessage({type:ve,out:Re})},Re=>{postMessage({type:ve,err:Re})});break}case"release":Wi(Te),postMessage({type:ve});break;case"run":{let{sessionId:Ce,inputIndices:Be,inputs:Re,outputIndices:Me,options:Fe}=Te;Ke(Ce,Be,Re,Me,new Array(Me.length).fill(null),Fe).then(et=>{et.some(it=>it[3]!=="cpu")?postMessage({type:ve,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ve,out:et},ft([...Re,...et]))},et=>{postMessage({type:ve,err:et})});break}case"end-profiling":qr(Te),postMessage({type:ve});break;default:}}catch(Ce){postMessage({type:ve,err:Ce})}}),$r=nn?null:fe=>new Worker(fe??yn,{type:"classic",name:cn})}),Vo,vi,yn,Fr,Zn,bi,Ms,as,Fi,wi,_i,Is,Ar,Ur=h(()=>{St(),Vo=typeof location>"u"?void 0:location.origin,vi=()=>{var re,fe;return typeof document<"u"?(re=document.currentScript)==null?void 0:re.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},yn=vi(),Fr=()=>{if(yn&&!yn.startsWith("blob:"))return yn.substring(0,yn.lastIndexOf("/")+1)},Zn=(re,fe)=>{try{let ve=fe??yn;return(ve?new URL(re,ve):new URL(re)).origin===Vo}catch{return!1}},bi=(re,fe)=>{let ve=fe??yn;try{return(ve?new URL(re,ve):new URL(re)).href}catch{return}},Ms=(re,fe)=>`${fe??"./"}${re}`,as=async re=>{let fe=await(await fetch(re,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},Fi=async re=>(await import(re)).default,wi=(Ta(),g(Tt)).default,_i=async()=>{if(!yn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zn(yn))return[void 0,wi()];let re=await as(yn);return[re,wi(re)]},Is=void 0,Ar=async(re,fe,ve,Te)=>{let Ce=Is&&!(re||fe);if(Ce)if(yn)Ce=Zn(yn)||Te&&!ve;else if(Te&&!ve)Ce=!0;else throw new Error("cannot determine the script source URL.");if(Ce)return[void 0,Is];{let Be="ort-wasm-simd-threaded.mjs",Re=re??bi(Be,fe),Me=ve&&Re&&!Zn(Re,fe),Fe=Me?await as(Re):Re??Ms(Be,fe);return[Me?Fe:void 0,await Fi(Fe)]}}}),Qs,Rr,ls,js,ho,Zs,ei,ti,zt,Hr=h(()=>{Ur(),Rr=!1,ls=!1,js=!1,ho=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Zs=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ei=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},ti=async re=>{if(Rr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(js)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let fe=re.initTimeout,ve=re.numThreads;if(re.simd!==!1){if(re.simd==="relaxed"){if(!ei())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Zs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=ho();ve>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ve+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),re.numThreads=ve=1);let Ce=re.wasmPaths,Be=typeof Ce=="string"?Ce:void 0,Re=Ce==null?void 0:Ce.mjs,Me=(Re==null?void 0:Re.href)??Re,Fe=Ce==null?void 0:Ce.wasm,et=(Fe==null?void 0:Fe.href)??Fe,it=re.wasmBinary,[tt,Xe]=await Ar(Me,Be,ve>1,!!it||!!et),At=!1,ze=[];if(fe>0&&ze.push(new Promise(ut=>{setTimeout(()=>{At=!0,ut()},fe)})),ze.push(new Promise((ut,Cn)=>{let Jt={numThreads:ve};if(it)Jt.wasmBinary=it,Jt.locateFile=Qt=>Qt;else if(et||Be)Jt.locateFile=Qt=>et??Be+Qt;else if(Me&&Me.indexOf("blob:")!==0)Jt.locateFile=Qt=>new URL(Qt,Me).href;else if(tt){let Qt=Fr();Qt&&(Jt.locateFile=jn=>Qt+jn)}Xe(Jt).then(Qt=>{ls=!1,Rr=!0,Qs=Qt,ut(),tt&&URL.revokeObjectURL(tt)},Qt=>{ls=!1,js=!0,Cn(Qt)})})),await Promise.race(ze),At)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},zt=()=>{if(Rr&&Qs)return Qs;throw new Error("WebAssembly is not initialized yet.")}}),Hn,_n,Ct,Ui=h(()=>{Hr(),Hn=(re,fe)=>{let ve=zt(),Te=ve.lengthBytesUTF8(re)+1,Ce=ve._malloc(Te);return ve.stringToUTF8(re,Ce,Te),fe.push(Ce),Ce},_n=(re,fe,ve,Te)=>{if(typeof re=="object"&&re!==null){if(ve.has(re))throw new Error("Circular reference in options");ve.add(re)}Object.entries(re).forEach(([Ce,Be])=>{let Re=fe?fe+Ce:Ce;if(typeof Be=="object")_n(Be,Re+".",ve,Te);else if(typeof Be=="string"||typeof Be=="number")Te(Re,Be.toString());else if(typeof Be=="boolean")Te(Re,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Ct=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetLastError(Ce,Ce+Te);let Be=Number(fe.getValue(Ce,Te===4?"i32":"i64")),Re=fe.getValue(Ce+Te,"*"),Me=Re?fe.UTF8ToString(Re):"";throw new Error(`${re} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Me}`)}finally{fe.stackRestore(ve)}}}),fo,$a=h(()=>{Hr(),Ui(),fo=re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};try{if((re==null?void 0:re.logSeverityLevel)===void 0)Ce.logSeverityLevel=2;else if(typeof re.logSeverityLevel!="number"||!Number.isInteger(re.logSeverityLevel)||re.logSeverityLevel<0||re.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${re.logSeverityLevel}`);if((re==null?void 0:re.logVerbosityLevel)===void 0)Ce.logVerbosityLevel=0;else if(typeof re.logVerbosityLevel!="number"||!Number.isInteger(re.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${re.logVerbosityLevel}`);(re==null?void 0:re.terminate)===void 0&&(Ce.terminate=!1);let Be=0;return(re==null?void 0:re.tag)!==void 0&&(Be=Hn(re.tag,Te)),ve=fe._OrtCreateRunOptions(Ce.logSeverityLevel,Ce.logVerbosityLevel,!!Ce.terminate,Be),ve===0&&Ct("Can't create run options."),(re==null?void 0:re.extra)!==void 0&&_n(re.extra,"",new WeakSet,(Re,Me)=>{let Fe=Hn(Re,Te),et=Hn(Me,Te);fe._OrtAddRunConfigEntry(ve,Fe,et)!==0&&Ct(`Can't set a run config entry: ${Re} - ${Me}.`)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseRunOptions(ve),Te.forEach(Re=>fe._free(Re)),Be}}}),po,mo,Go,Sr,Aa,Ra,kn=h(()=>{Hr(),Ui(),po=re=>{switch(re){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${re}`)}},mo=re=>{switch(re){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${re}`)}},Go=re=>{re.extra||(re.extra={}),re.extra.session||(re.extra.session={});let fe=re.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),re.executionProviders&&re.executionProviders.some(ve=>(typeof ve=="string"?ve:ve.name)==="webgpu")&&(re.enableMemPattern=!1)},Sr=(re,fe,ve,Te)=>{let Ce=Hn(fe,Te),Be=Hn(ve,Te);zt()._OrtAddSessionConfigEntry(re,Ce,Be)!==0&&Ct(`Can't set a session config entry: ${fe} - ${ve}.`)},Aa=async(re,fe,ve)=>{let Te=fe.executionProviders;for(let Ce of Te){let Be=typeof Ce=="string"?Ce:Ce.name,Re=[];switch(Be){case"webnn":if(Be="WEBNN",Sr(re,"session.disable_quant_qdq","1",ve),Sr(re,"session.disable_qdq_constant_folding","1",ve),typeof Ce!="string"){let tt=Ce==null?void 0:Ce.deviceType;tt&&Sr(re,"deviceType",tt,ve)}break;case"webgpu":if(Be="JS",typeof Ce!="string"){let tt=Ce;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Sr(re,"preferredLayout",tt.preferredLayout,ve)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Me=Hn(Be,ve),Fe=Re.length,et=0,it=0;if(Fe>0){et=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(et),it=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(it);for(let tt=0;tt<Fe;tt++)zt().setValue(et+tt*zt().PTR_SIZE,Re[tt][0],"*"),zt().setValue(it+tt*zt().PTR_SIZE,Re[tt][1],"*")}await zt()._OrtAppendExecutionProvider(re,Me,et,it,Fe)!==0&&Ct(`Can't append execution provider: ${Be}.`)}},Ra=async re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};Go(Ce);try{let Be=po(Ce.graphOptimizationLevel??"all"),Re=mo(Ce.executionMode??"sequential"),Me=typeof Ce.logId=="string"?Hn(Ce.logId,Te):0,Fe=Ce.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let et=Ce.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let it=typeof Ce.optimizedModelFilePath=="string"?Hn(Ce.optimizedModelFilePath,Te):0;if(ve=fe._OrtCreateSessionOptions(Be,!!Ce.enableCpuMemArena,!!Ce.enableMemPattern,Re,!!Ce.enableProfiling,0,Me,Fe,et,it),ve===0&&Ct("Can't create session options."),Ce.executionProviders&&await Aa(ve,Ce,Te),Ce.enableGraphCapture!==void 0){if(typeof Ce.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ce.enableGraphCapture}`);Sr(ve,"enableGraphCapture",Ce.enableGraphCapture.toString(),Te)}if(Ce.freeDimensionOverrides)for(let[tt,Xe]of Object.entries(Ce.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let At=Hn(tt,Te);fe._OrtAddFreeDimensionOverride(ve,At,Xe)!==0&&Ct(`Can't set a free dimension override: ${tt} - ${Xe}.`)}return Ce.extra!==void 0&&_n(Ce.extra,"",new WeakSet,(tt,Xe)=>{Sr(ve,tt,Xe,Te)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseSessionOptions(ve)!==0&&Ct("Can't release session options."),Te.forEach(Re=>fe._free(Re)),Be}}}),Mr,Vn,Ir,ni,Hi,ki,cs,gr,Bt=h(()=>{Mr=re=>{switch(re){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${re}`)}},Vn=re=>{switch(re){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${re}`)}},Ir=(re,fe)=>{let ve=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][re],Te=typeof fe=="number"?fe:fe.reduce((Ce,Be)=>Ce*Be,1);return ve>0?Math.ceil(Te*ve):void 0},ni=re=>{switch(re){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${re}`)}},Hi=re=>{switch(re){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${re}`)}},ki=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",cs=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint64"||re==="int8"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",gr=re=>{switch(re){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${re}`)}}}),Gn,Si=h(()=>{St(),Gn=async re=>{if(typeof re=="string"){let fe=await fetch(re);if(!fe.ok)throw new Error(`failed to load external data file: ${re}`);let ve=fe.headers.get("Content-Length"),Te=ve?parseInt(ve,10):0;if(Te<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${re}, no response body.`);let Ce=fe.body.getReader(),Be;try{Be=new ArrayBuffer(Te)}catch(Me){if(Me instanceof RangeError){let Fe=Math.ceil(Te/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Me}let Re=0;for(;;){let{done:Me,value:Fe}=await Ce.read();if(Me)break;let et=Fe.byteLength;new Uint8Array(Be,Re,et).set(Fe),Re+=et}return new Uint8Array(Be,0,Te)}}else return re instanceof Blob?new Uint8Array(await re.arrayBuffer()):re instanceof Uint8Array?re:new Uint8Array(re)}}),us,Ko,Ci,Wr,Ps,ji,on,ds,Wi,Es,Ke,qr,ft,be=h(()=>{nt(),$a(),kn(),Bt(),Hr(),Ui(),Si(),us=(re,fe)=>{zt()._OrtInit(re,fe)!==0&&Ct("Can't initialize onnxruntime.")},Ko=async re=>{us(re.wasm.numThreads,Hi(re.logLevel))},Ci=async(re,fe)=>{var Te,Ce;(Ce=(Te=zt()).asyncInit)==null||Ce.call(Te);let ve=re.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ve){if(typeof ve.limits!="object"||typeof ve.features!="object"||typeof ve.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=re.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Re=re.webgpu.forceFallbackAdapter;if(Re!==void 0&&typeof Re!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Re}"`);if(ve=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Re}),!ve)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(fe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wr=new Map,Ps=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetInputOutputCount(re,Ce,Ce+Te)!==0&&Ct("Can't get session input/output count.");let Be=Te===4?"i32":"i64";return[Number(fe.getValue(Ce,Be)),Number(fe.getValue(Ce+Te,Be))]}finally{fe.stackRestore(ve)}},ji=(re,fe)=>{let ve=zt(),Te=ve.stackSave(),Ce=0;try{let Be=ve.PTR_SIZE,Re=ve.stackAlloc(2*Be);ve._OrtGetInputOutputMetadata(re,fe,Re,Re+Be)!==0&&Ct("Can't get session input/output metadata.");let Me=Number(ve.getValue(Re,"*"));Ce=Number(ve.getValue(Re+Be,"*"));let Fe=ve.HEAP32[Ce/4];if(Fe===0)return[Me,0];let et=ve.HEAPU32[Ce/4+1],it=[];for(let tt=0;tt<et;tt++){let Xe=Number(ve.getValue(Ce+8+tt*Be,"*"));it.push(Xe!==0?ve.UTF8ToString(Xe):Number(ve.getValue(Ce+8+(tt+et)*Be,"*")))}return[Me,Fe,it]}finally{ve.stackRestore(Te),Ce!==0&&ve._OrtFree(Ce)}},on=re=>{let fe=zt(),ve=fe._malloc(re.byteLength);if(ve===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${re.byteLength}.`);return fe.HEAPU8.set(re,ve),[ve,re.byteLength]},ds=async(re,fe)=>{var it,tt,Xe;let ve,Te,Ce=zt();Array.isArray(re)?[ve,Te]=re:re.buffer===Ce.HEAPU8.buffer?[ve,Te]=[re.byteOffset,re.byteLength]:[ve,Te]=on(re);let Be=0,Re=0,Me=[],Fe=[],et=[];try{if([Re,Me]=await Ra(fe),(fe==null?void 0:fe.externalData)&&Ce.mountExternalData){let Mn=[];for(let hn of fe.externalData){let xr=typeof hn=="string"?hn:hn.path;Mn.push(Gn(typeof hn=="string"?hn:hn.data).then(Pr=>{Ce.mountExternalData(xr,Pr)}))}await Promise.all(Mn)}for(let Mn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Mn=="string"?Mn:Mn.name)==="webnn"){if(Ce.shouldTransferToMLTensor=!1,typeof Mn!="string"){let hn=Mn,xr=hn==null?void 0:hn.context,Pr=hn==null?void 0:hn.gpuDevice,Vr=hn==null?void 0:hn.deviceType,Ia=hn==null?void 0:hn.powerPreference;xr?Ce.currentContext=xr:Pr?Ce.currentContext=await Ce.webnnCreateMLContext(Pr):Ce.currentContext=await Ce.webnnCreateMLContext({deviceType:Vr,powerPreference:Ia})}else Ce.currentContext=await Ce.webnnCreateMLContext();break}Be=await Ce._OrtCreateSession(ve,Te,Re),(it=Ce.webgpuOnCreateSession)==null||it.call(Ce,Be),Be===0&&Ct("Can't create a session."),(tt=Ce.jsepOnCreateSession)==null||tt.call(Ce),Ce.currentContext&&(Ce.webnnRegisterMLContext(Be,Ce.currentContext),Ce.currentContext=void 0,Ce.shouldTransferToMLTensor=!0);let[At,ze]=Ps(Be),ut=!!(fe!=null&&fe.enableGraphCapture),Cn=[],Jt=[],Qt=[],jn=[],Ot=[];for(let Mn=0;Mn<At;Mn++){let[hn,xr,Pr]=ji(Be,Mn);hn===0&&Ct("Can't get an input name."),Fe.push(hn);let Vr=Ce.UTF8ToString(hn);Cn.push(Vr),Qt.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}for(let Mn=0;Mn<ze;Mn++){let[hn,xr,Pr]=ji(Be,Mn+At);hn===0&&Ct("Can't get an output name."),et.push(hn);let Vr=Ce.UTF8ToString(hn);Jt.push(Vr),jn.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}return Wr.set(Be,[Be,Fe,et,null,ut,!1]),[Be,Cn,Jt,Qt,jn]}catch(At){throw Fe.forEach(ze=>Ce._OrtFree(ze)),et.forEach(ze=>Ce._OrtFree(ze)),Be!==0&&Ce._OrtReleaseSession(Be)!==0&&Ct("Can't release session."),At}finally{Ce._free(ve),Re!==0&&Ce._OrtReleaseSessionOptions(Re)!==0&&Ct("Can't release session options."),Me.forEach(At=>Ce._free(At)),(Xe=Ce.unmountExternalData)==null||Xe.call(Ce)}},Wi=re=>{var Fe,et,it;let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error(`cannot release session. invalid session id: ${re}`);let[Te,Ce,Be,Re,Me]=ve;Re&&(Me&&fe._OrtClearBoundOutputs(Re.handle)!==0&&Ct("Can't clear bound outputs."),fe._OrtReleaseBinding(Re.handle)!==0&&Ct("Can't release IO binding.")),(Fe=fe.jsepOnReleaseSession)==null||Fe.call(fe,re),(et=fe.webnnOnReleaseSession)==null||et.call(fe,re),(it=fe.webgpuOnReleaseSession)==null||it.call(fe,re),Ce.forEach(tt=>fe._OrtFree(tt)),Be.forEach(tt=>fe._OrtFree(tt)),fe._OrtReleaseSession(Te)!==0&&Ct("Can't release session."),Wr.delete(re)},Es=async(re,fe,ve,Te,Ce,Be,Re=!1)=>{if(!re){fe.push(0);return}let Me=zt(),Fe=Me.PTR_SIZE,et=re[0],it=re[1],tt=re[3],Xe=tt,At,ze;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Re&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Jt=re[2].gpuBuffer;ze=Ir(Mr(et),it);{let Qt=Me.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');At=Qt(Te,Be,Jt,ze)}}else if(tt==="ml-tensor"){let Jt=re[2].mlTensor;ze=Ir(Mr(et),it);let Qt=Me.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');At=Qt(Te,Jt,Mr(et),it)}else{let Jt=re[2];if(Array.isArray(Jt)){ze=Fe*Jt.length,At=Me._malloc(ze),ve.push(At);for(let Qt=0;Qt<Jt.length;Qt++){if(typeof Jt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Me.setValue(At+Qt*Fe,Hn(Jt[Qt],ve),"*")}}else{let Qt=Me.webnnIsGraphInput,jn=Me.webnnIsGraphOutput;if(et!=="string"&&Qt&&jn){let Ot=Me.UTF8ToString(Ce);if(Qt(Te,Ot)||jn(Te,Ot)){let Mn=Mr(et);ze=Ir(Mn,it),Xe="ml-tensor";let hn=Me.webnnCreateTemporaryTensor,xr=Me.webnnUploadTensor;if(!hn||!xr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Pr=await hn(Te,Mn,it);xr(Pr,new Uint8Array(Jt.buffer,Jt.byteOffset,Jt.byteLength)),At=Pr}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}}let ut=Me.stackSave(),Cn=Me.stackAlloc(4*it.length);try{it.forEach((Qt,jn)=>Me.setValue(Cn+jn*Fe,Qt,Fe===4?"i32":"i64"));let Jt=Me._OrtCreateTensor(Mr(et),At,ze,Cn,it.length,gr(Xe));Jt===0&&Ct(`Can't create tensor for input/output. session=${Te}, index=${Be}.`),fe.push(Jt)}finally{Me.stackRestore(ut)}},Ke=async(re,fe,ve,Te,Ce,Be)=>{var Gr,Sl,Ec;let Re=zt(),Me=Re.PTR_SIZE,Fe=Wr.get(re);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${re}`);let et=Fe[0],it=Fe[1],tt=Fe[2],Xe=Fe[3],At=Fe[4];Fe[5];let ze=fe.length,ut=Te.length,Cn=0,Jt=[],Qt=[],jn=[],Ot=[],Mn=[],hn=Re.stackSave(),xr=Re.stackAlloc(ze*Me),Pr=Re.stackAlloc(ze*Me),Vr=Re.stackAlloc(ut*Me),Ia=Re.stackAlloc(ut*Me);try{[Cn,Jt]=fo(Be),bt("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)await Es(ve[un],Qt,Ot,re,it[fe[un]],fe[un],At);for(let un=0;un<ut;un++)await Es(Ce[un],jn,Ot,re,tt[Te[un]],ze+Te[un],At);st("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)Re.setValue(xr+un*Me,Qt[un],"*"),Re.setValue(Pr+un*Me,it[fe[un]],"*");for(let un=0;un<ut;un++)Re.setValue(Vr+un*Me,jn[un],"*"),Re.setValue(Ia+un*Me,tt[Te[un]],"*");(Gr=Re.jsepOnRunStart)==null||Gr.call(Re,et),(Sl=Re.webnnOnRunStart)==null||Sl.call(Re,et);let yr;yr=await Re._OrtRun(et,Pr,xr,ze,Ia,ut,Vr,Cn),yr!==0&&Ct("failed to call OrtRun().");let si=[],Nc=[];bt("wasm ProcessOutputTensor");for(let un=0;un<ut;un++){let Os=Number(Re.getValue(Vr+un*Me,"*"));if(Os===jn[un]||Mn.includes(jn[un])){si.push(Ce[un]),Os!==jn[un]&&Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.");continue}let Gu=Re.stackSave(),Ti=Re.stackAlloc(4*Me),Xo=!1,ir,Kr=0;try{Re._OrtGetTensorData(Os,Ti,Ti+Me,Ti+2*Me,Ti+3*Me)!==0&&Ct(`Can't access output tensor data on index ${un}.`);let Cl=Me===4?"i32":"i64",Xr=Number(Re.getValue(Ti,Cl));Kr=Re.getValue(Ti+Me,"*");let Tc=Re.getValue(Ti+Me*2,"*"),Ku=Number(Re.getValue(Ti+Me*3,Cl)),$i=[];for(let or=0;or<Ku;or++)$i.push(Number(Re.getValue(Tc+or*Me,Cl)));Re._OrtFree(Tc)!==0&&Ct("Can't free memory for tensor dims.");let Ls=$i.reduce((or,Wn)=>or*Wn,1);ir=Vn(Xr);let ii=Xe==null?void 0:Xe.outputPreferredLocations[Te[un]];if(ir==="string"){if(ii==="gpu-buffer"||ii==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let or=[];for(let Wn=0;Wn<Ls;Wn++){let zs=Re.getValue(Kr+Wn*Me,"*"),$c=Re.getValue(Kr+(Wn+1)*Me,"*"),Ac=Wn===Ls-1?void 0:$c-zs;or.push(Re.UTF8ToString(zs,Ac))}si.push([ir,$i,or,"cpu"])}else if(ii==="gpu-buffer"&&Ls>0){let or=Re.jsepGetBuffer;if(!or)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wn=or(Kr),zs=Ir(Xr,Ls);if(zs===void 0||!ki(ir))throw new Error(`Unsupported data type: ${ir}`);Xo=!0,si.push([ir,$i,{gpuBuffer:Wn,download:Re.jsepCreateDownloader(Wn,zs,ir),dispose:()=>{Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.")}},"gpu-buffer"])}else if(ii==="ml-tensor"&&Ls>0){let or=Re.webnnEnsureTensor,Wn=Re.webnnIsGraphInputOutputTypeSupported;if(!or||!Wn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ir(Xr,Ls)===void 0||!cs(ir))throw new Error(`Unsupported data type: ${ir}`);if(!Wn(re,ir,!1))throw new Error(`preferredLocation "ml-tensor" for ${ir} output is not supported by current WebNN Context.`);let zs=await or(re,Kr,Xr,$i,!1);Xo=!0,si.push([ir,$i,{mlTensor:zs,download:Re.webnnCreateMLTensorDownloader(Kr,ir),dispose:()=>{Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(ii==="ml-tensor-cpu-output"&&Ls>0){let or=Re.webnnCreateMLTensorDownloader(Kr,ir)(),Wn=si.length;Xo=!0,Nc.push((async()=>{let zs=[Wn,await or];return Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os),zs})()),si.push([ir,$i,[],"cpu"])}else{let or=ni(ir),Wn=new or(Ls);new Uint8Array(Wn.buffer,Wn.byteOffset,Wn.byteLength).set(Re.HEAPU8.subarray(Kr,Kr+Wn.byteLength)),si.push([ir,$i,Wn,"cpu"])}}finally{Re.stackRestore(Gu),ir==="string"&&Kr&&Re._free(Kr),Xo||Re._OrtReleaseTensor(Os)}}Xe&&!At&&(Re._OrtClearBoundOutputs(Xe.handle)!==0&&Ct("Can't clear bound outputs."),Wr.set(re,[et,it,tt,Xe,At,!1]));for(let[un,Os]of await Promise.all(Nc))si[un][2]=Os;return st("wasm ProcessOutputTensor"),si}finally{(Ec=Re.webnnOnRunEnd)==null||Ec.call(Re,et),Re.stackRestore(hn),Qt.forEach(yr=>Re._OrtReleaseTensor(yr)),jn.forEach(yr=>Re._OrtReleaseTensor(yr)),Ot.forEach(yr=>Re._free(yr)),Cn!==0&&Re._OrtReleaseRunOptions(Cn),Jt.forEach(yr=>Re._free(yr))}},qr=re=>{let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error("invalid session id");let Te=ve[0],Ce=fe._OrtEndProfiling(Te);Ce===0&&Ct("Can't get an profile file name."),fe._OrtFree(Ce)},ft=re=>{let fe=[];for(let ve of re){let Te=ve[2];!Array.isArray(Te)&&"buffer"in Te&&fe.push(Te.buffer)}return fe}}),Pe,Qe,Et,en,ln,$n,En,er,Ln,sr,Nn,Ds,qi,go,ri,Vu,xo,yo,Sc=h(()=>{nt(),be(),Hr(),Ur(),Pe=()=>!!I.wasm.proxy&&typeof document<"u",Et=!1,en=!1,ln=!1,er=new Map,Ln=(re,fe)=>{let ve=er.get(re);ve?ve.push(fe):er.set(re,[fe])},sr=()=>{if(Et||!en||ln||!Qe)throw new Error("worker not ready")},Nn=re=>{switch(re.data.type){case"init-wasm":Et=!1,re.data.err?(ln=!0,En[1](re.data.err)):(en=!0,En[0]()),$n&&(URL.revokeObjectURL($n),$n=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=er.get(re.data.type);re.data.err?fe.shift()[1](re.data.err):fe.shift()[0](re.data.out);break}}},Ds=async()=>{if(!en){if(Et)throw new Error("multiple calls to 'initWasm()' detected.");if(ln)throw new Error("previous call to 'initWasm()' failed.");if(Et=!0,Pe())return new Promise((re,fe)=>{Qe==null||Qe.terminate(),_i().then(([ve,Te])=>{try{Qe=Te,Qe.onerror=Be=>fe(Be),Qe.onmessage=Nn,En=[re,fe];let Ce={type:"init-wasm",in:I};if(!Ce.in.wasm.wasmPaths&&ve){let Be=Fr();Be&&(Ce.in.wasm.wasmPaths=Be)}Qe.postMessage(Ce),$n=ve}catch(Ce){fe(Ce)}},fe)});try{await ti(I.wasm),await Ko(I),en=!0}catch(re){throw ln=!0,re}finally{Et=!1}}},qi=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("init-ep",[fe,ve]);let Te={type:"init-ep",in:{epName:re,env:I}};Qe.postMessage(Te)});await Ci(I,re)},go=async re=>Pe()?(sr(),new Promise((fe,ve)=>{Ln("copy-from",[fe,ve]);let Te={type:"copy-from",in:{buffer:re}};Qe.postMessage(Te,[re.buffer])})):on(re),ri=async(re,fe)=>{if(Pe()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return sr(),new Promise((ve,Te)=>{Ln("create",[ve,Te]);let Ce={type:"create",in:{model:re,options:{...fe}}},Be=[];re instanceof Uint8Array&&Be.push(re.buffer),Qe.postMessage(Ce,Be)})}else return ds(re,fe)},Vu=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("release",[fe,ve]);let Te={type:"release",in:re};Qe.postMessage(Te)});Wi(re)},xo=async(re,fe,ve,Te,Ce,Be)=>{if(Pe()){if(ve.some(Re=>Re[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ce.some(Re=>Re))throw new Error("pre-allocated output tensor is not supported for proxy.");return sr(),new Promise((Re,Me)=>{Ln("run",[Re,Me]);let Fe=ve,et={type:"run",in:{sessionId:re,inputIndices:fe,inputs:Fe,outputIndices:Te,options:Be}};Qe.postMessage(et,ft(Fe))})}else return Ke(re,fe,ve,Te,Ce,Be)},yo=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("end-profiling",[fe,ve]);let Te={type:"end-profiling",in:re};Qe.postMessage(Te)});qr(re)}}),bl,vo,Ma,wl=h(()=>{nt(),Sc(),Bt(),St(),Si(),bl=(re,fe)=>{switch(re.location){case"cpu":return[re.type,re.dims,re.data,"cpu"];case"gpu-buffer":return[re.type,re.dims,{gpuBuffer:re.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[re.type,re.dims,{mlTensor:re.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${re.location} for ${fe()}`)}},vo=re=>{switch(re[3]){case"cpu":return new Ne(re[0],re[2],re[1]);case"gpu-buffer":{let fe=re[0];if(!ki(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:ve,download:Te,dispose:Ce}=re[2];return Ne.fromGpuBuffer(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}case"ml-tensor":{let fe=re[0];if(!cs(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:ve,download:Te,dispose:Ce}=re[2];return Ne.fromMLTensor(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}default:throw new Error(`invalid data location: ${re[3]}`)}},Ma=class{async fetchModelAndCopyToWasmMemory(re){return go(await Gn(re))}async loadModel(re,fe){Rt();let ve;typeof re=="string"?ve=await this.fetchModelAndCopyToWasmMemory(re):ve=re,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ri(ve,fe),He()}async dispose(){return Vu(this.sessionId)}async run(re,fe,ve){Rt();let Te=[],Ce=[];Object.entries(re).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);Te.push(At),Ce.push(ze)});let Be=[],Re=[];Object.entries(fe).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push(At),Re.push(ze)});let Me=Te.map((tt,Xe)=>bl(tt,()=>`input "${this.inputNames[Ce[Xe]]}"`)),Fe=Be.map((tt,Xe)=>tt?bl(tt,()=>`output "${this.outputNames[Re[Xe]]}"`):null),et=await xo(this.sessionId,Ce,Me,Re,Fe,ve),it={};for(let tt=0;tt<et.length;tt++)it[this.outputNames[Re[tt]]]=Be[tt]??vo(et[tt]);return He(),it}startProfiling(){}endProfiling(){yo(this.sessionId)}}}),Ei={};m(Ei,{OnnxruntimeWebAssemblyBackend:()=>Ni,initializeFlags:()=>Vi,wasmBackend:()=>bo});var Vi,Ni,bo,Cc=h(()=>{nt(),Sc(),wl(),Vi=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let re=I.wasm.simd;if(typeof re!="boolean"&&re!==void 0&&re!=="fixed"&&re!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${re}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let fe=typeof navigator>"u"?u("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Ni=class{async init(re){Vi(),await Ds(),await qi(re)}async createInferenceSessionHandler(re,fe){let ve=new Ma;return await ve.loadModel(re,fe),ve}},bo=new Ni}),jc={};m(jc,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>bt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,default:()=>kl,env:()=>I,registerBackend:()=>E}),nt(),nt(),nt();var _l="1.26.0",kl=Tr;{let re=(Cc(),g(Ei)).wasmBackend;E("cpu",re,10),E("wasm",re,10)}return Object.defineProperty(I.versions,"web",{value:_l,enumerable:!0}),g(jc)})();e.exports=r})(Mv)),Mv.exports}var P_;function mT(){return P_||(P_=1,(function(e){var n=rl&&rl.__createBinding||(Object.create?(function(C,N,$,R){R===void 0&&(R=$);var O=Object.getOwnPropertyDescriptor(N,$);(!O||("get"in O?!N.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return N[$]}}),Object.defineProperty(C,R,O)}):(function(C,N,$,R){R===void 0&&(R=$),C[R]=N[$]})),r=rl&&rl.__setModuleDefault||(Object.create?(function(C,N){Object.defineProperty(C,"default",{enumerable:!0,value:N})}):function(C,N){C.default=N}),i=rl&&rl.__importStar||function(C){if(C&&C.__esModule)return C;var N={};if(C!=null)for(var $ in C)$!=="default"&&Object.prototype.hasOwnProperty.call(C,$)&&n(N,C,$);return r(N,C),N};Object.defineProperty(e,"__esModule",{value:!0}),e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;const o=i(pT()),l=Zw(),d=e0(),u=Qm(),h=Ky(),m=z2(),x=B2();e.DEFAULT_MODEL="legacy",e.ort=o;const g="vad.worklet.bundle.min.js",v="silero_vad_v5.onnx",S="silero_vad_legacy.onnx",E=C=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{u.log.debug("VAD misfire")},onSpeechStart:()=>{u.log.debug("Detected speech start")},onSpeechEnd:()=>{u.log.debug("Detected speech end")},onSpeechRealStart:()=>{u.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:C,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async N=>{N.getTracks().forEach($=>{$.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:N=>{N.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});e.getDefaultRealTimeVADOptions=E;const j=C=>"audioWorklet"in C&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function y(C,N,$,R,O){await $.audioWorklet.addModule(C),N.processorOptions={...N.processorOptions??{},frameSamples:R};const I=new AudioWorkletNode($,"vad-helper-worklet",N);return I.port.onmessage=async z=>{const U=z.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case h.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const W=new Float32Array(U.data);await O(W);break}}},I}async function b(C,N,$){const R=new x.Resampler({nativeSampleRate:C.sampleRate,targetSampleRate:16e3,targetFrameSize:N});u.log.debug("using script processor");const I=C.createScriptProcessor(4096,1,1);let z=!1;return I.onaudioprocess=async U=>{if(!z){z=!0;try{const W=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const V=R.process(W);for(const H of V)await $(H)}catch(W){console.error("Error processing audio:",W)}finally{z=!1}}},I.connect(C.destination),I}class _{constructor(N,$,R,O,I=!1,z=null,U=null,W=null,Y=null,V=null,H=null,te="uninitialized",ae=!1){this.options=N,this.frameProcessor=$,this.model=R,this.frameSamples=O,this.listening=I,this.errored=z,this._stream=U,this._audioContext=W,this._vadNode=Y,this._mediaStreamAudioSourceNode=V,this._audioProcessorAdapterType=H,this.initializationState=te,this.ownsAudioContext=ae,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=oe=>{this.initializationState="errored",this.errored=oe},this.start=async()=>{switch(this.initializationState){case"uninitialized":{u.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(oe){throw oe instanceof Error?this.setErrored(oe.message):this.setErrored(String(oe)),oe}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?j(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await y(this.options.baseAssetPath+g,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await b(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),u.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{u.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:oe,audioContext:ie,vadNode:X}=this.getAudioInstances();this._stream=await this.options.resumeStream(oe);const Q=new MediaStreamAudioSourceNode(ie,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Q,Q.connect(X);break}case"destroyed":{u.log.warn("start called after destroyed");break}case"errored":{u.log.error("start called after errored");break}default:{u.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:oe,mediaStreamAudioSourceNode:ie}=this.getAudioInstances();await this.options.pauseStream(oe),ie.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ie;u.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:oe}=this.getAudioInstances();oe instanceof AudioWorkletNode&&oe.port.postMessage(h.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ie=this._audioContext)==null?void 0:ie.close())},this.setOptions=oe=>{this.frameProcessor.setOptions(oe)},this.processFrame=async oe=>{await this.frameProcessor.process(oe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=oe=>{switch(oe.msg){case h.Message.FrameProcessed:this.options.onFrameProcessed(oe.probs,oe.frame);break;case h.Message.SpeechStart:this.options.onSpeechStart();break;case h.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case h.Message.VADMisfire:this.options.onVADMisfire();break;case h.Message.SpeechEnd:this.options.onSpeechEnd(oe.audio);break}}}static async new(N={}){const $={...(0,e.getDefaultRealTimeVADOptions)(N.model??e.DEFAULT_MODEL),...N};(0,d.validateOptions)($),e.ort.env.wasm.wasmPaths=$.onnxWASMBasePath,$.ortConfig!==void 0&&$.ortConfig(e.ort);const R=$.model==="v5"?v:S,O=$.baseAssetPath+R,I=$.model==="v5"?m.SileroV5.new:m.SileroLegacy.new;let z;try{z=await I(e.ort,()=>(0,l.defaultModelFetcher)(O))}catch(H){throw console.error(`Encountered an error while loading model file ${O}`),H}const U=$.model==="v5"?512:1536,W=U/16,Y=new d.FrameProcessor(z.process,z.reset_state,{positiveSpeechThreshold:$.positiveSpeechThreshold,negativeSpeechThreshold:$.negativeSpeechThreshold,redemptionMs:$.redemptionMs,preSpeechPadMs:$.preSpeechPadMs,minSpeechMs:$.minSpeechMs,submitUserSpeechOnPause:$.submitUserSpeechOnPause},W),V=new _($,Y,z,U);if($.startOnLoad)try{await V.start()}catch(H){throw console.error("Error starting micVad",H),H}return V}}e.MicVAD=_})(rl)),rl}var D_;function gT(){return D_||(D_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultRealTimeVADOptions=e.MicVAD=e.DEFAULT_MODEL=e.utils=e.NonRealTimeVAD=e.Message=e.FrameProcessor=e.defaultModelFetcher=e.baseAssetPath=void 0;var n=D2();Object.defineProperty(e,"baseAssetPath",{enumerable:!0,get:function(){return n.baseAssetPath}});var r=Zw();Object.defineProperty(e,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var i=e0();Object.defineProperty(e,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var o=Ky();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return o.Message}});var l=hT();Object.defineProperty(e,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const d=fT();e.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var u=mT();Object.defineProperty(e,"DEFAULT_MODEL",{enumerable:!0,get:function(){return u.DEFAULT_MODEL}}),Object.defineProperty(e,"MicVAD",{enumerable:!0,get:function(){return u.MicVAD}}),Object.defineProperty(e,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return u.getDefaultRealTimeVADOptions}})})($v)),$v}var xT=gT();function ox(e,n,r,i){var l,d;try{(d=(l=window.api)==null?void 0:l.logs)==null||d.write(e,n,r,i)}catch{}const o=n==="error"?console.error:n==="warn"?console.warn:console.log;i!==void 0?o(`[${e}]`,r,i):o(`[${e}]`,r)}const dt={debug:(e,n,r)=>ox(e,"debug",n,r),info:(e,n,r)=>ox(e,"info",n,r),warn:(e,n,r)=>ox(e,"warn",n,r),error:(e,n,r)=>ox(e,"error",n,r)},U2=16e3,yT=6,Ch=U2*yT,vT=400,bT=U2*vT/1e3,O_=300,L_=2e3,z_=1500,B_=3e3,wT=600,H2=.5,W2=.35,F_=.85,U_=.7;let gi=null,wa=!1,Xs=!1;const Bb=new Set;function ax(e){for(const n of Array.from(Bb))try{n(e)}catch(r){dt.warn("speech","workerDeath listener threw",{error:r instanceof Error?r.message:String(r)})}}let Iv=0;const H_=2;let Bh=!1,q2=!1;function V2(e){e.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.type)!=="log")return;const r=n.data.level||"info";dt[r]("whisperWorker",n.data.message??"",n.data.meta)}),e.addEventListener("error",n=>{dt.error("whisperWorker","worker error event (fatal)",{message:n.message,filename:n.filename,lineno:n.lineno}),_T(`error:${n.message||"unknown"}`)})}function fy(){return gi||(gi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),V2(gi),dt.info("speech","worker spawned"),gi)}let lx=!1;function _T(e){if(!Bh){if(lx){dt.warn("speech","respawnWorker: already in flight, ignoring",{reason:e});return}if(lx=!0,Iv+=1,q2=!0,dt.warn("speech","respawnWorker: starting",{reason:e,attempt:Iv}),ax({reason:e,respawned:!1,finalOnly:!0}),Iv>H_){if(Bh=!0,dt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:H_}),gi)try{gi.terminate()}catch{}gi=null,wa=!1,Xs=!1,ax({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),lx=!1;return}if(gi)try{gi.terminate()}catch{}gi=null,wa=!1,Xs=!1;try{gi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),V2(gi),Xs=!0,gi.postMessage({type:"load"}),dt.info("speech","respawnWorker: new worker spawned, load posted"),ax({reason:e,respawned:!0,finalOnly:!0})}catch(n){Bh=!0,dt.error("speech","respawnWorker: spawn failed, disabling speech",{error:n instanceof Error?n.message:String(n)}),ax({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{lx=!1}}}function kT(e,n){if(wa||Xs)return;Xs=!0;const r=fy();dt.info("speech","preloadModel: posting load");const i=o=>{o.data.type==="status"?(e==null||e(o.data.status,o.data.message),o.data.status==="ready"&&(wa=!0,Xs=!1,dt.info("speech","preloadModel: ready"),r.removeEventListener("message",i))):o.data.type==="progress"?n==null||n(o.data.pct):o.data.type==="error"&&(Xs=!1,dt.error("speech","preloadModel: worker reported error",{error:o.data.error}),e==null||e("error",o.data.error),r.removeEventListener("message",i))};r.addEventListener("message",i),r.postMessage({type:"load"})}function ST(){dt.info("speech","resetModel: clearing load flags"),wa=!1,Xs=!1}function Xy(){var e;return typeof Worker<"u"&&!!((e=navigator.mediaDevices)!=null&&e.getUserMedia)&&typeof AudioWorkletNode<"u"}function CT(e){const n=fy();return!wa&&!Xs&&(Xs=!0,n.postMessage({type:"load"})),new Promise((r,i)=>{const o=l=>{var d,u,h;((d=l.data)==null?void 0:d.type)==="result"?(n.removeEventListener("message",o),r((l.data.text??"").trim())):((u=l.data)==null?void 0:u.type)==="error"?(n.removeEventListener("message",o),i(new Error(String(l.data.error??"Transcription failed")))):((h=l.data)==null?void 0:h.type)==="status"&&l.data.status==="ready"&&(wa=!0,Xs=!1)};n.addEventListener("message",o),n.postMessage({type:"transcribe",audio:e},[e.buffer])})}function G2(e){let n=fy(),r=!1,i=null,o=null,l=null,d=null,u=null;const h=[],m=new Set;let x=null,g=0,v=!1,S=0,E=!1,j=!1,y=0,b=0,_=0,C=-1,N=O_,$=0,R=null,O="",I="",z=!1,U=0;function W(ce,pe){const Ae=Math.min(ce.length,pe.length);let Se=0;for(;Se<Ae&&ce.charCodeAt(Se)===pe.charCodeAt(Se);)Se++;return Se}function Y(ce){const pe=W(O,ce);return O=ce,pe>I.length&&(I=ce.slice(0,pe)),I.length>ce.length&&(I=ce),I}const V=()=>(x||(x=new Float32Array(Ch)),x),H=()=>{g=0},te=ce=>{const pe=V(),Ae=ce.length;if(Ae>=Ch){pe.set(ce.subarray(Ae-Ch)),g=Ch;return}if(g+Ae<=Ch){pe.set(ce,g),g+=Ae;return}const Se=g+Ae-Ch;pe.copyWithin(0,Se,g),g-=Se,pe.set(ce,g),g+=Ae},ae=()=>{R&&(clearTimeout(R),R=null)},oe=()=>{ae(),v=!1,E=!1,j=!1,N=O_,O="",I="",z=!1,U=0,H()},ie=()=>{if(r||!v||j||E||R)return;if(g<bT){R=setTimeout(()=>{R=null,ie()},N);return}const ce=performance.now()-y;if(ce<N&&y!==0){R=setTimeout(()=>{R=null,ie()},N-ce);return}if(q2||Bh||e.partialsEnabled&&!e.partialsEnabled())return;const pe=V(),Ae=new Float32Array(g);Ae.set(pe.subarray(0,g)),b+=1,_=b,E=!0,$=performance.now(),y=$,n.postMessage({type:"transcribe-partial",audio:Ae,seq:b},[Ae.buffer])},X=ce=>ce.length===0?Promise.resolve():Bh?(dt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),r||e.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(pe=>{h.push(pe),b+=1;const Ae=b;C=Ae,n.postMessage({type:"transcribe",audio:ce,seq:Ae},[ce.buffer])}),Q=ce=>{const pe=X(ce);return m.add(pe),pe.finally(()=>{m.delete(pe)}),pe},J=ce=>{var pe,Ae,Se,ye,ne;if(ce.data.type==="result"){const we=ce.data.text,Ne=ce.data.seq??0;Ne&&Ne<C&&dt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ne,latestFinalSeq:C}),!r&&we&&e.onFinal(we),(pe=h.shift())==null||pe()}else if(ce.data.type==="partial"){const we=ce.data.seq??0,Ne=ce.data.text??"",Je=performance.now()-$;E=!1,Je>=B_?(j=!0,dt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Je),seq:we})):Je>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Je),newIntervalMs:N,seq:we})),z||(z=!0,Je>wT&&N<500&&(N=500,dt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Je),newIntervalMs:500})));const lt=we!==_||we<=C;if(!r&&!lt&&Ne){const xt=Y(Ne);xt&&((Ae=e.onPartial)==null||Ae.call(e,xt),U===0&&(U=performance.now(),dt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-S)})))}ie()}else if(ce.data.type==="partial-error"){const we=performance.now()-$;E=!1,we>=B_?(j=!0,dt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ce.data.seq})):we>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:N,seq:ce.data.seq})),dt.warn("speech","partial encode failed",{error:ce.data.error,seq:ce.data.seq}),ie()}else ce.data.type==="error"?(r||e.onError(ce.data.error),(Se=h.shift())==null||Se()):ce.data.type==="status"?(r||(ye=e.onModelStatus)==null||ye.call(e,ce.data.status,ce.data.message),ce.data.status==="ready"&&(wa=!0,Xs=!1)):ce.data.type==="progress"&&(r||(ne=e.onProgress)==null||ne.call(e,ce.data.pct))};n.addEventListener("message",J);const le=ce=>{var pe,Ae;if(!r){for(dt.warn("speech","createRecognition: worker death event",ce),(pe=e.onStatusChange)==null||pe.call(e,"restarting");h.length;)(Ae=h.shift())==null||Ae();if(m.clear(),ae(),E=!1,ce.respawned){try{n.removeEventListener("message",J)}catch{}n=fy(),n.addEventListener("message",J)}}};return Bb.add(le),{start:async()=>{if(!r){if(Bh){e.onError("Speech recognition disabled — please reload the app.");return}!wa&&!Xs&&(Xs=!0,dt.info("speech","createRecognition.start: triggering model load"),n.postMessage({type:"load"})),dt.info("speech","createRecognition.start: initializing VAD",{modelReady:wa,modelLoading:Xs});try{const ce=new URL("vad/",document.baseURI).href,pe=e.inputDeviceId||null,Ae={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};pe&&(Ae.deviceId={exact:pe}),dt.info("speech","getUserMedia",{hasDeviceId:!!pe,deviceIdPrefix:pe?pe.slice(0,8):null});const Se=await navigator.mediaDevices.getUserMedia({audio:Ae});o=Se,l=new AudioContext;for(const ye of Se.getAudioTracks())ye.addEventListener("ended",()=>{r||(dt.warn("speech","mic track ended (permission revoked or device removed)"),e.onError("Microphone disconnected or permission revoked"))});try{u=l.createMediaStreamSource(o),d=l.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,u.connect(d)}catch(ye){dt.warn("speech","analyser init failed",{error:ye instanceof Error?ye.message:String(ye)}),u=null,d=null}i=await xT.MicVAD.new({audioContext:l,getStream:async()=>Se,resumeStream:async()=>Se,pauseStream:async()=>{},baseAssetPath:ce,onnxWASMBasePath:ce,model:"v5",positiveSpeechThreshold:H2,negativeSpeechThreshold:W2,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ye,ne)=>{var we;r||((we=e.onFrame)==null||we.call(e,ye),v&&(te(ne),ie()))},onSpeechStart:()=>{var ye;r||(oe(),v=!0,S=performance.now(),(ye=e.onSpeechStart)==null||ye.call(e))},onSpeechEnd:ye=>{var ne;r||((ne=e.onStatusChange)==null||ne.call(e,"transcribing"),oe(),Q(ye))},onVADMisfire:()=>{var ye,ne;r||((ye=e.onStatusChange)==null||ye.call(e,"idle"),oe(),(ne=e.onMisfire)==null||ne.call(e))}}),i.start()}catch(ce){const pe=ce instanceof Error?ce.message:"Microphone access denied",Ae=ce instanceof Error?ce.stack:"";if(dt.error("speech","createRecognition.start: VAD init failed",{error:pe,stack:Ae}),d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(Se=>Se.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}e.onError(pe)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(oe();m.size>0;)await Promise.all(Array.from(m));if(i){try{await i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ce,pe)=>{if(i)try{i.setOptions({positiveSpeechThreshold:ce,negativeSpeechThreshold:pe})}catch(Ae){dt.warn("speech","setVadThresholds failed",{error:Ae instanceof Error?Ae.message:String(Ae)})}},getAnalyser:()=>d,destroy:()=>{if(r=!0,oe(),i){try{i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.close()}catch{}l=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}Bb.delete(le),n.removeEventListener("message",J)}}}let Am=null;const Fb=new Set,Ub=new Set;function jT(){for(const e of Fb)try{e()}catch{}}function Hb(){for(const e of Ub)try{e()}catch{}}function ET(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function NT(e){if(!window.speechSynthesis)return;const n=ET(e);if(!n)return;const r=new SpeechSynthesisUtterance(n);r.rate=1,r.pitch=1,r.onstart=()=>{Am=performance.now(),jT()},r.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},r.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},window.speechSynthesis.speak(r)}function K2(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Am=null,Hb())}function X2(){var e;return((e=window.speechSynthesis)==null?void 0:e.speaking)??!1}function TT(){return Am}function $T(e){return Fb.add(e),()=>{Fb.delete(e)}}function AT(e){return Ub.add(e),()=>{Ub.delete(e)}}function RT(e){X2()&&(e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const n=$T(()=>{e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on")}),r=AT(()=>{e.setVadThresholds(H2,W2),dt.info("voice","tts.duck.off")});return()=>{n(),r()}}const MT=[{match:/^(send|submit|enter)\.?$/i,data:"\r",label:"send"},{match:/^(cancel|escape)\.?$/i,data:"\x1B",label:"cancel"},{match:/^clear( line)?\.?$/i,data:"",label:"clear"}];function IT(e){const n=e.trim();return MT.find(r=>r.match.test(n))??null}const PT=4e4;let Tu=null;function Fh(){Tu&&clearTimeout(Tu),Tu=setTimeout(()=>{Tu=null,$t.getState().stopRecording()},PT)}function cx(){Tu&&(clearTimeout(Tu),Tu=null)}let mc=null,fc=null;const DT=.04,OT=.3;let py=0,Wb=0;function LT(e){fc!==null&&cancelAnimationFrame(fc);const n=()=>{if(mc===null||$t.getState().submitCountdownStartAt===null){fc=null;return}const r=performance.now();if(r-Wb<200&&py>OT){const o=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:py.toFixed(2),msIntoCountdown:Math.round(o)}),lc(),Fh();return}const i=Y2();if(i){const o=new Uint8Array(i.fftSize);i.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const d=Math.sqrt(l/o.length);if(d>DT){const u=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(u)}),lc(),Fh();return}}fc=requestAnimationFrame(n)};fc=requestAnimationFrame(n)}function zT(e){mc&&clearTimeout(mc);const n=$t.getState().submitDelayMs,r=performance.now();$t.setState({submitCountdownStartAt:r}),mc=setTimeout(()=>{mc=null,$t.setState({submitCountdownStartAt:null});try{window.api.pty.write({tabId:e,data:"\r"})}catch(i){dt.warn("voice","submit pty.write failed",{error:i instanceof Error?i.message:String(i)})}Fh()},n),LT(r)}function lc(){fc!==null&&(cancelAnimationFrame(fc),fc=null),mc&&(clearTimeout(mc),mc=null),$t.getState().submitCountdownStartAt!==null&&$t.setState({submitCountdownStartAt:null})}let rs=null,As=null;function Y2(){var e;return((e=rs==null?void 0:rs.getAnalyser)==null?void 0:e.call(rs))??null}const ux=1e4;let Rm=null;function dx(){Rm&&(clearTimeout(Rm),Rm=null)}let Yx=null,Jx=null;function hx(){Yx=null,Jx&&(Jx(),Jx=null)}const BT=1500,FT=9e4;let fx=0,Qx=null,qb=-1;function px(){Qx&&(clearTimeout(Qx),Qx=null,qb=-1)}const UT=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),$t=cr((e,n)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(n().modelStatus!=="idle")return;dt.info("voice","initModel: kicking off preload"),e({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const r=++fx,i=()=>{r===fx&&(px(),qb=r,Qx=setTimeout(()=>{qb===r&&n().modelStatus==="loading"&&(dt.warn("voice","mic.gate.timeout: no progress within 90s"),e({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},FT))};i(),kT((o,l)=>{r===fx&&(o==="ready"?(px(),dt.info("voice","modelStatus -> ready"),e({modelStatus:"ready",loadingProgress:100,errorKind:null})):o==="error"?(px(),dt.error("voice","modelStatus -> error",{msg:l}),e({modelStatus:"error",error:l,errorKind:"load"})):(i(),e({modelStatus:"loading"})))},o=>{r===fx&&(i(),e({loadingProgress:Math.round(o)}))})},resetAndRetryModel:()=>{dt.info("voice","mic.gate.retry"),px(),ST(),e({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),n().initModel()},startRecording:r=>{if(n().isRecording)return;if(rs){dt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Xy()){e({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const i=o=>{try{const l=G2({inputDeviceId:o,onStatusChange:d=>{e(d==="transcribing"?{statusPill:"transcribing"}:d==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:d=>{n().partialsEnabled&&e({lastPartial:d})},partialsEnabled:()=>n().partialsEnabled,onFrame:d=>{py=d.isSpeech,Wb=performance.now()},onSpeechStart:()=>{if(e({statusPill:"listening",lastPartial:""}),cx(),lc(),X2()){const u=TT(),h=u!==null?performance.now()-u:null;K2(),e({lastBargeInAt:performance.now()}),dt.info("voice","barge-in",{tabId:r,utteranceOffsetMs:h})}else dt.debug("voice","barge-in.no-op",{tabId:r})},onMisfire:()=>{e({lastPartial:"",statusPill:"idle"}),Fh();const d=n().lastBargeInAt;d!==null&&performance.now()-d<600&&dt.warn("voice","barge-in.misfire",{tabId:r,sinceBargeInMs:Math.round(performance.now()-d)})},onFinal:d=>{Fh();const u=d.trim();if(!u||UT.has(u)){e({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}const h=IT(u);if(h){dt.info("voice","voice-command",{tabId:r,label:h.label,transcript:u}),window.api.pty.write({tabId:r,data:h.data}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),lc();const x=window;x.__transcripts&&(x.__transcripts.push({tabId:r,text:u}),x.__transcripts.length>500&&x.__transcripts.shift());return}window.api.pty.write({tabId:r,data:u}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),n().autoSubmit&&zT(r);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:r,text:u}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:d=>{dt.error("voice","recognition error",{err:d}),lc(),e({error:d,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),As==null||As(),As=null,cx(),rs==null||rs.destroy(),rs=null,Le.error(`Microphone error: ${d}`)},onModelStatus:d=>{d==="ready"?e({modelStatus:"ready",loadingProgress:100}):d==="loading"&&e({modelStatus:"loading"})},onProgress:d=>e({loadingProgress:Math.round(d)})});rs=l,e({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Fh(),l.start().then(()=>{rs===l&&(As==null||As(),As=RT(l))}).catch(d=>{const u=d instanceof Error?d.message:String(d);dt.error("voice","handle.start() failed",{error:u}),Le.error(`Could not start mic: ${u}`)})}catch(l){e({error:l instanceof Error?l.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var o,l,d;return((d=(l=(o=window.api)==null?void 0:o.voice)==null?void 0:l.getDevicePref)==null?void 0:d.call(l))??Promise.resolve(null)}).then(o=>i((o==null?void 0:o.selectedDeviceId)??null)).catch(o=>{dt.warn("voice","getDevicePref failed; using default device",{error:o instanceof Error?o.message:String(o)}),i(null)})},stopRecording:()=>{const r=rs;r&&(cx(),lc(),py=0,Wb=0,As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),r.stop().finally(()=>{r.destroy(),rs===r&&(rs=null),n().hotkeyState==="stopping"&&(dx(),e({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!n().isRecording)return;const r=rs;if(!r)return;cx(),As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:""});try{await r.stop()}catch(l){dt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}r.destroy(),rs===r&&(rs=null);const{useSessions:i}=await Jm(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>GN);return{useSessions:l}},[],import.meta.url),o=i.getState().activeTabId;o&&n().startRecording(o)},setExternalRecording:r=>e({externalRecording:r}),toggleTTS:()=>e(r=>({ttsEnabled:!r.ttsEnabled})),setAutoSubmit:r=>e({autoSubmit:r}),setSubmitDelayMs:r=>e({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(r)))}),cancelSubmit:()=>lc(),setPartialsEnabled:r=>{n().partialsEnabled!==r&&(e({partialsEnabled:r}),r||e({lastPartial:""}))},clearError:()=>e({error:null,errorKind:null}),setPermissionState:r=>{n().permissionState!==r&&(dt.info("voice","mic.gate.permission_changed",{from:n().permissionState,to:r}),e({permissionState:r}))},setLevelMeterEnabled:r=>{n().levelMeterEnabled!==r&&e({levelMeterEnabled:r})},setTurnDetectorRuntimeState:r=>{n().turnDetectorState!==r&&(e({turnDetectorState:r}),r==="load_failed"?dt.warn("voice-turn","voice-turn.load_failed"):r==="runtime_error"?dt.warn("voice-turn","voice-turn.runtime_error"):r==="disabled"&&dt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:r=>{n().wizardArmed!==r&&e({wizardArmed:r})},openWizard:()=>{n().wizardOpen||e({wizardOpen:!0})},closeWizard:()=>{n().wizardOpen&&e({wizardOpen:!1})},armHotkey:({phase:r,source:i,mode:o,tabId:l})=>{const d=n(),{canRecord:u,reason:h}=Vb(d);if(r==="down"){if(h==="error"||h==="load-timeout"){d.resetAndRetryModel(),dt.info("voice-hotkey","down.retry",{source:i,reason:h});return}if(!u&&h!=="loading"){dt.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:h});return}if(d.hotkeyState==="recording"||d.isRecording){(o==="toggle"||i==="global")&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording());return}if(h==="loading"){d.hotkeyState!=="armed"&&(e({hotkeyState:"armed"}),dt.info("voice-hotkey","armed",{source:i,modelStatus:d.modelStatus})),hx(),Yx={tabId:l,source:i,mode:o},Jx=$t.subscribe((m,x)=>{if(Yx&&m.modelStatus==="ready"&&x.modelStatus!=="ready"&&m.hotkeyState==="armed"){const g=Yx;if(hx(),!g.tabId){dt.warn("voice-hotkey","armed-promote-no-tab",{source:g.source}),e({hotkeyState:"idle"});return}dt.info("voice-hotkey","armed-promote",g),e({hotkeyState:"recording"}),$t.getState().startRecording(g.tabId)}});return}if(!l){dt.warn("voice-hotkey","no-active-tab",{source:i});return}dt.info("voice-hotkey","start",{source:i,mode:o,tabId:l}),d.startRecording(l),n().isRecording?e({hotkeyState:"recording"}):(dt.warn("voice-hotkey","start: recording did not engage",{errorKind:n().errorKind}),e({hotkeyState:"idle"}));return}if(!(o!=="hold"||i==="global")){if(d.hotkeyState==="armed"){hx(),dt.info("voice-hotkey","miss-model-loading-armed-up"),e({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording())}},destroyHotkey:()=>{const r=n();if(hx(),lc(),r.hotkeyState==="recording"){dt.warn("voice-hotkey","destroyed-mid-recording"),e({hotkeyState:"destroyed"});try{r.stopRecording()}catch{}}else(r.hotkeyState==="armed"||r.hotkeyState==="stopping")&&(dx(),e({hotkeyState:"destroyed"}))}})),HT=e=>({isRecording:e.isRecording,statusPill:e.statusPill,lastPartial:e.lastPartial,lastTranscript:e.lastTranscript,submitCountdownStartAt:e.submitCountdownStartAt}),Vb=e=>Xy()?e.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:e.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:e.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:e.modelStatus==="error"?{canRecord:!1,reason:e.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const e=window;e.__voice=$t,e.__transcripts=[]}function t0(e,n,r){return new Promise((i,o)=>{const l=setTimeout(()=>o(new Error(`${r} timed out after ${n}ms`)),n);e.then(d=>{clearTimeout(l),i(d)},d=>{clearTimeout(l),o(d)})})}const WT=5e3,vc=cr(()=>({snapshot:null,loaded:!1}));let W_=!1,q_=!1,Kp;async function qT(){var e;if(!W_){W_=!0;try{const n=await t0(window.api.schedule.state(),WT,"schedule.state");vc.setState({snapshot:n,loaded:!0}),Kp=((e=n.paused)==null?void 0:e.reason)??null}catch(n){if(!q_){q_=!0;const r=n instanceof Error?n.message:String(n);Le.error(`Scheduler state hydrate failed: ${r}`)}Kp=null}window.api.schedule.onState(n=>{var i;const r=((i=n.paused)==null?void 0:i.reason)??null;Kp!==void 0&&r!==Kp&&(r==="auth"?Le.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):r==="network"&&Le.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Kp=r,vc.setState({snapshot:n,loaded:!0})})}}const VT=6e4,GT=5e3,Uh=cr(()=>({data:null,refreshing:!1}));let V_=!1,Zx=null,G_=null,K_=!1;async function n0(){Uh.setState({refreshing:!0});let e=VT;try{const n=await t0(window.api.billing.fetch(),GT,"billing.fetch");Uh.setState({data:n,refreshing:!1}),n.kind==="transient"?e=G_==="transient"?3e4:5e3:(n.kind==="auth"||n.kind==="meter_rate_limited")&&(e=3e4),G_=n.kind}catch(n){if(Uh.setState({refreshing:!1}),!K_){K_=!0;const r=n instanceof Error?n.message:String(n);Le.warn(`Billing usage fetch failed: ${r}`)}}Zx=setTimeout(n0,e)}function KT(){V_||(V_=!0,n0())}function Yy(e){return e?e.kind==="ok"||e.kind==="ok-stale"?e.data:(e.kind==="auth"||e.kind==="meter_rate_limited")&&e.cached?e.cached:null:null}function my(){Zx!==null&&(clearTimeout(Zx),Zx=null),n0()}function dn({name:e,size:n=17,stroke:r=1.6,className:i}){const o={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",className:i};switch(e){case"home":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 11l8-7 8 7"}),s.jsx("path",{d:"M6 10v9h12v-9"}),s.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 10l3 2-3 2"}),s.jsx("path",{d:"M13 14h4"})]});case"agents":case"subagents":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"7",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"17",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("path",{d:"M8.6 11l2.8 4M15.4 11l-2.8 4M9.5 9h5"})]});case"skills":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"}),s.jsx("path",{d:"M4 6l2 2"})]});case"usage":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"hive":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M8 4h8l4 7-4 7H8l-4-7z"}),s.jsx("circle",{cx:"12",cy:"11",r:"2.5"})]});case"plugins":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),s.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),s.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),s.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),s.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"8",cy:"12",r:"4"}),s.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"plans":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),s.jsx("path",{d:"M8 9h8M8 13h8M8 17h5"})]});case"tasks":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"7",height:"7",rx:"1.5"}),s.jsx("path",{d:"M14 6h7M14 10h5M14 15h7M14 19h5"})]});case"projects":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),s.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"11",cy:"11",r:"6"}),s.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l4 4v14H7z"}),s.jsx("path",{d:"M14 3v4h4"})]});case"play":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),s.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),s.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),s.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),s.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"orchestrator":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"6",r:"2.5"}),s.jsx("circle",{cx:"5",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"19",cy:"17",r:"2.5"}),s.jsx("path",{d:"M12 8.5v6M12 14.5l-7 0M12 14.5l7 0"})]});case"race":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 4v16M5 5h7l-1 3h7v6h-7l-1 3H5"})});case"background":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M3 4h18v4H3zM3 10h18v4H3zM3 16h18v4H3z"}),s.jsx("circle",{cx:"6",cy:"6",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"12",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:".75",fill:"currentColor",stroke:"none"})]});case"repoviz":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"6",cy:"12",r:"3"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"18",cy:"18",r:"3"}),s.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),s.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),s.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),s.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M9 12h6"}),s.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),s.jsx("path",{d:"M4 12h16"})]});case"target":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),s.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),s.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),s.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return s.jsx("svg",{...o,children:s.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14"})});default:return null}}function XT(e,n={}){switch(e){case"ready":return n.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof n.loadingPct=="number"?Math.round(n.loadingPct):0} percent`;case"error":return n.errorMessage?`Microphone — speech model error: ${n.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const X_=e=>Symbol.iterator in e,Y_=e=>"entries"in e,J_=(e,n)=>{const r=e instanceof Map?e:new Map(e.entries()),i=n instanceof Map?n:new Map(n.entries());if(r.size!==i.size)return!1;for(const[o,l]of r)if(!i.has(o)||!Object.is(l,i.get(o)))return!1;return!0},YT=(e,n)=>{const r=e[Symbol.iterator](),i=n[Symbol.iterator]();let o=r.next(),l=i.next();for(;!o.done&&!l.done;){if(!Object.is(o.value,l.value))return!1;o=r.next(),l=i.next()}return!!o.done&&!!l.done};function JT(e,n){return Object.is(e,n)?!0:typeof e!="object"||e===null||typeof n!="object"||n===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(n)?!1:X_(e)&&X_(n)?Y_(e)&&Y_(n)?J_(e,n):YT(e,n):J_({entries:()=>Object.entries(e)},{entries:()=>Object.entries(n)})}function J2(e){const n=co.useRef(void 0);return r=>{const i=e(r);return JT(n.current,i)?n.current:n.current=i}}let Q_=0;const QT=1e3;function ZT(e){const n=performance.now();n-Q_<QT||(Q_=n,dt.debug("voice","mic.gate.click_rejected",{reason:e}))}function Q2(){const e=$t(m=>m.isRecording),n=$t(m=>m.error),r=$t(m=>m.loadingProgress),i=$t(J2(Vb)),o=()=>{const m=$t.getState(),{canRecord:x,reason:g}=Vb(m);if(m.isRecording)return m.stopRecording();if(m.wizardArmed&&!m.wizardOpen){m.openWizard();return}if(g==="error"||g==="load-timeout"){m.resetAndRetryModel();return}if(!x)return ZT(g);const v=vt.getState().activeTabId;v&&m.startRecording(v)},l=XT(i.reason,{loadingPct:r,errorMessage:n,isRecording:e}),d=i.reason==="unsupported",u=!i.canRecord,h=i.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":i.reason==="error"||i.reason==="load-timeout"?"text-red-400 cursor-pointer":i.reason==="permission-denied"?"text-amber-400 cursor-pointer":i.reason==="idle"?"text-fg-faint cursor-pointer":i.reason==="unsupported"?"text-fg-faint cursor-not-allowed":e?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return s.jsx("button",{onClick:o,disabled:d,"aria-disabled":u,"aria-label":l,title:l,"data-testid":"mic-button","data-state":i.reason,className:`p-1.5 rounded transition-colors ${h}`,children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function e$(){const e=$t(r=>r.ttsEnabled),n=$t(r=>r.toggleTTS);return s.jsxs("button",{onClick:n,title:e?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${e?"text-accent":"text-fg-dim hover:text-fg"}`,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),s.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),s.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Zm(e){if(!e||e==="—"||e==="unknown")return e;const n=/\[(\dm)\]/.exec(e),r=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(e);if(!r)return e;const i=r[1].charAt(0).toUpperCase()+r[1].slice(1).toLowerCase(),o=r[3]?`${r[2]}.${r[3]}`:r[2];return n?`${i} ${o} ${n[1]}`:`${i} ${o}`}const mx=new Map,t$=3e4;function Z2(e){const[n,r]=L.useState(()=>{var i;return e?((i=mx.get(e))==null?void 0:i.value)??null:null});return L.useEffect(()=>{if(!e){r(null);return}let i=!1;return(async()=>{const l=mx.get(e);if(l&&Date.now()-l.ts<t$){i||r(l.value);return}try{const d=await window.api.app.gitBranch(e);if(i)return;mx.set(e,{value:d,ts:Date.now()}),r(d)}catch{if(i)return;mx.set(e,{value:null,ts:Date.now()}),r(null)}})(),()=>{i=!0}},[e]),n}const Jy=[{key:"overview",group:"Workspace",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",group:"Workspace",label:"Terminal",icon:"terminal",hint:"Live Claude Code, in-app"},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences"},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project"},{key:"subagents",group:"Workspace",label:"Subagents",icon:"hive",liveKind:"subagents",hint:"Fan out work: Hive · Orchestrate · Race · Boss"},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"usage",group:"Workspace",label:"Usage",icon:"usage",hint:"Tokens, cost, sessions per day"},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],n$=Object.fromEntries(Jy.map(e=>[e.key,e.group])),Pv={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},Z_=Jy.filter(e=>e.group==="Workspace"),e1=Jy.filter(e=>e.group==="Configure"),t1=Jy.filter(e=>e.group==="Tools").map(({key:e,label:n,icon:r,hint:i})=>({key:e,label:n,icon:r,hint:i})),Gb="sm.almanac.sidebarWidth",eC=180,tC=480,Kb=252;function r$(){try{const e=parseInt(localStorage.getItem(Gb)??"",10);if(Number.isFinite(e))return Math.min(tC,Math.max(eC,e))}catch{}return Kb}const s$=52,nC="sm.almanac.sidebarCollapsed";function i$(){try{return localStorage.getItem(nC)==="1"}catch{}return!1}const rC="sm.almanac.collapsedGroups";function o$(){try{const e=localStorage.getItem(rC);if(!e)return new Set;const n=JSON.parse(e);return Array.isArray(n)?new Set(n.filter(r=>r==="Workspace"||r==="Configure"||r==="Tools")):new Set}catch{return new Set}}function a$(){const e=$m(l=>l.tabs),n=vc(l=>{var d;return(((d=l.snapshot)==null?void 0:d.jobs)??[]).some(u=>u.status==="running")}),[r,i]=L.useState(()=>Date.now());return L.useEffect(()=>{const l=setInterval(()=>i(Date.now()),5e3);return()=>clearInterval(l)},[]),{subagents:Object.values(e).some(l=>l.agents.some(d=>r-d.at<6e4)),scheduler:n}}function l$({active:e,onNavigate:n,onNewSession:r}){const[i,o]=L.useState(()=>o$()),l=L.useCallback(_=>{o(C=>{const N=new Set(C);N.has(_)?N.delete(_):N.add(_);try{localStorage.setItem(rC,JSON.stringify(Array.from(N)))}catch{}return N})},[]),[d,u]=L.useState(()=>i$()),h=L.useCallback(()=>{u(_=>{const C=!_;try{localStorage.setItem(nC,C?"1":"0")}catch{}return C})},[]),m=vt(_=>_.tabs),x=vt(_=>_.activeTabId),g=m.find(_=>_.id===x)??null,v=a$(),[S,E]=L.useState(()=>r$()),j=L.useRef(S);j.current=S;const y=L.useCallback(_=>{_.preventDefault();const C=_.clientX,N=j.current;let $=N;const R=I=>{$=Math.min(tC,Math.max(eC,N+(I.clientX-C))),E($)},O=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",O),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Gb,String($))}catch{}};window.addEventListener("pointermove",R),window.addEventListener("pointerup",O),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),b=L.useCallback(()=>{E(Kb);try{localStorage.setItem(Gb,String(Kb))}catch{}},[]);return s.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?s$:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[s.jsx(c$,{tab:g,onNewSession:r,rail:d,onToggleRail:h}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:s.jsxs(s.Fragment,{children:[!d&&s.jsx(Dv,{label:"Workspace",desc:Pv.Workspace,collapsed:i.has("Workspace"),count:Z_.length,onToggle:()=>l("Workspace")}),(d||!i.has("Workspace"))&&Z_.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:_.liveKind?v[_.liveKind]:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Configure",desc:Pv.Configure,collapsed:i.has("Configure"),count:e1.length,onToggle:()=>l("Configure")}),(d||!i.has("Configure"))&&e1.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Tools",desc:Pv.Tools,collapsed:i.has("Tools"),count:t1.length,onToggle:()=>l("Tools")}),(d||!i.has("Tools"))&&t1.map(_=>s.jsx(u$,{tool:_,active:e===_.key,onClick:()=>n(_.key),rail:d},_.key))]})}),s.jsx(d$,{rail:d}),!d&&s.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:y,onDoubleClick:b,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function c$({tab:e,onNewSession:n,rail:r,onToggleRail:i}){const o=(e==null?void 0:e.label)??"no session",l=Z2((e==null?void 0:e.cwd)??null);return r?s.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[s.jsx("button",{onClick:n,"data-testid":"tour-new-session",title:"New session",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:s.jsx(dn,{name:"plus",size:15,stroke:1.8})}),s.jsx("button",{onClick:i,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:s.jsx(dn,{name:"chevron",size:15,stroke:1.8})})})]}):s.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),s.jsx("button",{onClick:i,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:s.jsx(dn,{name:"chevron",size:13,stroke:1.8})})})]}),s.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[s.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),s.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(e==null?void 0:e.cwd)??"",children:o})]}),s.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:l?`⌥${l}`:e?e.cwd:"—"}),s.jsxs("div",{className:"mt-3 flex items-stretch gap-1.5",children:[s.jsxs("button",{onClick:n,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[s.jsx(dn,{name:"plus",size:13,stroke:1.8}),"New session"]}),s.jsx("div",{className:"flex items-center rounded-md bg-bg-hi border border-line",children:s.jsx(Q2,{})})]})]})}function Dv({label:e,desc:n,collapsed:r,count:i,onToggle:o}){return s.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[s.jsxs("button",{onClick:o,"aria-expanded":!r,title:r?`Expand ${e}`:`Collapse ${e}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[s.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:r?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),s.jsx("span",{className:"flex-1",children:e}),r&&s.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]}),!r&&s.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:n})]})}function n1({item:e,active:n,live:r,onClick:i,rail:o}){return s.jsxs("button",{onClick:i,title:e.hint,"data-testid":e.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${o?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${n?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${o?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:17,stroke:1.6})}),!o&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]}),!o&&r&&s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),o&&r&&s.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function u$({tool:e,active:n,onClick:r,rail:i}){return s.jsxs("button",{onClick:r,title:e.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${i?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${n?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${i?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:15,stroke:1.6})}),!i&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]})]})}function d$({rail:e}){const n=$t(u=>u.isRecording),r=vt(u=>u.tabs),i=vt(u=>u.activeTabId),o=r.find(u=>u.id===i)??null,[l,d]=L.useState(null);return L.useEffect(()=>{let u=!1;if(!(o!=null&&o.presetId)){d(null);return}return C2(o.presetId).then(h=>{u||d((h==null?void 0:h.model)??null)}).catch(()=>{u||d(null)}),()=>{u=!0}},[o==null?void 0:o.presetId]),e?s.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"})}):s.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"}),s.jsx("span",{className:"truncate",title:l??"",children:n?"recording…":l?`Claude · ${Zm(l)}`:"Claude Code"})]})}function h$({onNavigate:e}){const n=vt(C=>C.tabs),r=vt(C=>C.activeTabId),i=n.find(C=>C.id===r)??null,o=P2(i),l=(o==null?void 0:o.lastEventAt)??0,d=Uh(C=>C.data),u=vc(C=>{var N;return((N=C.snapshot)==null?void 0:N.paused)??null}),h=Z2((i==null?void 0:i.cwd)??null),[,m]=L.useState(0);L.useEffect(()=>{const C=setInterval(()=>m(N=>N+1),6e4);return()=>clearInterval(C)},[]);const x=(o==null?void 0:o.todos)??[],[g,v]=L.useState(!1),S=L.useRef(null);L.useEffect(()=>{if(!g)return;const C=N=>{S.current&&!S.current.contains(N.target)&&v(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g]),L.useEffect(()=>{x.length===0&&v(!1)},[x.length]);const E=Yy(d),j=(E==null?void 0:E.usage.five_hour)??null,y=j?Math.round(j.utilization):null,b=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",_=l>0?m$(Date.now()-l):"—";return s.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[s.jsxs("button",{onClick:()=>e==null?void 0:e("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:b?"Connected to Anthropic":"Disconnected",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${b?"bg-sage":"bg-fg-faint"}`}),s.jsx("span",{children:b?"connected":"offline"})]}),s.jsx("button",{onClick:()=>e==null?void 0:e("usage"),className:"hover:text-fg transition-colors",title:"Open Usage",children:y!=null?`${y}% of 5h window used`:"5h —"}),u&&s.jsxs("button",{onClick:()=>e==null?void 0:e("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${u.reason==="auth"||u.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",u.reason]}),i&&s.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,h&&s.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",h]})]}),s.jsxs("span",{className:"text-fg-faint",children:["last activity: ",s.jsx("span",{className:"text-fg-dim",children:_})]}),x.length>0&&s.jsx(f$,{ref:S,todos:x,open:g,onToggle:()=>v(C=>!C)}),s.jsx("span",{className:"flex-1"}),s.jsxs("span",{className:"text-fg-faint",children:["v","0.38.3"]})]})}const f$=L.forwardRef(function({todos:n,open:r,onToggle:i},o){const l={completed:n.filter(d=>d.status==="completed").length,in_progress:n.filter(d=>d.status==="in_progress").length,pending:n.filter(d=>d.status==="pending").length};return s.jsxs("div",{ref:o,className:"relative",children:[s.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[s.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),s.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),s.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),s.jsxs("span",{className:"text-fg-faint",children:["todos ",r?"▾":"▴"]})]}),r&&s.jsx("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 z-50","data-testid":"footer-todos-popover",children:s.jsx("ul",{className:"space-y-0.5",children:n.map((d,u)=>s.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[s.jsx(p$,{status:d.status}),s.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},u))})})]})});function p$({status:e}){return e==="completed"?s.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):e==="in_progress"?s.jsx("span",{className:"w-3 shrink-0",children:s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function m$(e){const n=Math.max(0,Math.floor(e/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}var Ov={exports:{}},r1;function g$(){return r1||(r1=1,(function(e,n){(function(r,i){e.exports=i()})(globalThis,(()=>(()=>{var r={4567:function(d,u,h){var m=this&&this.__decorate||function(_,C,N,$){var R,O=arguments.length,I=O<3?C:$===null?$=Object.getOwnPropertyDescriptor(C,N):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(_,C,N,$);else for(var z=_.length-1;z>=0;z--)(R=_[z])&&(I=(O<3?R(I):O>3?R(C,N,I):R(C,N))||I);return O>3&&I&&Object.defineProperty(C,N,I),I},x=this&&this.__param||function(_,C){return function(N,$){C(N,$,_)}};Object.defineProperty(u,"__esModule",{value:!0}),u.AccessibilityManager=void 0;const g=h(9042),v=h(9924),S=h(844),E=h(4725),j=h(2585),y=h(3656);let b=u.AccessibilityManager=class extends S.Disposable{constructor(_,C,N,$){super(),this._terminal=_,this._coreBrowserService=N,this._renderService=$,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let R=0;R<this._terminal.rows;R++)this._rowElements[R]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[R]);if(this._topBoundaryFocusListener=R=>this._handleBoundaryFocus(R,0),this._bottomBoundaryFocusListener=R=>this._handleBoundaryFocus(R,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new v.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((R=>this._handleResize(R.rows)))),this.register(this._terminal.onRender((R=>this._refreshRows(R.start,R.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((R=>this._handleChar(R)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
2897
|
+
*/var I_;function pT(){return I_||(I_=1,(function(e,n){var r=(()=>{var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,u=(re=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(re,{get:(fe,ve)=>(typeof oo<"u"?oo:fe)[ve]}):re)(function(re){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+re+'" is not supported')}),h=(re,fe)=>()=>(re&&(fe=re(re=0)),fe),m=(re,fe)=>{for(var ve in fe)i(re,ve,{get:fe[ve],enumerable:!0})},x=(re,fe,ve,Te)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ce of l(fe))!d.call(re,Ce)&&Ce!==ve&&i(re,Ce,{get:()=>fe[Ce],enumerable:!(Te=o(fe,Ce))||Te.enumerable});return re},g=re=>x(i({},"__esModule",{value:!0}),re),v,S,E,j,y,b=h(()=>{v=new Map,S=[],E=(re,fe,ve)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let Te=v.get(re);if(Te===void 0)v.set(re,{backend:fe,priority:ve});else{if(Te.priority>ve)return;if(Te.priority===ve&&Te.backend!==fe)throw new Error(`cannot register backend "${re}" using priority ${ve}`)}if(ve>=0){let Ce=S.indexOf(re);Ce!==-1&&S.splice(Ce,1);for(let Be=0;Be<S.length;Be++)if(v.get(S[Be]).priority<=ve){S.splice(Be,0,re);return}S.push(re)}return}throw new TypeError("not a valid backend")},j=async re=>{let fe=v.get(re);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let ve=!!fe.initPromise;try{return ve||(fe.initPromise=fe.backend.init(re)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(Te){return ve||(fe.error=`${Te}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},y=async re=>{let fe=re.executionProviders||[],ve=fe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),Te=ve.length===0?S:ve,Ce,Be=[],Re=new Set;for(let Fe of Te){let et=await j(Fe);typeof et=="string"?Be.push({name:Fe,err:et}):(Ce||(Ce=et),Ce===et&&Re.add(Fe))}if(!Ce)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:et}of Be)ve.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${et}`);let Me=fe.filter(Fe=>Re.has(typeof Fe=="string"?Fe:Fe.name));return[Ce,new Proxy(re,{get:(Fe,et)=>et==="executionProviders"?Me:Reflect.get(Fe,et)})]}}),_=h(()=>{b()}),C,N=h(()=>{C="1.26.0"}),$,R,O=h(()=>{N(),$="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(re){if(re!==void 0){if(typeof re!="string"||["verbose","info","warning","error","fatal"].indexOf(re)===-1)throw new Error(`Unsupported logging level: ${re}`);$=re}},get logLevel(){return $}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),I,z=h(()=>{O(),I=R}),U,W,Y=h(()=>{U=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ve.width=re.dims[3],ve.height=re.dims[2];let Te=ve.getContext("2d");if(Te!=null){let Ce,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2]);let Re=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Me=fe==null?void 0:fe.norm,Fe,et;Me===void 0||Me.mean===void 0?Fe=[255,255,255,255]:typeof Me.mean=="number"?Fe=[Me.mean,Me.mean,Me.mean,Me.mean]:(Fe=[Me.mean[0],Me.mean[1],Me.mean[2],0],Me.mean[3]!==void 0&&(Fe[3]=Me.mean[3])),Me===void 0||Me.bias===void 0?et=[0,0,0,0]:typeof Me.bias=="number"?et=[Me.bias,Me.bias,Me.bias,Me.bias]:(et=[Me.bias[0],Me.bias[1],Me.bias[2],0],Me.bias[3]!==void 0&&(et[3]=Me.bias[3]));let it=Be*Ce,tt=0,Xe=it,At=it*2,ze=-1;Re==="RGBA"?(tt=0,Xe=it,At=it*2,ze=it*3):Re==="RGB"?(tt=0,Xe=it,At=it*2):Re==="RBG"&&(tt=0,At=it,Xe=it*2);for(let ut=0;ut<Be;ut++)for(let Cn=0;Cn<Ce;Cn++){let Jt=(re.data[tt++]-et[0])*Fe[0],Qt=(re.data[Xe++]-et[1])*Fe[1],jn=(re.data[At++]-et[2])*Fe[2],Ot=ze===-1?255:(re.data[ze++]-et[3])*Fe[3];Te.fillStyle="rgba("+Jt+","+Qt+","+jn+","+Ot+")",Te.fillRect(Cn,ut,1,1)}if("toDataURL"in ve)return ve.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},W=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(ve!=null){let Ce,Be,Re;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[1],Re=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2],Re=re.dims[1]);let Me=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Fe=fe==null?void 0:fe.norm,et,it;Fe===void 0||Fe.mean===void 0?et=[255,255,255,255]:typeof Fe.mean=="number"?et=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(et=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(et[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?it=[0,0,0,0]:typeof Fe.bias=="number"?it=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(it=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(it[3]=Fe.bias[3]));let tt=Be*Ce;if(fe!==void 0&&(fe.format!==void 0&&Re===4&&fe.format!=="RGBA"||Re===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,At=0,ze=1,ut=2,Cn=3,Jt=0,Qt=tt,jn=tt*2,Ot=-1;Me==="RGBA"?(Jt=0,Qt=tt,jn=tt*2,Ot=tt*3):Me==="RGB"?(Jt=0,Qt=tt,jn=tt*2):Me==="RBG"&&(Jt=0,jn=tt,Qt=tt*2),Te=ve.createImageData(Ce,Be);for(let Mn=0;Mn<Be*Ce;At+=Xe,ze+=Xe,ut+=Xe,Cn+=Xe,Mn++)Te.data[At]=(re.data[Jt++]-it[0])*et[0],Te.data[ze]=(re.data[Qt++]-it[1])*et[1],Te.data[ut]=(re.data[jn++]-it[2])*et[2],Te.data[Cn]=Ot===-1?255:(re.data[Ot++]-it[3])*et[3]}else throw new Error("Can not access image data");return Te}}),V,H,te,ae,oe,ie,X=h(()=>{we(),V=(re,fe)=>{if(re===void 0)throw new Error("Image buffer must be defined");if(fe.height===void 0||fe.width===void 0)throw new Error("Image height and width must be defined");if(fe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ve,width:Te}=fe,Ce=fe.norm??{mean:255,bias:0},Be,Re;typeof Ce.mean=="number"?Be=[Ce.mean,Ce.mean,Ce.mean,Ce.mean]:Be=[Ce.mean[0],Ce.mean[1],Ce.mean[2],Ce.mean[3]??255],typeof Ce.bias=="number"?Re=[Ce.bias,Ce.bias,Ce.bias,Ce.bias]:Re=[Ce.bias[0],Ce.bias[1],Ce.bias[2],Ce.bias[3]??0];let Me=fe.format!==void 0?fe.format:"RGBA",Fe=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",et=ve*Te,it=Fe==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Xe=0,At=1,ze=2,ut=3,Cn=0,Jt=et,Qt=et*2,jn=-1;Me==="RGB"&&(tt=3,Xe=0,At=1,ze=2,ut=-1),Fe==="RGBA"?jn=et*3:Fe==="RBG"?(Cn=0,Qt=et,Jt=et*2):Fe==="BGR"&&(Qt=0,Jt=et,Cn=et*2);for(let Ot=0;Ot<et;Ot++,Xe+=tt,ze+=tt,At+=tt,ut+=tt)it[Cn++]=(re[Xe]+Re[0])/Be[0],it[Jt++]=(re[At]+Re[1])/Be[1],it[Qt++]=(re[ze]+Re[2])/Be[2],jn!==-1&&ut!==-1&&(it[jn++]=(re[ut]+Re[3])/Be[3]);return Fe==="RGBA"?new ne("float32",it,[1,4,ve,Te]):new ne("float32",it,[1,3,ve,Te])},H=async(re,fe)=>{let ve=typeof HTMLImageElement<"u"&&re instanceof HTMLImageElement,Te=typeof ImageData<"u"&&re instanceof ImageData,Ce=typeof ImageBitmap<"u"&&re instanceof ImageBitmap,Be=typeof re=="string",Re,Me=fe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},et=it=>typeof HTMLCanvasElement<"u"&&it instanceof HTMLCanvasElement||it instanceof OffscreenCanvas?it.getContext("2d"):null;if(ve){let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,At=fe.resizedWidth),fe!==void 0){if(Me=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At}else Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At;tt.drawImage(re,0,0),Re=tt.getImageData(0,0,At,Xe).data}else throw new Error("Can not access image data")}else if(Te){let it,tt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(it=fe.resizedHeight,tt=fe.resizedWidth):(it=re.height,tt=re.width),fe!==void 0&&(Me=fe),Me.format="RGBA",Me.height=it,Me.width=tt,fe!==void 0){let Xe=Fe();Xe.width=tt,Xe.height=it;let At=et(Xe);if(At!=null)At.putImageData(re,0,0),Re=At.getImageData(0,0,tt,it).data;else throw new Error("Can not access image data")}else Re=re.data}else if(Ce){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;return tt.drawImage(re,0,0,At,Xe),Re=tt.getImageData(0,0,At,Xe).data,Me.height=Xe,Me.width=At,V(Re,Me)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((it,tt)=>{let Xe=Fe(),At=et(Xe);if(!re||!At)return tt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=re,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,At.drawImage(ze,0,0,Xe.width,Xe.height);let ut=At.getImageData(0,0,Xe.width,Xe.height);Me.height=Xe.height,Me.width=Xe.width,it(V(ut.data,Me))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Re!==void 0)return V(Re,Me);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(re,fe)=>{let{width:ve,height:Te,download:Ce,dispose:Be}=fe,Re=[1,Te,ve,4];return new ne({location:"texture",type:"float32",texture:re,dims:Re,download:Ce,dispose:Be})},ae=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"gpu-buffer",type:ve??"float32",gpuBuffer:re,dims:Te,download:Ce,dispose:Be})},oe=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"ml-tensor",type:ve??"float32",mlTensor:re,dims:Te,download:Ce,dispose:Be})},ie=(re,fe,ve)=>new ne({location:"cpu-pinned",type:re,data:fe,dims:ve??[fe.length]})}),Q,J,le,ce,pe=h(()=>{Q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ce=()=>{if(!le){le=!0;let re=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,ve=globalThis.Float16Array,Te=typeof ve<"u"&&ve.from;re&&(Q.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),fe&&(Q.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),Te?(Q.set("float16",ve),J.set(ve,"float16")):Q.set("float16",Uint16Array)}}}),Ae,Se,ye=h(()=>{we(),Ae=re=>{let fe=1;for(let ve=0;ve<re.length;ve++){let Te=re[ve];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${ve}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${ve}] must be a non-negative integer, got: ${Te}`);fe*=Te}return fe},Se=(re,fe)=>{switch(re.location){case"cpu":return new ne(re.type,re.data,fe);case"cpu-pinned":return new ne({location:"cpu-pinned",data:re.data,type:re.type,dims:fe});case"texture":return new ne({location:"texture",texture:re.texture,type:re.type,dims:fe});case"gpu-buffer":return new ne({location:"gpu-buffer",gpuBuffer:re.gpuBuffer,type:re.type,dims:fe});case"ml-tensor":return new ne({location:"ml-tensor",mlTensor:re.mlTensor,type:re.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${re.location} is not supported`)}}}),ne,we=h(()=>{Y(),X(),pe(),ye(),ne=class{constructor(re,fe,ve){ce();let Te,Ce;if(typeof re=="object"&&"location"in re)switch(this.dataLocation=re.location,Te=re.type,Ce=re.dims,re.location){case"cpu-pinned":{let Re=Q.get(Te);if(!Re)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(re.data instanceof Re))throw new TypeError(`buffer should be of type ${Re.name}`);this.cpuData=re.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=re.texture,this.downloader=re.download,this.disposer=re.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=re.gpuBuffer,this.downloader=re.download,this.disposer=re.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=re.mlTensor,this.downloader=re.download,this.disposer=re.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Re,Me;if(typeof re=="string")if(Te=re,Me=ve,re==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");Re=fe}else{let Fe=Q.get(re);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${re}.`);if(Array.isArray(fe)){if(re==="float16"&&Fe===Uint16Array||re==="uint4"||re==="int4")throw new TypeError(`Creating a ${re} tensor from number array is not supported. Please use ${Fe.name} as data.`);re==="uint64"||re==="int64"?Re=Fe.from(fe,BigInt):Re=Fe.from(fe)}else if(fe instanceof Fe)Re=fe;else if(fe instanceof Uint8ClampedArray)if(re==="uint8")Re=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(re==="float16"&&fe instanceof Uint16Array&&Fe!==Uint16Array)Re=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Fe}`)}else if(Me=fe,Array.isArray(re)){if(re.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof re[0];if(Fe==="string")Te="string",Re=re;else if(Fe==="boolean")Te="bool",Re=Uint8Array.from(re);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(re instanceof Uint8ClampedArray)Te="uint8",Re=Uint8Array.from(re);else{let Fe=J.get(re.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${re.constructor}.`);Te=Fe,Re=re}if(Me===void 0)Me=[Re.length];else if(!Array.isArray(Me))throw new TypeError("A tensor's dims must be a number array");Ce=Me,this.cpuData=Re,this.dataLocation="cpu"}let Be=Ae(Ce);if(this.cpuData&&Be!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=Ce,this.size=Be}static async fromImage(re,fe){return H(re,fe)}static fromTexture(re,fe){return te(re,fe)}static fromGpuBuffer(re,fe){return ae(re,fe)}static fromMLTensor(re,fe){return oe(re,fe)}static fromPinnedBuffer(re,fe,ve){return ie(re,fe,ve)}toDataURL(re){return U(this,re)}toImageData(re){return W(this,re)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(re){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let fe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=fe,re&&this.disposer&&(this.disposer(),this.disposer=void 0),fe}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(re){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,re)}}}),Ne,Je=h(()=>{we(),Ne=ne}),lt,xt,Rt,He,bt,st,an=h(()=>{O(),lt=(re,fe)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${re}::ORT::${fe}`)},xt=(re,fe)=>{var Ce;let ve=((Ce=new Error().stack)==null?void 0:Ce.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Be=0;Be<ve.length;Be++){if(Te&&!ve[Be].includes("TRACE_FUNC")){let Re=`FUNC_${re}::${ve[Be].trim().split(" ")[1]}`;fe&&(Re+=`::${fe}`),lt("CPU",Re);return}ve[Be].includes("TRACE_FUNC")&&(Te=!0)}},Rt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("BEGIN",re)},He=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("END",re)},bt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${re}`)},st=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${re}`)}}),sn,Ye=h(()=>{b(),Je(),an(),sn=class F2{constructor(fe){this.handler=fe}async run(fe,ve,Te){Rt(),bt("InferenceSession.run");let Ce={},Be={};if(typeof fe!="object"||fe===null||fe instanceof Ne||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Re=!0;if(typeof ve=="object"){if(ve===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ve instanceof Ne)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ve)){if(ve.length===0)throw new TypeError("'fetches' cannot be an empty array.");Re=!1;for(let et of ve){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Ce[et]=null}if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,it=Object.getOwnPropertyNames(ve);for(let tt of this.outputNames)if(it.indexOf(tt)!==-1){let Xe=ve[tt];(Xe===null||Xe instanceof Ne)&&(et=!0,Re=!1,Ce[tt]=Xe)}if(et){if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Be=ve}}else if(typeof ve<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof fe[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Re)for(let et of this.outputNames)Ce[et]=null;let Me=await this.handler.run(fe,Ce,Be),Fe={};for(let et in Me)if(Object.hasOwnProperty.call(Me,et)){let it=Me[et];it instanceof Ne?Fe[et]=it:Fe[et]=new Ne(it.type,it.data,it.dims)}return st("InferenceSession.run"),He(),Fe}async release(){return this.handler.dispose()}static async create(fe,ve,Te,Ce){Rt(),bt("InferenceSession.create");let Be,Re={};if(typeof fe=="string"){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let it=fe,tt=0,Xe=fe.byteLength;if(typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve=="number"){if(tt=ve,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=it.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${it.byteLength}).`);if(Xe=fe.byteLength-tt,typeof Te=="number"){if(Xe=Te,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||tt+Xe>it.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${it.byteLength-tt}].`);if(typeof Ce=="object"&&Ce!==null)Re=Ce;else if(typeof Ce<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ve<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(it,tt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Me,Fe]=await y(Re),et=await Me.createInferenceSessionHandler(Be,Fe);return st("InferenceSession.create"),He(),new F2(et)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),yt,kt=h(()=>{Ye(),yt=sn}),Kt=h(()=>{}),On=h(()=>{}),Rn=h(()=>{}),Br=h(()=>{}),Tr={};m(Tr,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>bt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,env:()=>I,registerBackend:()=>E});var nt=h(()=>{_(),z(),kt(),Je(),Kt(),On(),an(),Rn(),Br()}),St=h(()=>{}),Tt={};m(Tt,{default:()=>$r});var cn,nn,$r,Ta=h(()=>{var re;be(),Hr(),Ur(),cn="ort-wasm-proxy-worker",nn=((re=globalThis.self)==null?void 0:re.name)===cn,nn&&(self.onmessage=fe=>{let{type:ve,in:Te}=fe.data;try{switch(ve){case"init-wasm":ti(Te.wasm).then(()=>{Ko(Te).then(()=>{postMessage({type:ve})},Ce=>{postMessage({type:ve,err:Ce})})},Ce=>{postMessage({type:ve,err:Ce})});break;case"init-ep":{let{epName:Ce,env:Be}=Te;Ci(Be,Ce).then(()=>{postMessage({type:ve})},Re=>{postMessage({type:ve,err:Re})});break}case"copy-from":{let{buffer:Ce}=Te,Be=on(Ce);postMessage({type:ve,out:Be});break}case"create":{let{model:Ce,options:Be}=Te;ds(Ce,Be).then(Re=>{postMessage({type:ve,out:Re})},Re=>{postMessage({type:ve,err:Re})});break}case"release":Wi(Te),postMessage({type:ve});break;case"run":{let{sessionId:Ce,inputIndices:Be,inputs:Re,outputIndices:Me,options:Fe}=Te;Ke(Ce,Be,Re,Me,new Array(Me.length).fill(null),Fe).then(et=>{et.some(it=>it[3]!=="cpu")?postMessage({type:ve,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ve,out:et},ft([...Re,...et]))},et=>{postMessage({type:ve,err:et})});break}case"end-profiling":qr(Te),postMessage({type:ve});break;default:}}catch(Ce){postMessage({type:ve,err:Ce})}}),$r=nn?null:fe=>new Worker(fe??yn,{type:"classic",name:cn})}),Vo,vi,yn,Fr,Zn,bi,Ms,as,Fi,wi,_i,Is,Ar,Ur=h(()=>{St(),Vo=typeof location>"u"?void 0:location.origin,vi=()=>{var re,fe;return typeof document<"u"?(re=document.currentScript)==null?void 0:re.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},yn=vi(),Fr=()=>{if(yn&&!yn.startsWith("blob:"))return yn.substring(0,yn.lastIndexOf("/")+1)},Zn=(re,fe)=>{try{let ve=fe??yn;return(ve?new URL(re,ve):new URL(re)).origin===Vo}catch{return!1}},bi=(re,fe)=>{let ve=fe??yn;try{return(ve?new URL(re,ve):new URL(re)).href}catch{return}},Ms=(re,fe)=>`${fe??"./"}${re}`,as=async re=>{let fe=await(await fetch(re,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},Fi=async re=>(await import(re)).default,wi=(Ta(),g(Tt)).default,_i=async()=>{if(!yn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zn(yn))return[void 0,wi()];let re=await as(yn);return[re,wi(re)]},Is=void 0,Ar=async(re,fe,ve,Te)=>{let Ce=Is&&!(re||fe);if(Ce)if(yn)Ce=Zn(yn)||Te&&!ve;else if(Te&&!ve)Ce=!0;else throw new Error("cannot determine the script source URL.");if(Ce)return[void 0,Is];{let Be="ort-wasm-simd-threaded.mjs",Re=re??bi(Be,fe),Me=ve&&Re&&!Zn(Re,fe),Fe=Me?await as(Re):Re??Ms(Be,fe);return[Me?Fe:void 0,await Fi(Fe)]}}}),Qs,Rr,ls,js,ho,Zs,ei,ti,zt,Hr=h(()=>{Ur(),Rr=!1,ls=!1,js=!1,ho=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Zs=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ei=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},ti=async re=>{if(Rr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(js)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let fe=re.initTimeout,ve=re.numThreads;if(re.simd!==!1){if(re.simd==="relaxed"){if(!ei())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Zs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=ho();ve>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ve+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),re.numThreads=ve=1);let Ce=re.wasmPaths,Be=typeof Ce=="string"?Ce:void 0,Re=Ce==null?void 0:Ce.mjs,Me=(Re==null?void 0:Re.href)??Re,Fe=Ce==null?void 0:Ce.wasm,et=(Fe==null?void 0:Fe.href)??Fe,it=re.wasmBinary,[tt,Xe]=await Ar(Me,Be,ve>1,!!it||!!et),At=!1,ze=[];if(fe>0&&ze.push(new Promise(ut=>{setTimeout(()=>{At=!0,ut()},fe)})),ze.push(new Promise((ut,Cn)=>{let Jt={numThreads:ve};if(it)Jt.wasmBinary=it,Jt.locateFile=Qt=>Qt;else if(et||Be)Jt.locateFile=Qt=>et??Be+Qt;else if(Me&&Me.indexOf("blob:")!==0)Jt.locateFile=Qt=>new URL(Qt,Me).href;else if(tt){let Qt=Fr();Qt&&(Jt.locateFile=jn=>Qt+jn)}Xe(Jt).then(Qt=>{ls=!1,Rr=!0,Qs=Qt,ut(),tt&&URL.revokeObjectURL(tt)},Qt=>{ls=!1,js=!0,Cn(Qt)})})),await Promise.race(ze),At)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},zt=()=>{if(Rr&&Qs)return Qs;throw new Error("WebAssembly is not initialized yet.")}}),Hn,_n,Ct,Ui=h(()=>{Hr(),Hn=(re,fe)=>{let ve=zt(),Te=ve.lengthBytesUTF8(re)+1,Ce=ve._malloc(Te);return ve.stringToUTF8(re,Ce,Te),fe.push(Ce),Ce},_n=(re,fe,ve,Te)=>{if(typeof re=="object"&&re!==null){if(ve.has(re))throw new Error("Circular reference in options");ve.add(re)}Object.entries(re).forEach(([Ce,Be])=>{let Re=fe?fe+Ce:Ce;if(typeof Be=="object")_n(Be,Re+".",ve,Te);else if(typeof Be=="string"||typeof Be=="number")Te(Re,Be.toString());else if(typeof Be=="boolean")Te(Re,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Ct=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetLastError(Ce,Ce+Te);let Be=Number(fe.getValue(Ce,Te===4?"i32":"i64")),Re=fe.getValue(Ce+Te,"*"),Me=Re?fe.UTF8ToString(Re):"";throw new Error(`${re} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Me}`)}finally{fe.stackRestore(ve)}}}),fo,$a=h(()=>{Hr(),Ui(),fo=re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};try{if((re==null?void 0:re.logSeverityLevel)===void 0)Ce.logSeverityLevel=2;else if(typeof re.logSeverityLevel!="number"||!Number.isInteger(re.logSeverityLevel)||re.logSeverityLevel<0||re.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${re.logSeverityLevel}`);if((re==null?void 0:re.logVerbosityLevel)===void 0)Ce.logVerbosityLevel=0;else if(typeof re.logVerbosityLevel!="number"||!Number.isInteger(re.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${re.logVerbosityLevel}`);(re==null?void 0:re.terminate)===void 0&&(Ce.terminate=!1);let Be=0;return(re==null?void 0:re.tag)!==void 0&&(Be=Hn(re.tag,Te)),ve=fe._OrtCreateRunOptions(Ce.logSeverityLevel,Ce.logVerbosityLevel,!!Ce.terminate,Be),ve===0&&Ct("Can't create run options."),(re==null?void 0:re.extra)!==void 0&&_n(re.extra,"",new WeakSet,(Re,Me)=>{let Fe=Hn(Re,Te),et=Hn(Me,Te);fe._OrtAddRunConfigEntry(ve,Fe,et)!==0&&Ct(`Can't set a run config entry: ${Re} - ${Me}.`)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseRunOptions(ve),Te.forEach(Re=>fe._free(Re)),Be}}}),po,mo,Go,Sr,Aa,Ra,kn=h(()=>{Hr(),Ui(),po=re=>{switch(re){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${re}`)}},mo=re=>{switch(re){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${re}`)}},Go=re=>{re.extra||(re.extra={}),re.extra.session||(re.extra.session={});let fe=re.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),re.executionProviders&&re.executionProviders.some(ve=>(typeof ve=="string"?ve:ve.name)==="webgpu")&&(re.enableMemPattern=!1)},Sr=(re,fe,ve,Te)=>{let Ce=Hn(fe,Te),Be=Hn(ve,Te);zt()._OrtAddSessionConfigEntry(re,Ce,Be)!==0&&Ct(`Can't set a session config entry: ${fe} - ${ve}.`)},Aa=async(re,fe,ve)=>{let Te=fe.executionProviders;for(let Ce of Te){let Be=typeof Ce=="string"?Ce:Ce.name,Re=[];switch(Be){case"webnn":if(Be="WEBNN",Sr(re,"session.disable_quant_qdq","1",ve),Sr(re,"session.disable_qdq_constant_folding","1",ve),typeof Ce!="string"){let tt=Ce==null?void 0:Ce.deviceType;tt&&Sr(re,"deviceType",tt,ve)}break;case"webgpu":if(Be="JS",typeof Ce!="string"){let tt=Ce;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Sr(re,"preferredLayout",tt.preferredLayout,ve)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Me=Hn(Be,ve),Fe=Re.length,et=0,it=0;if(Fe>0){et=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(et),it=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(it);for(let tt=0;tt<Fe;tt++)zt().setValue(et+tt*zt().PTR_SIZE,Re[tt][0],"*"),zt().setValue(it+tt*zt().PTR_SIZE,Re[tt][1],"*")}await zt()._OrtAppendExecutionProvider(re,Me,et,it,Fe)!==0&&Ct(`Can't append execution provider: ${Be}.`)}},Ra=async re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};Go(Ce);try{let Be=po(Ce.graphOptimizationLevel??"all"),Re=mo(Ce.executionMode??"sequential"),Me=typeof Ce.logId=="string"?Hn(Ce.logId,Te):0,Fe=Ce.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let et=Ce.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let it=typeof Ce.optimizedModelFilePath=="string"?Hn(Ce.optimizedModelFilePath,Te):0;if(ve=fe._OrtCreateSessionOptions(Be,!!Ce.enableCpuMemArena,!!Ce.enableMemPattern,Re,!!Ce.enableProfiling,0,Me,Fe,et,it),ve===0&&Ct("Can't create session options."),Ce.executionProviders&&await Aa(ve,Ce,Te),Ce.enableGraphCapture!==void 0){if(typeof Ce.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ce.enableGraphCapture}`);Sr(ve,"enableGraphCapture",Ce.enableGraphCapture.toString(),Te)}if(Ce.freeDimensionOverrides)for(let[tt,Xe]of Object.entries(Ce.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let At=Hn(tt,Te);fe._OrtAddFreeDimensionOverride(ve,At,Xe)!==0&&Ct(`Can't set a free dimension override: ${tt} - ${Xe}.`)}return Ce.extra!==void 0&&_n(Ce.extra,"",new WeakSet,(tt,Xe)=>{Sr(ve,tt,Xe,Te)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseSessionOptions(ve)!==0&&Ct("Can't release session options."),Te.forEach(Re=>fe._free(Re)),Be}}}),Mr,Vn,Ir,ni,Hi,ki,cs,gr,Bt=h(()=>{Mr=re=>{switch(re){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${re}`)}},Vn=re=>{switch(re){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${re}`)}},Ir=(re,fe)=>{let ve=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][re],Te=typeof fe=="number"?fe:fe.reduce((Ce,Be)=>Ce*Be,1);return ve>0?Math.ceil(Te*ve):void 0},ni=re=>{switch(re){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${re}`)}},Hi=re=>{switch(re){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${re}`)}},ki=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",cs=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint64"||re==="int8"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",gr=re=>{switch(re){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${re}`)}}}),Gn,Si=h(()=>{St(),Gn=async re=>{if(typeof re=="string"){let fe=await fetch(re);if(!fe.ok)throw new Error(`failed to load external data file: ${re}`);let ve=fe.headers.get("Content-Length"),Te=ve?parseInt(ve,10):0;if(Te<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${re}, no response body.`);let Ce=fe.body.getReader(),Be;try{Be=new ArrayBuffer(Te)}catch(Me){if(Me instanceof RangeError){let Fe=Math.ceil(Te/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Me}let Re=0;for(;;){let{done:Me,value:Fe}=await Ce.read();if(Me)break;let et=Fe.byteLength;new Uint8Array(Be,Re,et).set(Fe),Re+=et}return new Uint8Array(Be,0,Te)}}else return re instanceof Blob?new Uint8Array(await re.arrayBuffer()):re instanceof Uint8Array?re:new Uint8Array(re)}}),us,Ko,Ci,Wr,Ps,ji,on,ds,Wi,Es,Ke,qr,ft,be=h(()=>{nt(),$a(),kn(),Bt(),Hr(),Ui(),Si(),us=(re,fe)=>{zt()._OrtInit(re,fe)!==0&&Ct("Can't initialize onnxruntime.")},Ko=async re=>{us(re.wasm.numThreads,Hi(re.logLevel))},Ci=async(re,fe)=>{var Te,Ce;(Ce=(Te=zt()).asyncInit)==null||Ce.call(Te);let ve=re.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ve){if(typeof ve.limits!="object"||typeof ve.features!="object"||typeof ve.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=re.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Re=re.webgpu.forceFallbackAdapter;if(Re!==void 0&&typeof Re!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Re}"`);if(ve=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Re}),!ve)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(fe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wr=new Map,Ps=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetInputOutputCount(re,Ce,Ce+Te)!==0&&Ct("Can't get session input/output count.");let Be=Te===4?"i32":"i64";return[Number(fe.getValue(Ce,Be)),Number(fe.getValue(Ce+Te,Be))]}finally{fe.stackRestore(ve)}},ji=(re,fe)=>{let ve=zt(),Te=ve.stackSave(),Ce=0;try{let Be=ve.PTR_SIZE,Re=ve.stackAlloc(2*Be);ve._OrtGetInputOutputMetadata(re,fe,Re,Re+Be)!==0&&Ct("Can't get session input/output metadata.");let Me=Number(ve.getValue(Re,"*"));Ce=Number(ve.getValue(Re+Be,"*"));let Fe=ve.HEAP32[Ce/4];if(Fe===0)return[Me,0];let et=ve.HEAPU32[Ce/4+1],it=[];for(let tt=0;tt<et;tt++){let Xe=Number(ve.getValue(Ce+8+tt*Be,"*"));it.push(Xe!==0?ve.UTF8ToString(Xe):Number(ve.getValue(Ce+8+(tt+et)*Be,"*")))}return[Me,Fe,it]}finally{ve.stackRestore(Te),Ce!==0&&ve._OrtFree(Ce)}},on=re=>{let fe=zt(),ve=fe._malloc(re.byteLength);if(ve===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${re.byteLength}.`);return fe.HEAPU8.set(re,ve),[ve,re.byteLength]},ds=async(re,fe)=>{var it,tt,Xe;let ve,Te,Ce=zt();Array.isArray(re)?[ve,Te]=re:re.buffer===Ce.HEAPU8.buffer?[ve,Te]=[re.byteOffset,re.byteLength]:[ve,Te]=on(re);let Be=0,Re=0,Me=[],Fe=[],et=[];try{if([Re,Me]=await Ra(fe),(fe==null?void 0:fe.externalData)&&Ce.mountExternalData){let Mn=[];for(let hn of fe.externalData){let xr=typeof hn=="string"?hn:hn.path;Mn.push(Gn(typeof hn=="string"?hn:hn.data).then(Pr=>{Ce.mountExternalData(xr,Pr)}))}await Promise.all(Mn)}for(let Mn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Mn=="string"?Mn:Mn.name)==="webnn"){if(Ce.shouldTransferToMLTensor=!1,typeof Mn!="string"){let hn=Mn,xr=hn==null?void 0:hn.context,Pr=hn==null?void 0:hn.gpuDevice,Vr=hn==null?void 0:hn.deviceType,Ia=hn==null?void 0:hn.powerPreference;xr?Ce.currentContext=xr:Pr?Ce.currentContext=await Ce.webnnCreateMLContext(Pr):Ce.currentContext=await Ce.webnnCreateMLContext({deviceType:Vr,powerPreference:Ia})}else Ce.currentContext=await Ce.webnnCreateMLContext();break}Be=await Ce._OrtCreateSession(ve,Te,Re),(it=Ce.webgpuOnCreateSession)==null||it.call(Ce,Be),Be===0&&Ct("Can't create a session."),(tt=Ce.jsepOnCreateSession)==null||tt.call(Ce),Ce.currentContext&&(Ce.webnnRegisterMLContext(Be,Ce.currentContext),Ce.currentContext=void 0,Ce.shouldTransferToMLTensor=!0);let[At,ze]=Ps(Be),ut=!!(fe!=null&&fe.enableGraphCapture),Cn=[],Jt=[],Qt=[],jn=[],Ot=[];for(let Mn=0;Mn<At;Mn++){let[hn,xr,Pr]=ji(Be,Mn);hn===0&&Ct("Can't get an input name."),Fe.push(hn);let Vr=Ce.UTF8ToString(hn);Cn.push(Vr),Qt.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}for(let Mn=0;Mn<ze;Mn++){let[hn,xr,Pr]=ji(Be,Mn+At);hn===0&&Ct("Can't get an output name."),et.push(hn);let Vr=Ce.UTF8ToString(hn);Jt.push(Vr),jn.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}return Wr.set(Be,[Be,Fe,et,null,ut,!1]),[Be,Cn,Jt,Qt,jn]}catch(At){throw Fe.forEach(ze=>Ce._OrtFree(ze)),et.forEach(ze=>Ce._OrtFree(ze)),Be!==0&&Ce._OrtReleaseSession(Be)!==0&&Ct("Can't release session."),At}finally{Ce._free(ve),Re!==0&&Ce._OrtReleaseSessionOptions(Re)!==0&&Ct("Can't release session options."),Me.forEach(At=>Ce._free(At)),(Xe=Ce.unmountExternalData)==null||Xe.call(Ce)}},Wi=re=>{var Fe,et,it;let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error(`cannot release session. invalid session id: ${re}`);let[Te,Ce,Be,Re,Me]=ve;Re&&(Me&&fe._OrtClearBoundOutputs(Re.handle)!==0&&Ct("Can't clear bound outputs."),fe._OrtReleaseBinding(Re.handle)!==0&&Ct("Can't release IO binding.")),(Fe=fe.jsepOnReleaseSession)==null||Fe.call(fe,re),(et=fe.webnnOnReleaseSession)==null||et.call(fe,re),(it=fe.webgpuOnReleaseSession)==null||it.call(fe,re),Ce.forEach(tt=>fe._OrtFree(tt)),Be.forEach(tt=>fe._OrtFree(tt)),fe._OrtReleaseSession(Te)!==0&&Ct("Can't release session."),Wr.delete(re)},Es=async(re,fe,ve,Te,Ce,Be,Re=!1)=>{if(!re){fe.push(0);return}let Me=zt(),Fe=Me.PTR_SIZE,et=re[0],it=re[1],tt=re[3],Xe=tt,At,ze;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Re&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Jt=re[2].gpuBuffer;ze=Ir(Mr(et),it);{let Qt=Me.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');At=Qt(Te,Be,Jt,ze)}}else if(tt==="ml-tensor"){let Jt=re[2].mlTensor;ze=Ir(Mr(et),it);let Qt=Me.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');At=Qt(Te,Jt,Mr(et),it)}else{let Jt=re[2];if(Array.isArray(Jt)){ze=Fe*Jt.length,At=Me._malloc(ze),ve.push(At);for(let Qt=0;Qt<Jt.length;Qt++){if(typeof Jt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Me.setValue(At+Qt*Fe,Hn(Jt[Qt],ve),"*")}}else{let Qt=Me.webnnIsGraphInput,jn=Me.webnnIsGraphOutput;if(et!=="string"&&Qt&&jn){let Ot=Me.UTF8ToString(Ce);if(Qt(Te,Ot)||jn(Te,Ot)){let Mn=Mr(et);ze=Ir(Mn,it),Xe="ml-tensor";let hn=Me.webnnCreateTemporaryTensor,xr=Me.webnnUploadTensor;if(!hn||!xr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Pr=await hn(Te,Mn,it);xr(Pr,new Uint8Array(Jt.buffer,Jt.byteOffset,Jt.byteLength)),At=Pr}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}}let ut=Me.stackSave(),Cn=Me.stackAlloc(4*it.length);try{it.forEach((Qt,jn)=>Me.setValue(Cn+jn*Fe,Qt,Fe===4?"i32":"i64"));let Jt=Me._OrtCreateTensor(Mr(et),At,ze,Cn,it.length,gr(Xe));Jt===0&&Ct(`Can't create tensor for input/output. session=${Te}, index=${Be}.`),fe.push(Jt)}finally{Me.stackRestore(ut)}},Ke=async(re,fe,ve,Te,Ce,Be)=>{var Gr,Sl,Ec;let Re=zt(),Me=Re.PTR_SIZE,Fe=Wr.get(re);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${re}`);let et=Fe[0],it=Fe[1],tt=Fe[2],Xe=Fe[3],At=Fe[4];Fe[5];let ze=fe.length,ut=Te.length,Cn=0,Jt=[],Qt=[],jn=[],Ot=[],Mn=[],hn=Re.stackSave(),xr=Re.stackAlloc(ze*Me),Pr=Re.stackAlloc(ze*Me),Vr=Re.stackAlloc(ut*Me),Ia=Re.stackAlloc(ut*Me);try{[Cn,Jt]=fo(Be),bt("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)await Es(ve[un],Qt,Ot,re,it[fe[un]],fe[un],At);for(let un=0;un<ut;un++)await Es(Ce[un],jn,Ot,re,tt[Te[un]],ze+Te[un],At);st("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)Re.setValue(xr+un*Me,Qt[un],"*"),Re.setValue(Pr+un*Me,it[fe[un]],"*");for(let un=0;un<ut;un++)Re.setValue(Vr+un*Me,jn[un],"*"),Re.setValue(Ia+un*Me,tt[Te[un]],"*");(Gr=Re.jsepOnRunStart)==null||Gr.call(Re,et),(Sl=Re.webnnOnRunStart)==null||Sl.call(Re,et);let yr;yr=await Re._OrtRun(et,Pr,xr,ze,Ia,ut,Vr,Cn),yr!==0&&Ct("failed to call OrtRun().");let si=[],Nc=[];bt("wasm ProcessOutputTensor");for(let un=0;un<ut;un++){let Os=Number(Re.getValue(Vr+un*Me,"*"));if(Os===jn[un]||Mn.includes(jn[un])){si.push(Ce[un]),Os!==jn[un]&&Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.");continue}let Gu=Re.stackSave(),Ti=Re.stackAlloc(4*Me),Xo=!1,ir,Kr=0;try{Re._OrtGetTensorData(Os,Ti,Ti+Me,Ti+2*Me,Ti+3*Me)!==0&&Ct(`Can't access output tensor data on index ${un}.`);let Cl=Me===4?"i32":"i64",Xr=Number(Re.getValue(Ti,Cl));Kr=Re.getValue(Ti+Me,"*");let Tc=Re.getValue(Ti+Me*2,"*"),Ku=Number(Re.getValue(Ti+Me*3,Cl)),$i=[];for(let or=0;or<Ku;or++)$i.push(Number(Re.getValue(Tc+or*Me,Cl)));Re._OrtFree(Tc)!==0&&Ct("Can't free memory for tensor dims.");let Ls=$i.reduce((or,Wn)=>or*Wn,1);ir=Vn(Xr);let ii=Xe==null?void 0:Xe.outputPreferredLocations[Te[un]];if(ir==="string"){if(ii==="gpu-buffer"||ii==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let or=[];for(let Wn=0;Wn<Ls;Wn++){let zs=Re.getValue(Kr+Wn*Me,"*"),$c=Re.getValue(Kr+(Wn+1)*Me,"*"),Ac=Wn===Ls-1?void 0:$c-zs;or.push(Re.UTF8ToString(zs,Ac))}si.push([ir,$i,or,"cpu"])}else if(ii==="gpu-buffer"&&Ls>0){let or=Re.jsepGetBuffer;if(!or)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wn=or(Kr),zs=Ir(Xr,Ls);if(zs===void 0||!ki(ir))throw new Error(`Unsupported data type: ${ir}`);Xo=!0,si.push([ir,$i,{gpuBuffer:Wn,download:Re.jsepCreateDownloader(Wn,zs,ir),dispose:()=>{Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.")}},"gpu-buffer"])}else if(ii==="ml-tensor"&&Ls>0){let or=Re.webnnEnsureTensor,Wn=Re.webnnIsGraphInputOutputTypeSupported;if(!or||!Wn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ir(Xr,Ls)===void 0||!cs(ir))throw new Error(`Unsupported data type: ${ir}`);if(!Wn(re,ir,!1))throw new Error(`preferredLocation "ml-tensor" for ${ir} output is not supported by current WebNN Context.`);let zs=await or(re,Kr,Xr,$i,!1);Xo=!0,si.push([ir,$i,{mlTensor:zs,download:Re.webnnCreateMLTensorDownloader(Kr,ir),dispose:()=>{Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(ii==="ml-tensor-cpu-output"&&Ls>0){let or=Re.webnnCreateMLTensorDownloader(Kr,ir)(),Wn=si.length;Xo=!0,Nc.push((async()=>{let zs=[Wn,await or];return Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os),zs})()),si.push([ir,$i,[],"cpu"])}else{let or=ni(ir),Wn=new or(Ls);new Uint8Array(Wn.buffer,Wn.byteOffset,Wn.byteLength).set(Re.HEAPU8.subarray(Kr,Kr+Wn.byteLength)),si.push([ir,$i,Wn,"cpu"])}}finally{Re.stackRestore(Gu),ir==="string"&&Kr&&Re._free(Kr),Xo||Re._OrtReleaseTensor(Os)}}Xe&&!At&&(Re._OrtClearBoundOutputs(Xe.handle)!==0&&Ct("Can't clear bound outputs."),Wr.set(re,[et,it,tt,Xe,At,!1]));for(let[un,Os]of await Promise.all(Nc))si[un][2]=Os;return st("wasm ProcessOutputTensor"),si}finally{(Ec=Re.webnnOnRunEnd)==null||Ec.call(Re,et),Re.stackRestore(hn),Qt.forEach(yr=>Re._OrtReleaseTensor(yr)),jn.forEach(yr=>Re._OrtReleaseTensor(yr)),Ot.forEach(yr=>Re._free(yr)),Cn!==0&&Re._OrtReleaseRunOptions(Cn),Jt.forEach(yr=>Re._free(yr))}},qr=re=>{let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error("invalid session id");let Te=ve[0],Ce=fe._OrtEndProfiling(Te);Ce===0&&Ct("Can't get an profile file name."),fe._OrtFree(Ce)},ft=re=>{let fe=[];for(let ve of re){let Te=ve[2];!Array.isArray(Te)&&"buffer"in Te&&fe.push(Te.buffer)}return fe}}),Pe,Qe,Et,en,ln,$n,En,er,Ln,sr,Nn,Ds,qi,go,ri,Vu,xo,yo,Sc=h(()=>{nt(),be(),Hr(),Ur(),Pe=()=>!!I.wasm.proxy&&typeof document<"u",Et=!1,en=!1,ln=!1,er=new Map,Ln=(re,fe)=>{let ve=er.get(re);ve?ve.push(fe):er.set(re,[fe])},sr=()=>{if(Et||!en||ln||!Qe)throw new Error("worker not ready")},Nn=re=>{switch(re.data.type){case"init-wasm":Et=!1,re.data.err?(ln=!0,En[1](re.data.err)):(en=!0,En[0]()),$n&&(URL.revokeObjectURL($n),$n=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=er.get(re.data.type);re.data.err?fe.shift()[1](re.data.err):fe.shift()[0](re.data.out);break}}},Ds=async()=>{if(!en){if(Et)throw new Error("multiple calls to 'initWasm()' detected.");if(ln)throw new Error("previous call to 'initWasm()' failed.");if(Et=!0,Pe())return new Promise((re,fe)=>{Qe==null||Qe.terminate(),_i().then(([ve,Te])=>{try{Qe=Te,Qe.onerror=Be=>fe(Be),Qe.onmessage=Nn,En=[re,fe];let Ce={type:"init-wasm",in:I};if(!Ce.in.wasm.wasmPaths&&ve){let Be=Fr();Be&&(Ce.in.wasm.wasmPaths=Be)}Qe.postMessage(Ce),$n=ve}catch(Ce){fe(Ce)}},fe)});try{await ti(I.wasm),await Ko(I),en=!0}catch(re){throw ln=!0,re}finally{Et=!1}}},qi=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("init-ep",[fe,ve]);let Te={type:"init-ep",in:{epName:re,env:I}};Qe.postMessage(Te)});await Ci(I,re)},go=async re=>Pe()?(sr(),new Promise((fe,ve)=>{Ln("copy-from",[fe,ve]);let Te={type:"copy-from",in:{buffer:re}};Qe.postMessage(Te,[re.buffer])})):on(re),ri=async(re,fe)=>{if(Pe()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return sr(),new Promise((ve,Te)=>{Ln("create",[ve,Te]);let Ce={type:"create",in:{model:re,options:{...fe}}},Be=[];re instanceof Uint8Array&&Be.push(re.buffer),Qe.postMessage(Ce,Be)})}else return ds(re,fe)},Vu=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("release",[fe,ve]);let Te={type:"release",in:re};Qe.postMessage(Te)});Wi(re)},xo=async(re,fe,ve,Te,Ce,Be)=>{if(Pe()){if(ve.some(Re=>Re[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ce.some(Re=>Re))throw new Error("pre-allocated output tensor is not supported for proxy.");return sr(),new Promise((Re,Me)=>{Ln("run",[Re,Me]);let Fe=ve,et={type:"run",in:{sessionId:re,inputIndices:fe,inputs:Fe,outputIndices:Te,options:Be}};Qe.postMessage(et,ft(Fe))})}else return Ke(re,fe,ve,Te,Ce,Be)},yo=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("end-profiling",[fe,ve]);let Te={type:"end-profiling",in:re};Qe.postMessage(Te)});qr(re)}}),bl,vo,Ma,wl=h(()=>{nt(),Sc(),Bt(),St(),Si(),bl=(re,fe)=>{switch(re.location){case"cpu":return[re.type,re.dims,re.data,"cpu"];case"gpu-buffer":return[re.type,re.dims,{gpuBuffer:re.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[re.type,re.dims,{mlTensor:re.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${re.location} for ${fe()}`)}},vo=re=>{switch(re[3]){case"cpu":return new Ne(re[0],re[2],re[1]);case"gpu-buffer":{let fe=re[0];if(!ki(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:ve,download:Te,dispose:Ce}=re[2];return Ne.fromGpuBuffer(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}case"ml-tensor":{let fe=re[0];if(!cs(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:ve,download:Te,dispose:Ce}=re[2];return Ne.fromMLTensor(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}default:throw new Error(`invalid data location: ${re[3]}`)}},Ma=class{async fetchModelAndCopyToWasmMemory(re){return go(await Gn(re))}async loadModel(re,fe){Rt();let ve;typeof re=="string"?ve=await this.fetchModelAndCopyToWasmMemory(re):ve=re,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ri(ve,fe),He()}async dispose(){return Vu(this.sessionId)}async run(re,fe,ve){Rt();let Te=[],Ce=[];Object.entries(re).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);Te.push(At),Ce.push(ze)});let Be=[],Re=[];Object.entries(fe).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push(At),Re.push(ze)});let Me=Te.map((tt,Xe)=>bl(tt,()=>`input "${this.inputNames[Ce[Xe]]}"`)),Fe=Be.map((tt,Xe)=>tt?bl(tt,()=>`output "${this.outputNames[Re[Xe]]}"`):null),et=await xo(this.sessionId,Ce,Me,Re,Fe,ve),it={};for(let tt=0;tt<et.length;tt++)it[this.outputNames[Re[tt]]]=Be[tt]??vo(et[tt]);return He(),it}startProfiling(){}endProfiling(){yo(this.sessionId)}}}),Ei={};m(Ei,{OnnxruntimeWebAssemblyBackend:()=>Ni,initializeFlags:()=>Vi,wasmBackend:()=>bo});var Vi,Ni,bo,Cc=h(()=>{nt(),Sc(),wl(),Vi=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let re=I.wasm.simd;if(typeof re!="boolean"&&re!==void 0&&re!=="fixed"&&re!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${re}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let fe=typeof navigator>"u"?u("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Ni=class{async init(re){Vi(),await Ds(),await qi(re)}async createInferenceSessionHandler(re,fe){let ve=new Ma;return await ve.loadModel(re,fe),ve}},bo=new Ni}),jc={};m(jc,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>bt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,default:()=>kl,env:()=>I,registerBackend:()=>E}),nt(),nt(),nt();var _l="1.26.0",kl=Tr;{let re=(Cc(),g(Ei)).wasmBackend;E("cpu",re,10),E("wasm",re,10)}return Object.defineProperty(I.versions,"web",{value:_l,enumerable:!0}),g(jc)})();e.exports=r})(Mv)),Mv.exports}var P_;function mT(){return P_||(P_=1,(function(e){var n=rl&&rl.__createBinding||(Object.create?(function(C,N,$,R){R===void 0&&(R=$);var O=Object.getOwnPropertyDescriptor(N,$);(!O||("get"in O?!N.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return N[$]}}),Object.defineProperty(C,R,O)}):(function(C,N,$,R){R===void 0&&(R=$),C[R]=N[$]})),r=rl&&rl.__setModuleDefault||(Object.create?(function(C,N){Object.defineProperty(C,"default",{enumerable:!0,value:N})}):function(C,N){C.default=N}),i=rl&&rl.__importStar||function(C){if(C&&C.__esModule)return C;var N={};if(C!=null)for(var $ in C)$!=="default"&&Object.prototype.hasOwnProperty.call(C,$)&&n(N,C,$);return r(N,C),N};Object.defineProperty(e,"__esModule",{value:!0}),e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;const o=i(pT()),l=Zw(),d=e0(),u=Qm(),h=Ky(),m=z2(),x=B2();e.DEFAULT_MODEL="legacy",e.ort=o;const g="vad.worklet.bundle.min.js",v="silero_vad_v5.onnx",S="silero_vad_legacy.onnx",E=C=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{u.log.debug("VAD misfire")},onSpeechStart:()=>{u.log.debug("Detected speech start")},onSpeechEnd:()=>{u.log.debug("Detected speech end")},onSpeechRealStart:()=>{u.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:C,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async N=>{N.getTracks().forEach($=>{$.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:N=>{N.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});e.getDefaultRealTimeVADOptions=E;const j=C=>"audioWorklet"in C&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function y(C,N,$,R,O){await $.audioWorklet.addModule(C),N.processorOptions={...N.processorOptions??{},frameSamples:R};const I=new AudioWorkletNode($,"vad-helper-worklet",N);return I.port.onmessage=async z=>{const U=z.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case h.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const W=new Float32Array(U.data);await O(W);break}}},I}async function b(C,N,$){const R=new x.Resampler({nativeSampleRate:C.sampleRate,targetSampleRate:16e3,targetFrameSize:N});u.log.debug("using script processor");const I=C.createScriptProcessor(4096,1,1);let z=!1;return I.onaudioprocess=async U=>{if(!z){z=!0;try{const W=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const V=R.process(W);for(const H of V)await $(H)}catch(W){console.error("Error processing audio:",W)}finally{z=!1}}},I.connect(C.destination),I}class _{constructor(N,$,R,O,I=!1,z=null,U=null,W=null,Y=null,V=null,H=null,te="uninitialized",ae=!1){this.options=N,this.frameProcessor=$,this.model=R,this.frameSamples=O,this.listening=I,this.errored=z,this._stream=U,this._audioContext=W,this._vadNode=Y,this._mediaStreamAudioSourceNode=V,this._audioProcessorAdapterType=H,this.initializationState=te,this.ownsAudioContext=ae,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=oe=>{this.initializationState="errored",this.errored=oe},this.start=async()=>{switch(this.initializationState){case"uninitialized":{u.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(oe){throw oe instanceof Error?this.setErrored(oe.message):this.setErrored(String(oe)),oe}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?j(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await y(this.options.baseAssetPath+g,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await b(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),u.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{u.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:oe,audioContext:ie,vadNode:X}=this.getAudioInstances();this._stream=await this.options.resumeStream(oe);const Q=new MediaStreamAudioSourceNode(ie,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Q,Q.connect(X);break}case"destroyed":{u.log.warn("start called after destroyed");break}case"errored":{u.log.error("start called after errored");break}default:{u.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:oe,mediaStreamAudioSourceNode:ie}=this.getAudioInstances();await this.options.pauseStream(oe),ie.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ie;u.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:oe}=this.getAudioInstances();oe instanceof AudioWorkletNode&&oe.port.postMessage(h.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ie=this._audioContext)==null?void 0:ie.close())},this.setOptions=oe=>{this.frameProcessor.setOptions(oe)},this.processFrame=async oe=>{await this.frameProcessor.process(oe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=oe=>{switch(oe.msg){case h.Message.FrameProcessed:this.options.onFrameProcessed(oe.probs,oe.frame);break;case h.Message.SpeechStart:this.options.onSpeechStart();break;case h.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case h.Message.VADMisfire:this.options.onVADMisfire();break;case h.Message.SpeechEnd:this.options.onSpeechEnd(oe.audio);break}}}static async new(N={}){const $={...(0,e.getDefaultRealTimeVADOptions)(N.model??e.DEFAULT_MODEL),...N};(0,d.validateOptions)($),e.ort.env.wasm.wasmPaths=$.onnxWASMBasePath,$.ortConfig!==void 0&&$.ortConfig(e.ort);const R=$.model==="v5"?v:S,O=$.baseAssetPath+R,I=$.model==="v5"?m.SileroV5.new:m.SileroLegacy.new;let z;try{z=await I(e.ort,()=>(0,l.defaultModelFetcher)(O))}catch(H){throw console.error(`Encountered an error while loading model file ${O}`),H}const U=$.model==="v5"?512:1536,W=U/16,Y=new d.FrameProcessor(z.process,z.reset_state,{positiveSpeechThreshold:$.positiveSpeechThreshold,negativeSpeechThreshold:$.negativeSpeechThreshold,redemptionMs:$.redemptionMs,preSpeechPadMs:$.preSpeechPadMs,minSpeechMs:$.minSpeechMs,submitUserSpeechOnPause:$.submitUserSpeechOnPause},W),V=new _($,Y,z,U);if($.startOnLoad)try{await V.start()}catch(H){throw console.error("Error starting micVad",H),H}return V}}e.MicVAD=_})(rl)),rl}var D_;function gT(){return D_||(D_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultRealTimeVADOptions=e.MicVAD=e.DEFAULT_MODEL=e.utils=e.NonRealTimeVAD=e.Message=e.FrameProcessor=e.defaultModelFetcher=e.baseAssetPath=void 0;var n=D2();Object.defineProperty(e,"baseAssetPath",{enumerable:!0,get:function(){return n.baseAssetPath}});var r=Zw();Object.defineProperty(e,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var i=e0();Object.defineProperty(e,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var o=Ky();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return o.Message}});var l=hT();Object.defineProperty(e,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const d=fT();e.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var u=mT();Object.defineProperty(e,"DEFAULT_MODEL",{enumerable:!0,get:function(){return u.DEFAULT_MODEL}}),Object.defineProperty(e,"MicVAD",{enumerable:!0,get:function(){return u.MicVAD}}),Object.defineProperty(e,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return u.getDefaultRealTimeVADOptions}})})($v)),$v}var xT=gT();function ox(e,n,r,i){var l,d;try{(d=(l=window.api)==null?void 0:l.logs)==null||d.write(e,n,r,i)}catch{}const o=n==="error"?console.error:n==="warn"?console.warn:console.log;i!==void 0?o(`[${e}]`,r,i):o(`[${e}]`,r)}const dt={debug:(e,n,r)=>ox(e,"debug",n,r),info:(e,n,r)=>ox(e,"info",n,r),warn:(e,n,r)=>ox(e,"warn",n,r),error:(e,n,r)=>ox(e,"error",n,r)},U2=16e3,yT=6,Ch=U2*yT,vT=400,bT=U2*vT/1e3,O_=300,L_=2e3,z_=1500,B_=3e3,wT=600,H2=.5,W2=.35,F_=.85,U_=.7;let gi=null,wa=!1,Xs=!1;const Bb=new Set;function ax(e){for(const n of Array.from(Bb))try{n(e)}catch(r){dt.warn("speech","workerDeath listener threw",{error:r instanceof Error?r.message:String(r)})}}let Iv=0;const H_=2;let Bh=!1,q2=!1;function V2(e){e.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.type)!=="log")return;const r=n.data.level||"info";dt[r]("whisperWorker",n.data.message??"",n.data.meta)}),e.addEventListener("error",n=>{dt.error("whisperWorker","worker error event (fatal)",{message:n.message,filename:n.filename,lineno:n.lineno}),_T(`error:${n.message||"unknown"}`)})}function fy(){return gi||(gi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),V2(gi),dt.info("speech","worker spawned"),gi)}let lx=!1;function _T(e){if(!Bh){if(lx){dt.warn("speech","respawnWorker: already in flight, ignoring",{reason:e});return}if(lx=!0,Iv+=1,q2=!0,dt.warn("speech","respawnWorker: starting",{reason:e,attempt:Iv}),ax({reason:e,respawned:!1,finalOnly:!0}),Iv>H_){if(Bh=!0,dt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:H_}),gi)try{gi.terminate()}catch{}gi=null,wa=!1,Xs=!1,ax({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),lx=!1;return}if(gi)try{gi.terminate()}catch{}gi=null,wa=!1,Xs=!1;try{gi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),V2(gi),Xs=!0,gi.postMessage({type:"load"}),dt.info("speech","respawnWorker: new worker spawned, load posted"),ax({reason:e,respawned:!0,finalOnly:!0})}catch(n){Bh=!0,dt.error("speech","respawnWorker: spawn failed, disabling speech",{error:n instanceof Error?n.message:String(n)}),ax({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{lx=!1}}}function kT(e,n){if(wa||Xs)return;Xs=!0;const r=fy();dt.info("speech","preloadModel: posting load");const i=o=>{o.data.type==="status"?(e==null||e(o.data.status,o.data.message),o.data.status==="ready"&&(wa=!0,Xs=!1,dt.info("speech","preloadModel: ready"),r.removeEventListener("message",i))):o.data.type==="progress"?n==null||n(o.data.pct):o.data.type==="error"&&(Xs=!1,dt.error("speech","preloadModel: worker reported error",{error:o.data.error}),e==null||e("error",o.data.error),r.removeEventListener("message",i))};r.addEventListener("message",i),r.postMessage({type:"load"})}function ST(){dt.info("speech","resetModel: clearing load flags"),wa=!1,Xs=!1}function Xy(){var e;return typeof Worker<"u"&&!!((e=navigator.mediaDevices)!=null&&e.getUserMedia)&&typeof AudioWorkletNode<"u"}function CT(e){const n=fy();return!wa&&!Xs&&(Xs=!0,n.postMessage({type:"load"})),new Promise((r,i)=>{const o=l=>{var d,u,h;((d=l.data)==null?void 0:d.type)==="result"?(n.removeEventListener("message",o),r((l.data.text??"").trim())):((u=l.data)==null?void 0:u.type)==="error"?(n.removeEventListener("message",o),i(new Error(String(l.data.error??"Transcription failed")))):((h=l.data)==null?void 0:h.type)==="status"&&l.data.status==="ready"&&(wa=!0,Xs=!1)};n.addEventListener("message",o),n.postMessage({type:"transcribe",audio:e},[e.buffer])})}function G2(e){let n=fy(),r=!1,i=null,o=null,l=null,d=null,u=null;const h=[],m=new Set;let x=null,g=0,v=!1,S=0,E=!1,j=!1,y=0,b=0,_=0,C=-1,N=O_,$=0,R=null,O="",I="",z=!1,U=0;function W(ce,pe){const Ae=Math.min(ce.length,pe.length);let Se=0;for(;Se<Ae&&ce.charCodeAt(Se)===pe.charCodeAt(Se);)Se++;return Se}function Y(ce){const pe=W(O,ce);return O=ce,pe>I.length&&(I=ce.slice(0,pe)),I.length>ce.length&&(I=ce),I}const V=()=>(x||(x=new Float32Array(Ch)),x),H=()=>{g=0},te=ce=>{const pe=V(),Ae=ce.length;if(Ae>=Ch){pe.set(ce.subarray(Ae-Ch)),g=Ch;return}if(g+Ae<=Ch){pe.set(ce,g),g+=Ae;return}const Se=g+Ae-Ch;pe.copyWithin(0,Se,g),g-=Se,pe.set(ce,g),g+=Ae},ae=()=>{R&&(clearTimeout(R),R=null)},oe=()=>{ae(),v=!1,E=!1,j=!1,N=O_,O="",I="",z=!1,U=0,H()},ie=()=>{if(r||!v||j||E||R)return;if(g<bT){R=setTimeout(()=>{R=null,ie()},N);return}const ce=performance.now()-y;if(ce<N&&y!==0){R=setTimeout(()=>{R=null,ie()},N-ce);return}if(q2||Bh||e.partialsEnabled&&!e.partialsEnabled())return;const pe=V(),Ae=new Float32Array(g);Ae.set(pe.subarray(0,g)),b+=1,_=b,E=!0,$=performance.now(),y=$,n.postMessage({type:"transcribe-partial",audio:Ae,seq:b},[Ae.buffer])},X=ce=>ce.length===0?Promise.resolve():Bh?(dt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),r||e.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(pe=>{h.push(pe),b+=1;const Ae=b;C=Ae,n.postMessage({type:"transcribe",audio:ce,seq:Ae},[ce.buffer])}),Q=ce=>{const pe=X(ce);return m.add(pe),pe.finally(()=>{m.delete(pe)}),pe},J=ce=>{var pe,Ae,Se,ye,ne;if(ce.data.type==="result"){const we=ce.data.text,Ne=ce.data.seq??0;Ne&&Ne<C&&dt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ne,latestFinalSeq:C}),!r&&we&&e.onFinal(we),(pe=h.shift())==null||pe()}else if(ce.data.type==="partial"){const we=ce.data.seq??0,Ne=ce.data.text??"",Je=performance.now()-$;E=!1,Je>=B_?(j=!0,dt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Je),seq:we})):Je>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Je),newIntervalMs:N,seq:we})),z||(z=!0,Je>wT&&N<500&&(N=500,dt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Je),newIntervalMs:500})));const lt=we!==_||we<=C;if(!r&&!lt&&Ne){const xt=Y(Ne);xt&&((Ae=e.onPartial)==null||Ae.call(e,xt),U===0&&(U=performance.now(),dt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-S)})))}ie()}else if(ce.data.type==="partial-error"){const we=performance.now()-$;E=!1,we>=B_?(j=!0,dt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ce.data.seq})):we>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:N,seq:ce.data.seq})),dt.warn("speech","partial encode failed",{error:ce.data.error,seq:ce.data.seq}),ie()}else ce.data.type==="error"?(r||e.onError(ce.data.error),(Se=h.shift())==null||Se()):ce.data.type==="status"?(r||(ye=e.onModelStatus)==null||ye.call(e,ce.data.status,ce.data.message),ce.data.status==="ready"&&(wa=!0,Xs=!1)):ce.data.type==="progress"&&(r||(ne=e.onProgress)==null||ne.call(e,ce.data.pct))};n.addEventListener("message",J);const le=ce=>{var pe,Ae;if(!r){for(dt.warn("speech","createRecognition: worker death event",ce),(pe=e.onStatusChange)==null||pe.call(e,"restarting");h.length;)(Ae=h.shift())==null||Ae();if(m.clear(),ae(),E=!1,ce.respawned){try{n.removeEventListener("message",J)}catch{}n=fy(),n.addEventListener("message",J)}}};return Bb.add(le),{start:async()=>{if(!r){if(Bh){e.onError("Speech recognition disabled — please reload the app.");return}!wa&&!Xs&&(Xs=!0,dt.info("speech","createRecognition.start: triggering model load"),n.postMessage({type:"load"})),dt.info("speech","createRecognition.start: initializing VAD",{modelReady:wa,modelLoading:Xs});try{const ce=new URL("vad/",document.baseURI).href,pe=e.inputDeviceId||null,Ae={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};pe&&(Ae.deviceId={exact:pe}),dt.info("speech","getUserMedia",{hasDeviceId:!!pe,deviceIdPrefix:pe?pe.slice(0,8):null});const Se=await navigator.mediaDevices.getUserMedia({audio:Ae});o=Se,l=new AudioContext;for(const ye of Se.getAudioTracks())ye.addEventListener("ended",()=>{r||(dt.warn("speech","mic track ended (permission revoked or device removed)"),e.onError("Microphone disconnected or permission revoked"))});try{u=l.createMediaStreamSource(o),d=l.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,u.connect(d)}catch(ye){dt.warn("speech","analyser init failed",{error:ye instanceof Error?ye.message:String(ye)}),u=null,d=null}i=await xT.MicVAD.new({audioContext:l,getStream:async()=>Se,resumeStream:async()=>Se,pauseStream:async()=>{},baseAssetPath:ce,onnxWASMBasePath:ce,model:"v5",positiveSpeechThreshold:H2,negativeSpeechThreshold:W2,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ye,ne)=>{var we;r||((we=e.onFrame)==null||we.call(e,ye),v&&(te(ne),ie()))},onSpeechStart:()=>{var ye;r||(oe(),v=!0,S=performance.now(),(ye=e.onSpeechStart)==null||ye.call(e))},onSpeechEnd:ye=>{var ne;r||((ne=e.onStatusChange)==null||ne.call(e,"transcribing"),oe(),Q(ye))},onVADMisfire:()=>{var ye,ne;r||((ye=e.onStatusChange)==null||ye.call(e,"idle"),oe(),(ne=e.onMisfire)==null||ne.call(e))}}),i.start()}catch(ce){const pe=ce instanceof Error?ce.message:"Microphone access denied",Ae=ce instanceof Error?ce.stack:"";if(dt.error("speech","createRecognition.start: VAD init failed",{error:pe,stack:Ae}),d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(Se=>Se.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}e.onError(pe)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(oe();m.size>0;)await Promise.all(Array.from(m));if(i){try{await i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ce,pe)=>{if(i)try{i.setOptions({positiveSpeechThreshold:ce,negativeSpeechThreshold:pe})}catch(Ae){dt.warn("speech","setVadThresholds failed",{error:Ae instanceof Error?Ae.message:String(Ae)})}},getAnalyser:()=>d,destroy:()=>{if(r=!0,oe(),i){try{i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.close()}catch{}l=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}Bb.delete(le),n.removeEventListener("message",J)}}}let Am=null;const Fb=new Set,Ub=new Set;function jT(){for(const e of Fb)try{e()}catch{}}function Hb(){for(const e of Ub)try{e()}catch{}}function ET(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function NT(e){if(!window.speechSynthesis)return;const n=ET(e);if(!n)return;const r=new SpeechSynthesisUtterance(n);r.rate=1,r.pitch=1,r.onstart=()=>{Am=performance.now(),jT()},r.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},r.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},window.speechSynthesis.speak(r)}function K2(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Am=null,Hb())}function X2(){var e;return((e=window.speechSynthesis)==null?void 0:e.speaking)??!1}function TT(){return Am}function $T(e){return Fb.add(e),()=>{Fb.delete(e)}}function AT(e){return Ub.add(e),()=>{Ub.delete(e)}}function RT(e){X2()&&(e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const n=$T(()=>{e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on")}),r=AT(()=>{e.setVadThresholds(H2,W2),dt.info("voice","tts.duck.off")});return()=>{n(),r()}}const MT=[{match:/^(send|submit|enter)\.?$/i,data:"\r",label:"send"},{match:/^(cancel|escape)\.?$/i,data:"\x1B",label:"cancel"},{match:/^clear( line)?\.?$/i,data:"",label:"clear"}];function IT(e){const n=e.trim();return MT.find(r=>r.match.test(n))??null}const PT=4e4;let Tu=null;function Fh(){Tu&&clearTimeout(Tu),Tu=setTimeout(()=>{Tu=null,$t.getState().stopRecording()},PT)}function cx(){Tu&&(clearTimeout(Tu),Tu=null)}let mc=null,fc=null;const DT=.04,OT=.3;let py=0,Wb=0;function LT(e){fc!==null&&cancelAnimationFrame(fc);const n=()=>{if(mc===null||$t.getState().submitCountdownStartAt===null){fc=null;return}const r=performance.now();if(r-Wb<200&&py>OT){const o=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:py.toFixed(2),msIntoCountdown:Math.round(o)}),lc(),Fh();return}const i=Y2();if(i){const o=new Uint8Array(i.fftSize);i.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const d=Math.sqrt(l/o.length);if(d>DT){const u=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(u)}),lc(),Fh();return}}fc=requestAnimationFrame(n)};fc=requestAnimationFrame(n)}function zT(e){mc&&clearTimeout(mc);const n=$t.getState().submitDelayMs,r=performance.now();$t.setState({submitCountdownStartAt:r}),mc=setTimeout(()=>{mc=null,$t.setState({submitCountdownStartAt:null});try{window.api.pty.write({tabId:e,data:"\r"})}catch(i){dt.warn("voice","submit pty.write failed",{error:i instanceof Error?i.message:String(i)})}Fh()},n),LT(r)}function lc(){fc!==null&&(cancelAnimationFrame(fc),fc=null),mc&&(clearTimeout(mc),mc=null),$t.getState().submitCountdownStartAt!==null&&$t.setState({submitCountdownStartAt:null})}let rs=null,As=null;function Y2(){var e;return((e=rs==null?void 0:rs.getAnalyser)==null?void 0:e.call(rs))??null}const ux=1e4;let Rm=null;function dx(){Rm&&(clearTimeout(Rm),Rm=null)}let Yx=null,Jx=null;function hx(){Yx=null,Jx&&(Jx(),Jx=null)}const BT=1500,FT=9e4;let fx=0,Qx=null,qb=-1;function px(){Qx&&(clearTimeout(Qx),Qx=null,qb=-1)}const UT=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),$t=cr((e,n)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(n().modelStatus!=="idle")return;dt.info("voice","initModel: kicking off preload"),e({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const r=++fx,i=()=>{r===fx&&(px(),qb=r,Qx=setTimeout(()=>{qb===r&&n().modelStatus==="loading"&&(dt.warn("voice","mic.gate.timeout: no progress within 90s"),e({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},FT))};i(),kT((o,l)=>{r===fx&&(o==="ready"?(px(),dt.info("voice","modelStatus -> ready"),e({modelStatus:"ready",loadingProgress:100,errorKind:null})):o==="error"?(px(),dt.error("voice","modelStatus -> error",{msg:l}),e({modelStatus:"error",error:l,errorKind:"load"})):(i(),e({modelStatus:"loading"})))},o=>{r===fx&&(i(),e({loadingProgress:Math.round(o)}))})},resetAndRetryModel:()=>{dt.info("voice","mic.gate.retry"),px(),ST(),e({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),n().initModel()},startRecording:r=>{if(n().isRecording)return;if(rs){dt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Xy()){e({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const i=o=>{try{const l=G2({inputDeviceId:o,onStatusChange:d=>{e(d==="transcribing"?{statusPill:"transcribing"}:d==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:d=>{n().partialsEnabled&&e({lastPartial:d})},partialsEnabled:()=>n().partialsEnabled,onFrame:d=>{py=d.isSpeech,Wb=performance.now()},onSpeechStart:()=>{if(e({statusPill:"listening",lastPartial:""}),cx(),lc(),X2()){const u=TT(),h=u!==null?performance.now()-u:null;K2(),e({lastBargeInAt:performance.now()}),dt.info("voice","barge-in",{tabId:r,utteranceOffsetMs:h})}else dt.debug("voice","barge-in.no-op",{tabId:r})},onMisfire:()=>{e({lastPartial:"",statusPill:"idle"}),Fh();const d=n().lastBargeInAt;d!==null&&performance.now()-d<600&&dt.warn("voice","barge-in.misfire",{tabId:r,sinceBargeInMs:Math.round(performance.now()-d)})},onFinal:d=>{Fh();const u=d.trim();if(!u||UT.has(u)){e({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}const h=IT(u);if(h){dt.info("voice","voice-command",{tabId:r,label:h.label,transcript:u}),window.api.pty.write({tabId:r,data:h.data}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),lc();const x=window;x.__transcripts&&(x.__transcripts.push({tabId:r,text:u}),x.__transcripts.length>500&&x.__transcripts.shift());return}window.api.pty.write({tabId:r,data:u}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),n().autoSubmit&&zT(r);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:r,text:u}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:d=>{dt.error("voice","recognition error",{err:d}),lc(),e({error:d,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),As==null||As(),As=null,cx(),rs==null||rs.destroy(),rs=null,Le.error(`Microphone error: ${d}`)},onModelStatus:d=>{d==="ready"?e({modelStatus:"ready",loadingProgress:100}):d==="loading"&&e({modelStatus:"loading"})},onProgress:d=>e({loadingProgress:Math.round(d)})});rs=l,e({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Fh(),l.start().then(()=>{rs===l&&(As==null||As(),As=RT(l))}).catch(d=>{const u=d instanceof Error?d.message:String(d);dt.error("voice","handle.start() failed",{error:u}),Le.error(`Could not start mic: ${u}`)})}catch(l){e({error:l instanceof Error?l.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var o,l,d;return((d=(l=(o=window.api)==null?void 0:o.voice)==null?void 0:l.getDevicePref)==null?void 0:d.call(l))??Promise.resolve(null)}).then(o=>i((o==null?void 0:o.selectedDeviceId)??null)).catch(o=>{dt.warn("voice","getDevicePref failed; using default device",{error:o instanceof Error?o.message:String(o)}),i(null)})},stopRecording:()=>{const r=rs;r&&(cx(),lc(),py=0,Wb=0,As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),r.stop().finally(()=>{r.destroy(),rs===r&&(rs=null),n().hotkeyState==="stopping"&&(dx(),e({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!n().isRecording)return;const r=rs;if(!r)return;cx(),As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:""});try{await r.stop()}catch(l){dt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}r.destroy(),rs===r&&(rs=null);const{useSessions:i}=await Jm(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>GN);return{useSessions:l}},[],import.meta.url),o=i.getState().activeTabId;o&&n().startRecording(o)},setExternalRecording:r=>e({externalRecording:r}),toggleTTS:()=>e(r=>({ttsEnabled:!r.ttsEnabled})),setAutoSubmit:r=>e({autoSubmit:r}),setSubmitDelayMs:r=>e({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(r)))}),cancelSubmit:()=>lc(),setPartialsEnabled:r=>{n().partialsEnabled!==r&&(e({partialsEnabled:r}),r||e({lastPartial:""}))},clearError:()=>e({error:null,errorKind:null}),setPermissionState:r=>{n().permissionState!==r&&(dt.info("voice","mic.gate.permission_changed",{from:n().permissionState,to:r}),e({permissionState:r}))},setLevelMeterEnabled:r=>{n().levelMeterEnabled!==r&&e({levelMeterEnabled:r})},setTurnDetectorRuntimeState:r=>{n().turnDetectorState!==r&&(e({turnDetectorState:r}),r==="load_failed"?dt.warn("voice-turn","voice-turn.load_failed"):r==="runtime_error"?dt.warn("voice-turn","voice-turn.runtime_error"):r==="disabled"&&dt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:r=>{n().wizardArmed!==r&&e({wizardArmed:r})},openWizard:()=>{n().wizardOpen||e({wizardOpen:!0})},closeWizard:()=>{n().wizardOpen&&e({wizardOpen:!1})},armHotkey:({phase:r,source:i,mode:o,tabId:l})=>{const d=n(),{canRecord:u,reason:h}=Vb(d);if(r==="down"){if(h==="error"||h==="load-timeout"){d.resetAndRetryModel(),dt.info("voice-hotkey","down.retry",{source:i,reason:h});return}if(!u&&h!=="loading"){dt.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:h});return}if(d.hotkeyState==="recording"||d.isRecording){(o==="toggle"||i==="global")&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording());return}if(h==="loading"){d.hotkeyState!=="armed"&&(e({hotkeyState:"armed"}),dt.info("voice-hotkey","armed",{source:i,modelStatus:d.modelStatus})),hx(),Yx={tabId:l,source:i,mode:o},Jx=$t.subscribe((m,x)=>{if(Yx&&m.modelStatus==="ready"&&x.modelStatus!=="ready"&&m.hotkeyState==="armed"){const g=Yx;if(hx(),!g.tabId){dt.warn("voice-hotkey","armed-promote-no-tab",{source:g.source}),e({hotkeyState:"idle"});return}dt.info("voice-hotkey","armed-promote",g),e({hotkeyState:"recording"}),$t.getState().startRecording(g.tabId)}});return}if(!l){dt.warn("voice-hotkey","no-active-tab",{source:i});return}dt.info("voice-hotkey","start",{source:i,mode:o,tabId:l}),d.startRecording(l),n().isRecording?e({hotkeyState:"recording"}):(dt.warn("voice-hotkey","start: recording did not engage",{errorKind:n().errorKind}),e({hotkeyState:"idle"}));return}if(!(o!=="hold"||i==="global")){if(d.hotkeyState==="armed"){hx(),dt.info("voice-hotkey","miss-model-loading-armed-up"),e({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording())}},destroyHotkey:()=>{const r=n();if(hx(),lc(),r.hotkeyState==="recording"){dt.warn("voice-hotkey","destroyed-mid-recording"),e({hotkeyState:"destroyed"});try{r.stopRecording()}catch{}}else(r.hotkeyState==="armed"||r.hotkeyState==="stopping")&&(dx(),e({hotkeyState:"destroyed"}))}})),HT=e=>({isRecording:e.isRecording,statusPill:e.statusPill,lastPartial:e.lastPartial,lastTranscript:e.lastTranscript,submitCountdownStartAt:e.submitCountdownStartAt}),Vb=e=>Xy()?e.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:e.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:e.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:e.modelStatus==="error"?{canRecord:!1,reason:e.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const e=window;e.__voice=$t,e.__transcripts=[]}function t0(e,n,r){return new Promise((i,o)=>{const l=setTimeout(()=>o(new Error(`${r} timed out after ${n}ms`)),n);e.then(d=>{clearTimeout(l),i(d)},d=>{clearTimeout(l),o(d)})})}const WT=5e3,vc=cr(()=>({snapshot:null,loaded:!1}));let W_=!1,q_=!1,Kp;async function qT(){var e;if(!W_){W_=!0;try{const n=await t0(window.api.schedule.state(),WT,"schedule.state");vc.setState({snapshot:n,loaded:!0}),Kp=((e=n.paused)==null?void 0:e.reason)??null}catch(n){if(!q_){q_=!0;const r=n instanceof Error?n.message:String(n);Le.error(`Scheduler state hydrate failed: ${r}`)}Kp=null}window.api.schedule.onState(n=>{var i;const r=((i=n.paused)==null?void 0:i.reason)??null;Kp!==void 0&&r!==Kp&&(r==="auth"?Le.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):r==="network"&&Le.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Kp=r,vc.setState({snapshot:n,loaded:!0})})}}const VT=6e4,GT=5e3,Uh=cr(()=>({data:null,refreshing:!1}));let V_=!1,Zx=null,G_=null,K_=!1;async function n0(){Uh.setState({refreshing:!0});let e=VT;try{const n=await t0(window.api.billing.fetch(),GT,"billing.fetch");Uh.setState({data:n,refreshing:!1}),n.kind==="transient"?e=G_==="transient"?3e4:5e3:(n.kind==="auth"||n.kind==="meter_rate_limited")&&(e=3e4),G_=n.kind}catch(n){if(Uh.setState({refreshing:!1}),!K_){K_=!0;const r=n instanceof Error?n.message:String(n);Le.warn(`Billing usage fetch failed: ${r}`)}}Zx=setTimeout(n0,e)}function KT(){V_||(V_=!0,n0())}function Yy(e){return e?e.kind==="ok"||e.kind==="ok-stale"?e.data:(e.kind==="auth"||e.kind==="meter_rate_limited")&&e.cached?e.cached:null:null}function my(){Zx!==null&&(clearTimeout(Zx),Zx=null),n0()}function dn({name:e,size:n=17,stroke:r=1.6,className:i}){const o={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",className:i};switch(e){case"home":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 11l8-7 8 7"}),s.jsx("path",{d:"M6 10v9h12v-9"}),s.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 10l3 2-3 2"}),s.jsx("path",{d:"M13 14h4"})]});case"agents":case"subagents":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"7",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"17",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("path",{d:"M8.6 11l2.8 4M15.4 11l-2.8 4M9.5 9h5"})]});case"skills":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"}),s.jsx("path",{d:"M4 6l2 2"})]});case"usage":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"hive":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M8 4h8l4 7-4 7H8l-4-7z"}),s.jsx("circle",{cx:"12",cy:"11",r:"2.5"})]});case"plugins":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),s.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),s.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),s.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),s.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"8",cy:"12",r:"4"}),s.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"plans":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),s.jsx("path",{d:"M8 9h8M8 13h8M8 17h5"})]});case"tasks":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"7",height:"7",rx:"1.5"}),s.jsx("path",{d:"M14 6h7M14 10h5M14 15h7M14 19h5"})]});case"projects":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),s.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"11",cy:"11",r:"6"}),s.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l4 4v14H7z"}),s.jsx("path",{d:"M14 3v4h4"})]});case"play":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),s.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),s.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),s.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),s.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"orchestrator":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"6",r:"2.5"}),s.jsx("circle",{cx:"5",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"19",cy:"17",r:"2.5"}),s.jsx("path",{d:"M12 8.5v6M12 14.5l-7 0M12 14.5l7 0"})]});case"race":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 4v16M5 5h7l-1 3h7v6h-7l-1 3H5"})});case"background":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M3 4h18v4H3zM3 10h18v4H3zM3 16h18v4H3z"}),s.jsx("circle",{cx:"6",cy:"6",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"12",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:".75",fill:"currentColor",stroke:"none"})]});case"repoviz":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"6",cy:"12",r:"3"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"18",cy:"18",r:"3"}),s.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),s.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),s.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),s.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M9 12h6"}),s.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),s.jsx("path",{d:"M4 12h16"})]});case"target":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),s.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),s.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),s.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return s.jsx("svg",{...o,children:s.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14"})});default:return null}}function XT(e,n={}){switch(e){case"ready":return n.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof n.loadingPct=="number"?Math.round(n.loadingPct):0} percent`;case"error":return n.errorMessage?`Microphone — speech model error: ${n.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const X_=e=>Symbol.iterator in e,Y_=e=>"entries"in e,J_=(e,n)=>{const r=e instanceof Map?e:new Map(e.entries()),i=n instanceof Map?n:new Map(n.entries());if(r.size!==i.size)return!1;for(const[o,l]of r)if(!i.has(o)||!Object.is(l,i.get(o)))return!1;return!0},YT=(e,n)=>{const r=e[Symbol.iterator](),i=n[Symbol.iterator]();let o=r.next(),l=i.next();for(;!o.done&&!l.done;){if(!Object.is(o.value,l.value))return!1;o=r.next(),l=i.next()}return!!o.done&&!!l.done};function JT(e,n){return Object.is(e,n)?!0:typeof e!="object"||e===null||typeof n!="object"||n===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(n)?!1:X_(e)&&X_(n)?Y_(e)&&Y_(n)?J_(e,n):YT(e,n):J_({entries:()=>Object.entries(e)},{entries:()=>Object.entries(n)})}function J2(e){const n=co.useRef(void 0);return r=>{const i=e(r);return JT(n.current,i)?n.current:n.current=i}}let Q_=0;const QT=1e3;function ZT(e){const n=performance.now();n-Q_<QT||(Q_=n,dt.debug("voice","mic.gate.click_rejected",{reason:e}))}function Q2(){const e=$t(m=>m.isRecording),n=$t(m=>m.error),r=$t(m=>m.loadingProgress),i=$t(J2(Vb)),o=()=>{const m=$t.getState(),{canRecord:x,reason:g}=Vb(m);if(m.isRecording)return m.stopRecording();if(m.wizardArmed&&!m.wizardOpen){m.openWizard();return}if(g==="error"||g==="load-timeout"){m.resetAndRetryModel();return}if(!x)return ZT(g);const v=vt.getState().activeTabId;v&&m.startRecording(v)},l=XT(i.reason,{loadingPct:r,errorMessage:n,isRecording:e}),d=i.reason==="unsupported",u=!i.canRecord,h=i.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":i.reason==="error"||i.reason==="load-timeout"?"text-red-400 cursor-pointer":i.reason==="permission-denied"?"text-amber-400 cursor-pointer":i.reason==="idle"?"text-fg-faint cursor-pointer":i.reason==="unsupported"?"text-fg-faint cursor-not-allowed":e?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return s.jsx("button",{onClick:o,disabled:d,"aria-disabled":u,"aria-label":l,title:l,"data-testid":"mic-button","data-state":i.reason,className:`p-1.5 rounded transition-colors ${h}`,children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function e$(){const e=$t(r=>r.ttsEnabled),n=$t(r=>r.toggleTTS);return s.jsxs("button",{onClick:n,title:e?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${e?"text-accent":"text-fg-dim hover:text-fg"}`,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),s.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),s.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Zm(e){if(!e||e==="—"||e==="unknown")return e;const n=/\[(\dm)\]/.exec(e),r=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(e);if(!r)return e;const i=r[1].charAt(0).toUpperCase()+r[1].slice(1).toLowerCase(),o=r[3]?`${r[2]}.${r[3]}`:r[2];return n?`${i} ${o} ${n[1]}`:`${i} ${o}`}const mx=new Map,t$=3e4;function Z2(e){const[n,r]=L.useState(()=>{var i;return e?((i=mx.get(e))==null?void 0:i.value)??null:null});return L.useEffect(()=>{if(!e){r(null);return}let i=!1;return(async()=>{const l=mx.get(e);if(l&&Date.now()-l.ts<t$){i||r(l.value);return}try{const d=await window.api.app.gitBranch(e);if(i)return;mx.set(e,{value:d,ts:Date.now()}),r(d)}catch{if(i)return;mx.set(e,{value:null,ts:Date.now()}),r(null)}})(),()=>{i=!0}},[e]),n}const Jy=[{key:"overview",group:"Workspace",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",group:"Workspace",label:"Terminal",icon:"terminal",hint:"Live Claude Code, in-app"},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences"},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project"},{key:"subagents",group:"Workspace",label:"Subagents",icon:"hive",liveKind:"subagents",hint:"Fan out work: Hive · Orchestrate · Race · Boss"},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"usage",group:"Workspace",label:"Usage",icon:"usage",hint:"Tokens, cost, sessions per day"},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],n$=Object.fromEntries(Jy.map(e=>[e.key,e.group])),Pv={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},Z_=Jy.filter(e=>e.group==="Workspace"),e1=Jy.filter(e=>e.group==="Configure"),t1=Jy.filter(e=>e.group==="Tools").map(({key:e,label:n,icon:r,hint:i})=>({key:e,label:n,icon:r,hint:i})),Gb="sm.almanac.sidebarWidth",eC=180,tC=480,Kb=252;function r$(){try{const e=parseInt(localStorage.getItem(Gb)??"",10);if(Number.isFinite(e))return Math.min(tC,Math.max(eC,e))}catch{}return Kb}const s$=52,nC="sm.almanac.sidebarCollapsed";function i$(){try{return localStorage.getItem(nC)==="1"}catch{}return!1}const rC="sm.almanac.collapsedGroups";function o$(){try{const e=localStorage.getItem(rC);if(!e)return new Set;const n=JSON.parse(e);return Array.isArray(n)?new Set(n.filter(r=>r==="Workspace"||r==="Configure"||r==="Tools")):new Set}catch{return new Set}}function a$(){const e=$m(l=>l.tabs),n=vc(l=>{var d;return(((d=l.snapshot)==null?void 0:d.jobs)??[]).some(u=>u.status==="running")}),[r,i]=L.useState(()=>Date.now());return L.useEffect(()=>{const l=setInterval(()=>i(Date.now()),5e3);return()=>clearInterval(l)},[]),{subagents:Object.values(e).some(l=>l.agents.some(d=>r-d.at<6e4)),scheduler:n}}function l$({active:e,onNavigate:n,onNewSession:r}){const[i,o]=L.useState(()=>o$()),l=L.useCallback(_=>{o(C=>{const N=new Set(C);N.has(_)?N.delete(_):N.add(_);try{localStorage.setItem(rC,JSON.stringify(Array.from(N)))}catch{}return N})},[]),[d,u]=L.useState(()=>i$()),h=L.useCallback(()=>{u(_=>{const C=!_;try{localStorage.setItem(nC,C?"1":"0")}catch{}return C})},[]),m=vt(_=>_.tabs),x=vt(_=>_.activeTabId),g=m.find(_=>_.id===x)??null,v=a$(),[S,E]=L.useState(()=>r$()),j=L.useRef(S);j.current=S;const y=L.useCallback(_=>{_.preventDefault();const C=_.clientX,N=j.current;let $=N;const R=I=>{$=Math.min(tC,Math.max(eC,N+(I.clientX-C))),E($)},O=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",O),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Gb,String($))}catch{}};window.addEventListener("pointermove",R),window.addEventListener("pointerup",O),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),b=L.useCallback(()=>{E(Kb);try{localStorage.setItem(Gb,String(Kb))}catch{}},[]);return s.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?s$:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[s.jsx(c$,{tab:g,onNewSession:r,rail:d,onToggleRail:h}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:s.jsxs(s.Fragment,{children:[!d&&s.jsx(Dv,{label:"Workspace",desc:Pv.Workspace,collapsed:i.has("Workspace"),count:Z_.length,onToggle:()=>l("Workspace")}),(d||!i.has("Workspace"))&&Z_.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:_.liveKind?v[_.liveKind]:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Configure",desc:Pv.Configure,collapsed:i.has("Configure"),count:e1.length,onToggle:()=>l("Configure")}),(d||!i.has("Configure"))&&e1.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Tools",desc:Pv.Tools,collapsed:i.has("Tools"),count:t1.length,onToggle:()=>l("Tools")}),(d||!i.has("Tools"))&&t1.map(_=>s.jsx(u$,{tool:_,active:e===_.key,onClick:()=>n(_.key),rail:d},_.key))]})}),s.jsx(d$,{rail:d}),!d&&s.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:y,onDoubleClick:b,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function c$({tab:e,onNewSession:n,rail:r,onToggleRail:i}){const o=(e==null?void 0:e.label)??"no session",l=Z2((e==null?void 0:e.cwd)??null);return r?s.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[s.jsx("button",{onClick:n,"data-testid":"tour-new-session",title:"New session",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:s.jsx(dn,{name:"plus",size:15,stroke:1.8})}),s.jsx("button",{onClick:i,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:s.jsx(dn,{name:"chevron",size:15,stroke:1.8})})})]}):s.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),s.jsx("button",{onClick:i,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:s.jsx(dn,{name:"chevron",size:13,stroke:1.8})})})]}),s.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[s.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),s.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(e==null?void 0:e.cwd)??"",children:o})]}),s.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:l?`⌥${l}`:e?e.cwd:"—"}),s.jsxs("div",{className:"mt-3 flex items-stretch gap-1.5",children:[s.jsxs("button",{onClick:n,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[s.jsx(dn,{name:"plus",size:13,stroke:1.8}),"New session"]}),s.jsx("div",{className:"flex items-center rounded-md bg-bg-hi border border-line",children:s.jsx(Q2,{})})]})]})}function Dv({label:e,desc:n,collapsed:r,count:i,onToggle:o}){return s.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[s.jsxs("button",{onClick:o,"aria-expanded":!r,title:r?`Expand ${e}`:`Collapse ${e}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[s.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:r?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),s.jsx("span",{className:"flex-1",children:e}),r&&s.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]}),!r&&s.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:n})]})}function n1({item:e,active:n,live:r,onClick:i,rail:o}){return s.jsxs("button",{onClick:i,title:e.hint,"data-testid":e.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${o?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${n?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${o?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:17,stroke:1.6})}),!o&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]}),!o&&r&&s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),o&&r&&s.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function u$({tool:e,active:n,onClick:r,rail:i}){return s.jsxs("button",{onClick:r,title:e.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${i?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${n?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${i?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:15,stroke:1.6})}),!i&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]})]})}function d$({rail:e}){const n=$t(u=>u.isRecording),r=vt(u=>u.tabs),i=vt(u=>u.activeTabId),o=r.find(u=>u.id===i)??null,[l,d]=L.useState(null);return L.useEffect(()=>{let u=!1;if(!(o!=null&&o.presetId)){d(null);return}return C2(o.presetId).then(h=>{u||d((h==null?void 0:h.model)??null)}).catch(()=>{u||d(null)}),()=>{u=!0}},[o==null?void 0:o.presetId]),e?s.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"})}):s.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"}),s.jsx("span",{className:"truncate",title:l??"",children:n?"recording…":l?`Claude · ${Zm(l)}`:"Claude Code"})]})}function h$({onNavigate:e}){const n=vt(C=>C.tabs),r=vt(C=>C.activeTabId),i=n.find(C=>C.id===r)??null,o=P2(i),l=(o==null?void 0:o.lastEventAt)??0,d=Uh(C=>C.data),u=vc(C=>{var N;return((N=C.snapshot)==null?void 0:N.paused)??null}),h=Z2((i==null?void 0:i.cwd)??null),[,m]=L.useState(0);L.useEffect(()=>{const C=setInterval(()=>m(N=>N+1),6e4);return()=>clearInterval(C)},[]);const x=(o==null?void 0:o.todos)??[],[g,v]=L.useState(!1),S=L.useRef(null);L.useEffect(()=>{if(!g)return;const C=N=>{S.current&&!S.current.contains(N.target)&&v(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g]),L.useEffect(()=>{x.length===0&&v(!1)},[x.length]);const E=Yy(d),j=(E==null?void 0:E.usage.five_hour)??null,y=j?Math.round(j.utilization):null,b=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",_=l>0?m$(Date.now()-l):"—";return s.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[s.jsxs("button",{onClick:()=>e==null?void 0:e("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:b?"Connected to Anthropic":"Disconnected",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${b?"bg-sage":"bg-fg-faint"}`}),s.jsx("span",{children:b?"connected":"offline"})]}),s.jsx("button",{onClick:()=>e==null?void 0:e("usage"),className:"hover:text-fg transition-colors",title:"Open Usage",children:y!=null?`${y}% of 5h window used`:"5h —"}),u&&s.jsxs("button",{onClick:()=>e==null?void 0:e("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${u.reason==="auth"||u.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",u.reason]}),i&&s.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,h&&s.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",h]})]}),s.jsxs("span",{className:"text-fg-faint",children:["last activity: ",s.jsx("span",{className:"text-fg-dim",children:_})]}),x.length>0&&s.jsx(f$,{ref:S,todos:x,open:g,onToggle:()=>v(C=>!C)}),s.jsx("span",{className:"flex-1"}),s.jsxs("span",{className:"text-fg-faint",children:["v","0.38.4"]})]})}const f$=L.forwardRef(function({todos:n,open:r,onToggle:i},o){const l={completed:n.filter(d=>d.status==="completed").length,in_progress:n.filter(d=>d.status==="in_progress").length,pending:n.filter(d=>d.status==="pending").length};return s.jsxs("div",{ref:o,className:"relative",children:[s.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[s.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),s.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),s.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),s.jsxs("span",{className:"text-fg-faint",children:["todos ",r?"▾":"▴"]})]}),r&&s.jsx("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 z-50","data-testid":"footer-todos-popover",children:s.jsx("ul",{className:"space-y-0.5",children:n.map((d,u)=>s.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[s.jsx(p$,{status:d.status}),s.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},u))})})]})});function p$({status:e}){return e==="completed"?s.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):e==="in_progress"?s.jsx("span",{className:"w-3 shrink-0",children:s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function m$(e){const n=Math.max(0,Math.floor(e/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}var Ov={exports:{}},r1;function g$(){return r1||(r1=1,(function(e,n){(function(r,i){e.exports=i()})(globalThis,(()=>(()=>{var r={4567:function(d,u,h){var m=this&&this.__decorate||function(_,C,N,$){var R,O=arguments.length,I=O<3?C:$===null?$=Object.getOwnPropertyDescriptor(C,N):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(_,C,N,$);else for(var z=_.length-1;z>=0;z--)(R=_[z])&&(I=(O<3?R(I):O>3?R(C,N,I):R(C,N))||I);return O>3&&I&&Object.defineProperty(C,N,I),I},x=this&&this.__param||function(_,C){return function(N,$){C(N,$,_)}};Object.defineProperty(u,"__esModule",{value:!0}),u.AccessibilityManager=void 0;const g=h(9042),v=h(9924),S=h(844),E=h(4725),j=h(2585),y=h(3656);let b=u.AccessibilityManager=class extends S.Disposable{constructor(_,C,N,$){super(),this._terminal=_,this._coreBrowserService=N,this._renderService=$,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let R=0;R<this._terminal.rows;R++)this._rowElements[R]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[R]);if(this._topBoundaryFocusListener=R=>this._handleBoundaryFocus(R,0),this._bottomBoundaryFocusListener=R=>this._handleBoundaryFocus(R,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new v.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((R=>this._handleResize(R.rows)))),this.register(this._terminal.onRender((R=>this._refreshRows(R.start,R.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((R=>this._handleChar(R)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
2898
2898
|
`)))),this.register(this._terminal.onA11yTab((R=>this._handleTab(R)))),this.register(this._terminal.onKey((R=>this._handleKey(R.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,S.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(_){for(let C=0;C<_;C++)this._handleChar(" ")}_handleChar(_){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==_&&(this._charsToAnnounce+=_):this._charsToAnnounce+=_,_===`
|
|
2899
2899
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(_){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(_)||this._charsToConsume.push(_)}_refreshRows(_,C){this._liveRegionDebouncer.refresh(_,C,this._terminal.rows)}_renderRows(_,C){const N=this._terminal.buffer,$=N.lines.length.toString();for(let R=_;R<=C;R++){const O=N.lines.get(N.ydisp+R),I=[],z=(O==null?void 0:O.translateToString(!0,void 0,void 0,I))||"",U=(N.ydisp+R+1).toString(),W=this._rowElements[R];W&&(z.length===0?(W.innerText=" ",this._rowColumns.set(W,[0,1])):(W.textContent=z,this._rowColumns.set(W,I)),W.setAttribute("aria-posinset",U),W.setAttribute("aria-setsize",$))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(_,C){const N=_.target,$=this._rowElements[C===0?1:this._rowElements.length-2];if(N.getAttribute("aria-posinset")===(C===0?"1":`${this._terminal.buffer.lines.length}`)||_.relatedTarget!==$)return;let R,O;if(C===0?(R=N,O=this._rowElements.pop(),this._rowContainer.removeChild(O)):(R=this._rowElements.shift(),O=N,this._rowContainer.removeChild(R)),R.removeEventListener("focus",this._topBoundaryFocusListener),O.removeEventListener("focus",this._bottomBoundaryFocusListener),C===0){const I=this._createAccessibilityTreeNode();this._rowElements.unshift(I),this._rowContainer.insertAdjacentElement("afterbegin",I)}else{const I=this._createAccessibilityTreeNode();this._rowElements.push(I),this._rowContainer.appendChild(I)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(C===0?-1:1),this._rowElements[C===0?1:this._rowElements.length-2].focus(),_.preventDefault(),_.stopImmediatePropagation()}_handleSelectionChange(){var z;if(this._rowElements.length===0)return;const _=document.getSelection();if(!_)return;if(_.isCollapsed)return void(this._rowContainer.contains(_.anchorNode)&&this._terminal.clearSelection());if(!_.anchorNode||!_.focusNode)return void console.error("anchorNode and/or focusNode are null");let C={node:_.anchorNode,offset:_.anchorOffset},N={node:_.focusNode,offset:_.focusOffset};if((C.node.compareDocumentPosition(N.node)&Node.DOCUMENT_POSITION_PRECEDING||C.node===N.node&&C.offset>N.offset)&&([C,N]=[N,C]),C.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(C={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(C.node))return;const $=this._rowElements.slice(-1)[0];if(N.node.compareDocumentPosition($)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(N={node:$,offset:((z=$.textContent)==null?void 0:z.length)??0}),!this._rowContainer.contains(N.node))return;const R=({node:U,offset:W})=>{const Y=U instanceof Text?U.parentNode:U;let V=parseInt(Y==null?void 0:Y.getAttribute("aria-posinset"),10)-1;if(isNaN(V))return console.warn("row is invalid. Race condition?"),null;const H=this._rowColumns.get(Y);if(!H)return console.warn("columns is null. Race condition?"),null;let te=W<H.length?H[W]:H.slice(-1)[0]+1;return te>=this._terminal.cols&&(++V,te=0),{row:V,column:te}},O=R(C),I=R(N);if(O&&I){if(O.row>I.row||O.row===I.row&&O.column>=I.column)throw new Error("invalid range");this._terminal.select(O.column,O.row,(I.row-O.row)*this._terminal.cols-O.column+I.column)}}_handleResize(_){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let C=this._rowContainer.children.length;C<this._terminal.rows;C++)this._rowElements[C]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[C]);for(;this._rowElements.length>_;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const _=this._coreBrowserService.mainDocument.createElement("div");return _.setAttribute("role","listitem"),_.tabIndex=-1,this._refreshRowDimensions(_),_}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let _=0;_<this._terminal.rows;_++)this._refreshRowDimensions(this._rowElements[_])}}_refreshRowDimensions(_){_.style.height=`${this._renderService.dimensions.css.cell.height}px`}};u.AccessibilityManager=b=m([x(1,j.IInstantiationService),x(2,E.ICoreBrowserService),x(3,E.IRenderService)],b)},3614:(d,u)=>{function h(v){return v.replace(/\r?\n/g,"\r")}function m(v,S){return S?"\x1B[200~"+v+"\x1B[201~":v}function x(v,S,E,j){v=m(v=h(v),E.decPrivateModes.bracketedPasteMode&&j.rawOptions.ignoreBracketedPasteMode!==!0),E.triggerDataEvent(v,!0),S.value=""}function g(v,S,E){const j=E.getBoundingClientRect(),y=v.clientX-j.left-10,b=v.clientY-j.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${y}px`,S.style.top=`${b}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(u,"__esModule",{value:!0}),u.rightClickHandler=u.moveTextAreaUnderMouseCursor=u.paste=u.handlePasteEvent=u.copyHandler=u.bracketTextForPaste=u.prepareTextForTerminal=void 0,u.prepareTextForTerminal=h,u.bracketTextForPaste=m,u.copyHandler=function(v,S){v.clipboardData&&v.clipboardData.setData("text/plain",S.selectionText),v.preventDefault()},u.handlePasteEvent=function(v,S,E,j){v.stopPropagation(),v.clipboardData&&x(v.clipboardData.getData("text/plain"),S,E,j)},u.paste=x,u.moveTextAreaUnderMouseCursor=g,u.rightClickHandler=function(v,S,E,j,y){g(v,S,E),y&&j.rightClickSelect(v),S.value=j.selectionText,S.select()}},7239:(d,u,h)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ColorContrastCache=void 0;const m=h(1505);u.ColorContrastCache=class{constructor(){this._color=new m.TwoKeyMap,this._css=new m.TwoKeyMap}setCss(x,g,v){this._css.set(x,g,v)}getCss(x,g){return this._css.get(x,g)}setColor(x,g,v){this._color.set(x,g,v)}getColor(x,g){return this._color.get(x,g)}clear(){this._color.clear(),this._css.clear()}}},3656:(d,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.addDisposableDomListener=void 0,u.addDisposableDomListener=function(h,m,x,g){h.addEventListener(m,x,g);let v=!1;return{dispose:()=>{v||(v=!0,h.removeEventListener(m,x,g))}}}},3551:function(d,u,h){var m=this&&this.__decorate||function(b,_,C,N){var $,R=arguments.length,O=R<3?_:N===null?N=Object.getOwnPropertyDescriptor(_,C):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(b,_,C,N);else for(var I=b.length-1;I>=0;I--)($=b[I])&&(O=(R<3?$(O):R>3?$(_,C,O):$(_,C))||O);return R>3&&O&&Object.defineProperty(_,C,O),O},x=this&&this.__param||function(b,_){return function(C,N){_(C,N,b)}};Object.defineProperty(u,"__esModule",{value:!0}),u.Linkifier=void 0;const g=h(3656),v=h(8460),S=h(844),E=h(2585),j=h(4725);let y=u.Linkifier=class extends S.Disposable{get currentLink(){return this._currentLink}constructor(b,_,C,N,$){super(),this._element=b,this._mouseService=_,this._renderService=C,this._bufferService=N,this._linkProviderService=$,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new v.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new v.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,S.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,S.toDisposable)((()=>{var R;this._lastMouseEvent=void 0,(R=this._activeProviderReplies)==null||R.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,g.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,g.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(b){this._lastMouseEvent=b;const _=this._positionFromMouseEvent(b,this._element,this._mouseService);if(!_)return;this._isMouseOut=!1;const C=b.composedPath();for(let N=0;N<C.length;N++){const $=C[N];if($.classList.contains("xterm"))break;if($.classList.contains("xterm-hover"))return}this._lastBufferCell&&_.x===this._lastBufferCell.x&&_.y===this._lastBufferCell.y||(this._handleHover(_),this._lastBufferCell=_)}_handleHover(b){if(this._activeLine!==b.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(b,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,b)||(this._clearCurrentLink(),this._askForLink(b,!0))}_askForLink(b,_){var N,$;this._activeProviderReplies&&_||((N=this._activeProviderReplies)==null||N.forEach((R=>{R==null||R.forEach((O=>{O.link.dispose&&O.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=b.y);let C=!1;for(const[R,O]of this._linkProviderService.linkProviders.entries())_?($=this._activeProviderReplies)!=null&&$.get(R)&&(C=this._checkLinkProviderResult(R,b,C)):O.provideLinks(b.y,(I=>{var U,W;if(this._isMouseOut)return;const z=I==null?void 0:I.map((Y=>({link:Y})));(U=this._activeProviderReplies)==null||U.set(R,z),C=this._checkLinkProviderResult(R,b,C),((W=this._activeProviderReplies)==null?void 0:W.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(b.y,this._activeProviderReplies)}))}_removeIntersectingLinks(b,_){const C=new Set;for(let N=0;N<_.size;N++){const $=_.get(N);if($)for(let R=0;R<$.length;R++){const O=$[R],I=O.link.range.start.y<b?0:O.link.range.start.x,z=O.link.range.end.y>b?this._bufferService.cols:O.link.range.end.x;for(let U=I;U<=z;U++){if(C.has(U)){$.splice(R--,1);break}C.add(U)}}}}_checkLinkProviderResult(b,_,C){var R;if(!this._activeProviderReplies)return C;const N=this._activeProviderReplies.get(b);let $=!1;for(let O=0;O<b;O++)this._activeProviderReplies.has(O)&&!this._activeProviderReplies.get(O)||($=!0);if(!$&&N){const O=N.find((I=>this._linkAtPosition(I.link,_)));O&&(C=!0,this._handleNewLink(O))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!C)for(let O=0;O<this._activeProviderReplies.size;O++){const I=(R=this._activeProviderReplies.get(O))==null?void 0:R.find((z=>this._linkAtPosition(z.link,_)));if(I){C=!0,this._handleNewLink(I);break}}return C}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(b){if(!this._currentLink)return;const _=this._positionFromMouseEvent(b,this._element,this._mouseService);_&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,_)&&this._currentLink.link.activate(b,this._currentLink.link.text)}_clearCurrentLink(b,_){this._currentLink&&this._lastMouseEvent&&(!b||!_||this._currentLink.link.range.start.y>=b&&this._currentLink.link.range.end.y<=_)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,S.disposeArray)(this._linkCacheDisposables))}_handleNewLink(b){if(!this._lastMouseEvent)return;const _=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);_&&this._linkAtPosition(b.link,_)&&(this._currentLink=b,this._currentLink.state={decorations:{underline:b.link.decorations===void 0||b.link.decorations.underline,pointerCursor:b.link.decorations===void 0||b.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,b.link,this._lastMouseEvent),b.link.decorations={},Object.defineProperties(b.link.decorations,{pointerCursor:{get:()=>{var C,N;return(N=(C=this._currentLink)==null?void 0:C.state)==null?void 0:N.decorations.pointerCursor},set:C=>{var N;(N=this._currentLink)!=null&&N.state&&this._currentLink.state.decorations.pointerCursor!==C&&(this._currentLink.state.decorations.pointerCursor=C,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",C))}},underline:{get:()=>{var C,N;return(N=(C=this._currentLink)==null?void 0:C.state)==null?void 0:N.decorations.underline},set:C=>{var N,$,R;(N=this._currentLink)!=null&&N.state&&((R=($=this._currentLink)==null?void 0:$.state)==null?void 0:R.decorations.underline)!==C&&(this._currentLink.state.decorations.underline=C,this._currentLink.state.isHovered&&this._fireUnderlineEvent(b.link,C))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((C=>{if(!this._currentLink)return;const N=C.start===0?0:C.start+1+this._bufferService.buffer.ydisp,$=this._bufferService.buffer.ydisp+1+C.end;if(this._currentLink.link.range.start.y>=N&&this._currentLink.link.range.end.y<=$&&(this._clearCurrentLink(N,$),this._lastMouseEvent)){const R=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);R&&this._askForLink(R,!1)}}))))}_linkHover(b,_,C){var N;(N=this._currentLink)!=null&&N.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(_,!0),this._currentLink.state.decorations.pointerCursor&&b.classList.add("xterm-cursor-pointer")),_.hover&&_.hover(C,_.text)}_fireUnderlineEvent(b,_){const C=b.range,N=this._bufferService.buffer.ydisp,$=this._createLinkUnderlineEvent(C.start.x-1,C.start.y-N-1,C.end.x,C.end.y-N-1,void 0);(_?this._onShowLinkUnderline:this._onHideLinkUnderline).fire($)}_linkLeave(b,_,C){var N;(N=this._currentLink)!=null&&N.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(_,!1),this._currentLink.state.decorations.pointerCursor&&b.classList.remove("xterm-cursor-pointer")),_.leave&&_.leave(C,_.text)}_linkAtPosition(b,_){const C=b.range.start.y*this._bufferService.cols+b.range.start.x,N=b.range.end.y*this._bufferService.cols+b.range.end.x,$=_.y*this._bufferService.cols+_.x;return C<=$&&$<=N}_positionFromMouseEvent(b,_,C){const N=C.getCoords(b,_,this._bufferService.cols,this._bufferService.rows);if(N)return{x:N[0],y:N[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(b,_,C,N,$){return{x1:b,y1:_,x2:C,y2:N,cols:this._bufferService.cols,fg:$}}};u.Linkifier=y=m([x(1,j.IMouseService),x(2,j.IRenderService),x(3,E.IBufferService),x(4,j.ILinkProviderService)],y)},9042:(d,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.tooMuchOutput=u.promptLabel=void 0,u.promptLabel="Terminal input",u.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(d,u,h){var m=this&&this.__decorate||function(j,y,b,_){var C,N=arguments.length,$=N<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(j,y,b,_);else for(var R=j.length-1;R>=0;R--)(C=j[R])&&($=(N<3?C($):N>3?C(y,b,$):C(y,b))||$);return N>3&&$&&Object.defineProperty(y,b,$),$},x=this&&this.__param||function(j,y){return function(b,_){y(b,_,j)}};Object.defineProperty(u,"__esModule",{value:!0}),u.OscLinkProvider=void 0;const g=h(511),v=h(2585);let S=u.OscLinkProvider=class{constructor(j,y,b){this._bufferService=j,this._optionsService=y,this._oscLinkService=b}provideLinks(j,y){var z;const b=this._bufferService.buffer.lines.get(j-1);if(!b)return void y(void 0);const _=[],C=this._optionsService.rawOptions.linkHandler,N=new g.CellData,$=b.getTrimmedLength();let R=-1,O=-1,I=!1;for(let U=0;U<$;U++)if(O!==-1||b.hasContent(U)){if(b.loadCell(U,N),N.hasExtendedAttrs()&&N.extended.urlId){if(O===-1){O=U,R=N.extended.urlId;continue}I=N.extended.urlId!==R}else O!==-1&&(I=!0);if(I||O!==-1&&U===$-1){const W=(z=this._oscLinkService.getLinkData(R))==null?void 0:z.uri;if(W){const Y={start:{x:O+1,y:j},end:{x:U+(I||U!==$-1?0:1),y:j}};let V=!1;if(!(C!=null&&C.allowNonHttpProtocols))try{const H=new URL(W);["http:","https:"].includes(H.protocol)||(V=!0)}catch{V=!0}V||_.push({text:W,range:Y,activate:(H,te)=>C?C.activate(H,te,Y):E(0,te),hover:(H,te)=>{var ae;return(ae=C==null?void 0:C.hover)==null?void 0:ae.call(C,H,te,Y)},leave:(H,te)=>{var ae;return(ae=C==null?void 0:C.leave)==null?void 0:ae.call(C,H,te,Y)}})}I=!1,N.hasExtendedAttrs()&&N.extended.urlId?(O=U,R=N.extended.urlId):(O=-1,R=-1)}}y(_)}};function E(j,y){if(confirm(`Do you want to navigate to ${y}?
|
|
2900
2900
|
|
|
@@ -2959,7 +2959,7 @@ ${n}</tr>
|
|
|
2959
2959
|
`+this.renderer.text(u);r?i+=this.renderer.paragraph({type:"paragraph",raw:h,text:h,tokens:[{type:"text",raw:h,text:h}]}):i+=h;continue}default:{const u='Token with "'+d.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return i}parseInline(n,r){r=r||this.renderer;let i="";for(let o=0;o<n.length;o++){const l=n[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[l.type]){const u=this.options.extensions.renderers[l.type].call({parser:this},l);if(u!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(l.type)){i+=u||"";continue}}const d=l;switch(d.type){case"escape":{i+=r.text(d);break}case"html":{i+=r.html(d);break}case"link":{i+=r.link(d);break}case"image":{i+=r.image(d);break}case"strong":{i+=r.strong(d);break}case"em":{i+=r.em(d);break}case"codespan":{i+=r.codespan(d);break}case"br":{i+=r.br(d);break}case"del":{i+=r.del(d);break}case"text":{i+=r.text(d);break}default:{const u='Token with "'+d.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return i}}class Im{constructor(n){Fn(this,"options");this.options=n||Bu}preprocess(n){return n}postprocess(n){return n}processAllTokens(n){return n}}Fn(Im,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));class S3{constructor(...n){Fn(this,"defaults",s0());Fn(this,"options",this.setOptions);Fn(this,"parse",this.parseMarkdown(ya.lex,va.parse));Fn(this,"parseInline",this.parseMarkdown(ya.lexInline,va.parseInline));Fn(this,"Parser",va);Fn(this,"Renderer",vy);Fn(this,"TextRenderer",u0);Fn(this,"Lexer",ya);Fn(this,"Tokenizer",xy);Fn(this,"Hooks",Im);this.use(...n)}walkTokens(n,r){var o,l;let i=[];for(const d of n)switch(i=i.concat(r.call(this,d)),d.type){case"table":{const u=d;for(const h of u.header)i=i.concat(this.walkTokens(h.tokens,r));for(const h of u.rows)for(const m of h)i=i.concat(this.walkTokens(m.tokens,r));break}case"list":{const u=d;i=i.concat(this.walkTokens(u.items,r));break}default:{const u=d;(l=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&l[u.type]?this.defaults.extensions.childTokens[u.type].forEach(h=>{const m=u[h].flat(1/0);i=i.concat(this.walkTokens(m,r))}):u.tokens&&(i=i.concat(this.walkTokens(u.tokens,r)))}}return i}use(...n){const r=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(i=>{const o={...i};if(o.async=this.defaults.async||o.async||!1,i.extensions&&(i.extensions.forEach(l=>{if(!l.name)throw new Error("extension name required");if("renderer"in l){const d=r.renderers[l.name];d?r.renderers[l.name]=function(...u){let h=l.renderer.apply(this,u);return h===!1&&(h=d.apply(this,u)),h}:r.renderers[l.name]=l.renderer}if("tokenizer"in l){if(!l.level||l.level!=="block"&&l.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const d=r[l.level];d?d.unshift(l.tokenizer):r[l.level]=[l.tokenizer],l.start&&(l.level==="block"?r.startBlock?r.startBlock.push(l.start):r.startBlock=[l.start]:l.level==="inline"&&(r.startInline?r.startInline.push(l.start):r.startInline=[l.start]))}"childTokens"in l&&l.childTokens&&(r.childTokens[l.name]=l.childTokens)}),o.extensions=r),i.renderer){const l=this.defaults.renderer||new vy(this.defaults);for(const d in i.renderer){if(!(d in l))throw new Error(`renderer '${d}' does not exist`);if(["options","parser"].includes(d))continue;const u=d,h=i.renderer[u],m=l[u];l[u]=(...x)=>{let g=h.apply(l,x);return g===!1&&(g=m.apply(l,x)),g||""}}o.renderer=l}if(i.tokenizer){const l=this.defaults.tokenizer||new xy(this.defaults);for(const d in i.tokenizer){if(!(d in l))throw new Error(`tokenizer '${d}' does not exist`);if(["options","rules","lexer"].includes(d))continue;const u=d,h=i.tokenizer[u],m=l[u];l[u]=(...x)=>{let g=h.apply(l,x);return g===!1&&(g=m.apply(l,x)),g}}o.tokenizer=l}if(i.hooks){const l=this.defaults.hooks||new Im;for(const d in i.hooks){if(!(d in l))throw new Error(`hook '${d}' does not exist`);if(d==="options")continue;const u=d,h=i.hooks[u],m=l[u];Im.passThroughHooks.has(d)?l[u]=x=>{if(this.defaults.async)return Promise.resolve(h.call(l,x)).then(v=>m.call(l,v));const g=h.call(l,x);return m.call(l,g)}:l[u]=(...x)=>{let g=h.apply(l,x);return g===!1&&(g=m.apply(l,x)),g}}o.hooks=l}if(i.walkTokens){const l=this.defaults.walkTokens,d=i.walkTokens;o.walkTokens=function(u){let h=[];return h.push(d.call(this,u)),l&&(h=h.concat(l.call(this,u))),h}}this.defaults={...this.defaults,...o}}),this}setOptions(n){return this.defaults={...this.defaults,...n},this}lexer(n,r){return ya.lex(n,r??this.defaults)}parser(n,r){return va.parse(n,r??this.defaults)}parseMarkdown(n,r){return(o,l)=>{const d={...l},u={...this.defaults,...d},h=this.onError(!!u.silent,!!u.async);if(this.defaults.async===!0&&d.async===!1)return h(new 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 o>"u"||o===null)return h(new Error("marked(): input parameter is undefined or null"));if(typeof o!="string")return h(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(o)+", string expected"));if(u.hooks&&(u.hooks.options=u),u.async)return Promise.resolve(u.hooks?u.hooks.preprocess(o):o).then(m=>n(m,u)).then(m=>u.hooks?u.hooks.processAllTokens(m):m).then(m=>u.walkTokens?Promise.all(this.walkTokens(m,u.walkTokens)).then(()=>m):m).then(m=>r(m,u)).then(m=>u.hooks?u.hooks.postprocess(m):m).catch(h);try{u.hooks&&(o=u.hooks.preprocess(o));let m=n(o,u);u.hooks&&(m=u.hooks.processAllTokens(m)),u.walkTokens&&this.walkTokens(m,u.walkTokens);let x=r(m,u);return u.hooks&&(x=u.hooks.postprocess(x)),x}catch(m){return h(m)}}}onError(n,r){return i=>{if(i.message+=`
|
|
2960
2960
|
Please report this to https://github.com/markedjs/marked.`,n){const o="<p>An error occurred:</p><pre>"+Oi(i.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(i);throw i}}}const Lu=new S3;function wn(e,n){return Lu.parse(e,n)}wn.options=wn.setOptions=function(e){return Lu.setOptions(e),wn.defaults=Lu.defaults,xC(wn.defaults),wn};wn.getDefaults=s0;wn.defaults=Bu;wn.use=function(...e){return Lu.use(...e),wn.defaults=Lu.defaults,xC(wn.defaults),wn};wn.walkTokens=function(e,n){return Lu.walkTokens(e,n)};wn.parseInline=Lu.parseInline;wn.Parser=va;wn.parser=va.parse;wn.Renderer=vy;wn.TextRenderer=u0;wn.Lexer=ya;wn.lexer=ya.lex;wn.Tokenizer=xy;wn.Hooks=Im;wn.parse=wn;wn.options;wn.setOptions;wn.use;wn.walkTokens;wn.parseInline;va.parse;ya.lex;/*! @license DOMPurify 3.4.11 | (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.11/LICENSE */function g1(e,n){(n==null||n>e.length)&&(n=e.length);for(var r=0,i=Array(n);r<n;r++)i[r]=e[r];return i}function C3(e){if(Array.isArray(e))return e}function j3(e,n){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var i,o,l,d,u=[],h=!0,m=!1;try{if(l=(r=r.call(e)).next,n!==0)for(;!(h=(i=l.call(r)).done)&&(u.push(i.value),u.length!==n);h=!0);}catch(x){m=!0,o=x}finally{try{if(!h&&r.return!=null&&(d=r.return(),Object(d)!==d))return}finally{if(m)throw o}}return u}}function E3(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2961
2961
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N3(e,n){return C3(e)||j3(e,n)||T3(e,n)||E3()}function T3(e,n){if(e){if(typeof e=="string")return g1(e,n);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?g1(e,n):void 0}}const EC=Object.entries,x1=Object.setPrototypeOf,$3=Object.isFrozen,A3=Object.getPrototypeOf,R3=Object.getOwnPropertyDescriptor;let ks=Object.freeze,Ss=Object.seal,Ih=Object.create,NC=typeof Reflect<"u"&&Reflect,tw=NC.apply,nw=NC.construct;ks||(ks=function(n){return n});Ss||(Ss=function(n){return n});tw||(tw=function(n,r){for(var i=arguments.length,o=new Array(i>2?i-2:0),l=2;l<i;l++)o[l-2]=arguments[l];return n.apply(r,o)});nw||(nw=function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return new n(...i)});const Jp=Nr(Array.prototype.forEach),M3=Nr(Array.prototype.lastIndexOf),y1=Nr(Array.prototype.pop),Eh=Nr(Array.prototype.push),I3=Nr(Array.prototype.splice),pc=Array.isArray,bm=Nr(String.prototype.toLowerCase),Bv=Nr(String.prototype.toString),v1=Nr(String.prototype.match),Qp=Nr(String.prototype.replace),b1=Nr(String.prototype.indexOf),P3=Nr(String.prototype.trim),D3=Nr(Number.prototype.toString),O3=Nr(Boolean.prototype.toString),w1=typeof BigInt>"u"?null:Nr(BigInt.prototype.toString),_1=typeof Symbol>"u"?null:Nr(Symbol.prototype.toString),ns=Nr(Object.prototype.hasOwnProperty),Zp=Nr(Object.prototype.toString),_s=Nr(RegExp.prototype.test),bu=L3(TypeError);function Nr(e){return function(n){n instanceof RegExp&&(n.lastIndex=0);for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return tw(e,n,i)}}function L3(e){return function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return nw(e,r)}}function Sn(e,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:bm;if(x1&&x1(e,null),!pc(n))return e;let i=n.length;for(;i--;){let o=n[i];if(typeof o=="string"){const l=r(o);l!==o&&($3(n)||(n[i]=l),o=l)}e[o]=!0}return e}function z3(e){for(let n=0;n<e.length;n++)ns(e,n)||(e[n]=null);return e}function Vs(e){const n=Ih(null);for(const i of EC(e)){var r=N3(i,2);const o=r[0],l=r[1];ns(e,o)&&(pc(l)?n[o]=z3(l):l&&typeof l=="object"&&l.constructor===Object?n[o]=Vs(l):n[o]=l)}return n}function B3(e){switch(typeof e){case"string":return e;case"number":return D3(e);case"boolean":return O3(e);case"bigint":return w1?w1(e):"0";case"symbol":return _1?_1(e):"Symbol()";case"undefined":return Zp(e);case"function":case"object":{if(e===null)return Zp(e);const n=e,r=pa(n,"toString");if(typeof r=="function"){const i=r(n);return typeof i=="string"?i:Zp(i)}return Zp(e)}default:return Zp(e)}}function pa(e,n){for(;e!==null;){const i=R3(e,n);if(i){if(i.get)return Nr(i.get);if(typeof i.value=="function")return Nr(i.value)}e=A3(e)}function r(){return null}return r}function F3(e){try{return _s(e,""),!0}catch{return!1}}const k1=ks(["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"]),Fv=ks(["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"]),Uv=ks(["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"]),U3=ks(["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"]),Hv=ks(["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"]),H3=ks(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),S1=ks(["#text"]),C1=ks(["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"]),Wv=ks(["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","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-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"]),j1=ks(["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"]),vx=ks(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),W3=Ss(/{{[\w\W]*|^[\w\W]*}}/g),q3=Ss(/<%[\w\W]*|^[\w\W]*%>/g),V3=Ss(/\${[\w\W]*/g),G3=Ss(/^data-[\-\w.\u00B7-\uFFFF]+$/),K3=Ss(/^aria-[\-\w]+$/),E1=Ss(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),X3=Ss(/^(?:\w+script|data):/i),Y3=Ss(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),J3=Ss(/^html$/i),Q3=Ss(/^[a-z][.\w]*(-[.\w]+)+$/i),N1=Ss(/<[/\w!]/g),Z3=Ss(/<[/\w]/g),eA=Ss(/<\/no(script|embed|frames)/i),tA=Ss(/\/>/i),fa={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},nA=function(){return typeof window>"u"?null:window},rA=function(n,r){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let i=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(i=r.getAttribute(o));const l="dompurify"+(i?"#"+i:"");try{return n.createPolicy(l,{createHTML(d){return d},createScriptURL(d){return d}})}catch{return console.warn("TrustedTypes policy "+l+" could not be created."),null}},T1=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Zl=function(n,r,i,o){return ns(n,r)&&pc(n[r])?Sn(o.base?Vs(o.base):{},n[r],o.transform):i};function TC(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:nA();const n=ft=>TC(ft);if(n.version="3.4.11",n.removed=[],!e||!e.document||e.document.nodeType!==fa.document||!e.Element)return n.isSupported=!1,n;let r=e.document;const i=r,o=i.currentScript;e.DocumentFragment;const l=e.HTMLTemplateElement,d=e.Node,u=e.Element,h=e.NodeFilter,m=e.NamedNodeMap;m===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const x=e.DOMParser,g=e.trustedTypes,v=u.prototype,S=pa(v,"cloneNode"),E=pa(v,"remove"),j=pa(v,"nextSibling"),y=pa(v,"childNodes"),b=pa(v,"parentNode"),_=pa(v,"shadowRoot"),C=pa(v,"attributes"),N=d&&d.prototype?pa(d.prototype,"nodeType"):null,$=d&&d.prototype?pa(d.prototype,"nodeName"):null;if(typeof l=="function"){const ft=r.createElement("template");ft.content&&ft.content.ownerDocument&&(r=ft.content.ownerDocument)}let R,O="",I,z=!1,U=0;const W=function(){if(U>0)throw bu('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.')},Y=function(be){W(),U++;try{return R.createHTML(be)}finally{U--}},V=function(be){W(),U++;try{return R.createScriptURL(be)}finally{U--}},H=function(){return z||(I=rA(g,o),z=!0),I},te=r,ae=te.implementation,oe=te.createNodeIterator,ie=te.createDocumentFragment,X=te.getElementsByTagName,Q=i.importNode;let J=T1();n.isSupported=typeof EC=="function"&&typeof b=="function"&&ae&&ae.createHTMLDocument!==void 0;const le=W3,ce=q3,pe=V3,Ae=G3,Se=K3,ye=X3,ne=Y3,we=Q3;let Ne=E1,Je=null;const lt=Sn({},[...k1,...Fv,...Uv,...Hv,...S1]);let xt=null;const Rt=Sn({},[...C1,...Wv,...j1,...vx]);let He=Object.seal(Ih(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}})),bt=null,st=null;const an=Object.seal(Ih(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let sn=!0,Ye=!0,yt=!1,kt=!0,Kt=!1,On=!0,Rn=!1,Br=!1,Tr=null,nt=null,St=!1,Tt=!1,cn=!1,nn=!1,$r=!0,Ta=!1;const Vo="user-content-";let vi=!0,yn=!1,Fr={},Zn=null;const bi=Sn({},["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"]);let Ms=null;const as=Sn({},["audio","video","img","source","image","track"]);let Fi=null;const wi=Sn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_i="http://www.w3.org/1998/Math/MathML",Is="http://www.w3.org/2000/svg",Ar="http://www.w3.org/1999/xhtml";let Ur=Ar,Qs=!1,Rr=null;const ls=Sn({},[_i,Is,Ar],Bv),js=ks(["mi","mo","mn","ms","mtext"]);let ho=Sn({},js);const Zs=ks(["annotation-xml"]);let ei=Sn({},Zs);const ti=Sn({},["title","style","font","a","script"]);let zt=null;const Hr=["application/xhtml+xml","text/html"],Hn="text/html";let _n=null,Ct=null;const Ui=r.createElement("form"),fo=function(be){return be instanceof RegExp||be instanceof Function},$a=function(){let be=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ct&&Ct===be)return;(!be||typeof be!="object")&&(be={}),be=Vs(be),zt=Hr.indexOf(be.PARSER_MEDIA_TYPE)===-1?Hn:be.PARSER_MEDIA_TYPE,_n=zt==="application/xhtml+xml"?Bv:bm,Je=Zl(be,"ALLOWED_TAGS",lt,{transform:_n}),xt=Zl(be,"ALLOWED_ATTR",Rt,{transform:_n}),Rr=Zl(be,"ALLOWED_NAMESPACES",ls,{transform:Bv}),Fi=Zl(be,"ADD_URI_SAFE_ATTR",wi,{transform:_n,base:wi}),Ms=Zl(be,"ADD_DATA_URI_TAGS",as,{transform:_n,base:as}),Zn=Zl(be,"FORBID_CONTENTS",bi,{transform:_n}),bt=Zl(be,"FORBID_TAGS",Vs({}),{transform:_n}),st=Zl(be,"FORBID_ATTR",Vs({}),{transform:_n}),Fr=ns(be,"USE_PROFILES")?be.USE_PROFILES&&typeof be.USE_PROFILES=="object"?Vs(be.USE_PROFILES):be.USE_PROFILES:!1,sn=be.ALLOW_ARIA_ATTR!==!1,Ye=be.ALLOW_DATA_ATTR!==!1,yt=be.ALLOW_UNKNOWN_PROTOCOLS||!1,kt=be.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Kt=be.SAFE_FOR_TEMPLATES||!1,On=be.SAFE_FOR_XML!==!1,Rn=be.WHOLE_DOCUMENT||!1,Tt=be.RETURN_DOM||!1,cn=be.RETURN_DOM_FRAGMENT||!1,nn=be.RETURN_TRUSTED_TYPE||!1,St=be.FORCE_BODY||!1,$r=be.SANITIZE_DOM!==!1,Ta=be.SANITIZE_NAMED_PROPS||!1,vi=be.KEEP_CONTENT!==!1,yn=be.IN_PLACE||!1,Ne=F3(be.ALLOWED_URI_REGEXP)?be.ALLOWED_URI_REGEXP:E1,Ur=typeof be.NAMESPACE=="string"?be.NAMESPACE:Ar,ho=ns(be,"MATHML_TEXT_INTEGRATION_POINTS")&&be.MATHML_TEXT_INTEGRATION_POINTS&&typeof be.MATHML_TEXT_INTEGRATION_POINTS=="object"?Vs(be.MATHML_TEXT_INTEGRATION_POINTS):Sn({},js),ei=ns(be,"HTML_INTEGRATION_POINTS")&&be.HTML_INTEGRATION_POINTS&&typeof be.HTML_INTEGRATION_POINTS=="object"?Vs(be.HTML_INTEGRATION_POINTS):Sn({},Zs);const Pe=ns(be,"CUSTOM_ELEMENT_HANDLING")&&be.CUSTOM_ELEMENT_HANDLING&&typeof be.CUSTOM_ELEMENT_HANDLING=="object"?Vs(be.CUSTOM_ELEMENT_HANDLING):Ih(null);if(He=Ih(null),ns(Pe,"tagNameCheck")&&fo(Pe.tagNameCheck)&&(He.tagNameCheck=Pe.tagNameCheck),ns(Pe,"attributeNameCheck")&&fo(Pe.attributeNameCheck)&&(He.attributeNameCheck=Pe.attributeNameCheck),ns(Pe,"allowCustomizedBuiltInElements")&&typeof Pe.allowCustomizedBuiltInElements=="boolean"&&(He.allowCustomizedBuiltInElements=Pe.allowCustomizedBuiltInElements),Ss(He),Kt&&(Ye=!1),cn&&(Tt=!0),Fr&&(Je=Sn({},S1),xt=Ih(null),Fr.html===!0&&(Sn(Je,k1),Sn(xt,C1)),Fr.svg===!0&&(Sn(Je,Fv),Sn(xt,Wv),Sn(xt,vx)),Fr.svgFilters===!0&&(Sn(Je,Uv),Sn(xt,Wv),Sn(xt,vx)),Fr.mathMl===!0&&(Sn(Je,Hv),Sn(xt,j1),Sn(xt,vx))),an.tagCheck=null,an.attributeCheck=null,ns(be,"ADD_TAGS")&&(typeof be.ADD_TAGS=="function"?an.tagCheck=be.ADD_TAGS:pc(be.ADD_TAGS)&&(Je===lt&&(Je=Vs(Je)),Sn(Je,be.ADD_TAGS,_n))),ns(be,"ADD_ATTR")&&(typeof be.ADD_ATTR=="function"?an.attributeCheck=be.ADD_ATTR:pc(be.ADD_ATTR)&&(xt===Rt&&(xt=Vs(xt)),Sn(xt,be.ADD_ATTR,_n))),ns(be,"ADD_URI_SAFE_ATTR")&&pc(be.ADD_URI_SAFE_ATTR)&&Sn(Fi,be.ADD_URI_SAFE_ATTR,_n),ns(be,"FORBID_CONTENTS")&&pc(be.FORBID_CONTENTS)&&(Zn===bi&&(Zn=Vs(Zn)),Sn(Zn,be.FORBID_CONTENTS,_n)),ns(be,"ADD_FORBID_CONTENTS")&&pc(be.ADD_FORBID_CONTENTS)&&(Zn===bi&&(Zn=Vs(Zn)),Sn(Zn,be.ADD_FORBID_CONTENTS,_n)),vi&&(Je["#text"]=!0),Rn&&Sn(Je,["html","head","body"]),Je.table&&(Sn(Je,["tbody"]),delete bt.tbody),be.TRUSTED_TYPES_POLICY){if(typeof be.TRUSTED_TYPES_POLICY.createHTML!="function")throw bu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof be.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw bu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Qe=R;R=be.TRUSTED_TYPES_POLICY;try{O=Y("")}catch(Et){throw R=Qe,Et}}else be.TRUSTED_TYPES_POLICY===null?(R=void 0,O=""):(R===void 0&&(R=H()),R&&typeof O=="string"&&(O=Y("")));ks&&ks(be),Ct=be},po=Sn({},[...Fv,...Uv,...U3]),mo=Sn({},[...Hv,...H3]),Go=function(be,Pe,Qe){return Pe.namespaceURI===Ar?be==="svg":Pe.namespaceURI===_i?be==="svg"&&(Qe==="annotation-xml"||ho[Qe]):!!po[be]},Sr=function(be,Pe,Qe){return Pe.namespaceURI===Ar?be==="math":Pe.namespaceURI===Is?be==="math"&&ei[Qe]:!!mo[be]},Aa=function(be,Pe,Qe){return Pe.namespaceURI===Is&&!ei[Qe]||Pe.namespaceURI===_i&&!ho[Qe]?!1:!mo[be]&&(ti[be]||!po[be])},Ra=function(be){let Pe=b(be);(!Pe||!Pe.tagName)&&(Pe={namespaceURI:Ur,tagName:"template"});const Qe=bm(be.tagName),Et=bm(Pe.tagName);return Rr[be.namespaceURI]?be.namespaceURI===Is?Go(Qe,Pe,Et):be.namespaceURI===_i?Sr(Qe,Pe,Et):be.namespaceURI===Ar?Aa(Qe,Pe,Et):!!(zt==="application/xhtml+xml"&&Rr[be.namespaceURI]):!1},kn=function(be){Eh(n.removed,{element:be});try{b(be).removeChild(be)}catch{if(E(be),!b(be))throw bu("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Mr=function(be){const Pe=y(be);if(Pe){const Et=[];Jp(Pe,en=>{Eh(Et,en)}),Jp(Et,en=>{try{E(en)}catch{}})}const Qe=C(be);if(Qe)for(let Et=Qe.length-1;Et>=0;--Et){const en=Qe[Et],ln=en&&en.name;if(typeof ln=="string")try{be.removeAttribute(ln)}catch{}}},Vn=function(be,Pe){try{Eh(n.removed,{attribute:Pe.getAttributeNode(be),from:Pe})}catch{Eh(n.removed,{attribute:null,from:Pe})}if(Pe.removeAttribute(be),be==="is")if(Tt||cn)try{kn(Pe)}catch{}else try{Pe.setAttribute(be,"")}catch{}},Ir=function(be){const Pe=C(be);if(Pe)for(let Qe=Pe.length-1;Qe>=0;--Qe){const Et=Pe[Qe],en=Et&&Et.name;if(!(typeof en!="string"||xt[_n(en)]))try{be.removeAttribute(en)}catch{}}},ni=function(be){const Pe=[be];for(;Pe.length>0;){const Qe=Pe.pop();(N?N(Qe):Qe.nodeType)===fa.element&&Ir(Qe);const en=y(Qe);if(en)for(let ln=en.length-1;ln>=0;--ln)Pe.push(en[ln])}},Hi=function(be){let Pe=null,Qe=null;if(St)be="<remove></remove>"+be;else{const ln=v1(be,/^[\r\n\t ]+/);Qe=ln&&ln[0]}zt==="application/xhtml+xml"&&Ur===Ar&&(be='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+be+"</body></html>");const Et=R?Y(be):be;if(Ur===Ar)try{Pe=new x().parseFromString(Et,zt)}catch{}if(!Pe||!Pe.documentElement){Pe=ae.createDocument(Ur,"template",null);try{Pe.documentElement.innerHTML=Qs?O:Et}catch{}}const en=Pe.body||Pe.documentElement;return be&&Qe&&en.insertBefore(r.createTextNode(Qe),en.childNodes[0]||null),Ur===Ar?X.call(Pe,Rn?"html":"body")[0]:Rn?Pe.documentElement:en},ki=function(be){return oe.call(be.ownerDocument||be,be,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},cs=function(be){return be=Qp(be,le," "),be=Qp(be,ce," "),be=Qp(be,pe," "),be},gr=function(be){var Pe;be.normalize();const Qe=oe.call(be.ownerDocument||be,be,h.SHOW_TEXT|h.SHOW_COMMENT|h.SHOW_CDATA_SECTION|h.SHOW_PROCESSING_INSTRUCTION,null);let Et=Qe.nextNode();for(;Et;)Et.data=cs(Et.data),Et=Qe.nextNode();const en=(Pe=be.querySelectorAll)===null||Pe===void 0?void 0:Pe.call(be,"template");en&&Jp(en,ln=>{Gn(ln.content)&&gr(ln.content)})},Bt=function(be){const Pe=$?$(be):null;return typeof Pe!="string"||_n(Pe)!=="form"?!1:typeof be.nodeName!="string"||typeof be.textContent!="string"||typeof be.removeChild!="function"||be.attributes!==C(be)||typeof be.removeAttribute!="function"||typeof be.setAttribute!="function"||typeof be.namespaceURI!="string"||typeof be.insertBefore!="function"||typeof be.hasChildNodes!="function"||be.nodeType!==N(be)||be.childNodes!==y(be)},Gn=function(be){if(!N||typeof be!="object"||be===null)return!1;try{return N(be)===fa.documentFragment}catch{return!1}},Si=function(be){if(!N||typeof be!="object"||be===null)return!1;try{return typeof N(be)=="number"}catch{return!1}};function us(ft,be,Pe){ft.length!==0&&Jp(ft,Qe=>{Qe.call(n,be,Pe,Ct)})}const Ko=function(be,Pe){return!!(On&&be.hasChildNodes()&&!Si(be.firstElementChild)&&_s(N1,be.textContent)&&_s(N1,be.innerHTML)||On&&be.namespaceURI===Ar&&Pe==="style"&&Si(be.firstElementChild)||be.nodeType===fa.processingInstruction||On&&be.nodeType===fa.comment&&_s(Z3,be.data))},Ci=function(be,Pe){if(!bt[Pe]&&on(Pe)&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,Pe)||He.tagNameCheck instanceof Function&&He.tagNameCheck(Pe)))return!1;if(vi&&!Zn[Pe]){const Qe=b(be),Et=y(be);if(Et&&Qe){const en=Et.length;for(let ln=en-1;ln>=0;--ln){const $n=yn?Et[ln]:S(Et[ln],!0);Qe.insertBefore($n,j(be))}}}return kn(be),!0},Wr=function(be){if(us(J.beforeSanitizeElements,be,null),Bt(be))return kn(be),!0;const Pe=_n($?$(be):be.nodeName);if(us(J.uponSanitizeElement,be,{tagName:Pe,allowedTags:Je}),Ko(be,Pe))return kn(be),!0;if(bt[Pe]||!(an.tagCheck instanceof Function&&an.tagCheck(Pe))&&!Je[Pe])return Ci(be,Pe);if((N?N(be):be.nodeType)===fa.element&&!Ra(be)||(Pe==="noscript"||Pe==="noembed"||Pe==="noframes")&&_s(eA,be.innerHTML))return kn(be),!0;if(Kt&&be.nodeType===fa.text){const Et=cs(be.textContent);be.textContent!==Et&&(Eh(n.removed,{element:be.cloneNode()}),be.textContent=Et)}return us(J.afterSanitizeElements,be,null),!1},Ps=function(be,Pe,Qe){if(st[Pe]||$r&&(Pe==="id"||Pe==="name")&&(Qe in r||Qe in Ui))return!1;const Et=xt[Pe]||an.attributeCheck instanceof Function&&an.attributeCheck(Pe,be);if(!(Ye&&_s(Ae,Pe))){if(!(sn&&_s(Se,Pe))){if(Et){if(!Fi[Pe]){if(!_s(Ne,Qp(Qe,ne,""))){if(!((Pe==="src"||Pe==="xlink:href"||Pe==="href")&&be!=="script"&&b1(Qe,"data:")===0&&Ms[be])){if(!(yt&&!_s(ye,Qp(Qe,ne,"")))){if(Qe)return!1}}}}}else if(!(on(be)&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,be)||He.tagNameCheck instanceof Function&&He.tagNameCheck(be))&&(He.attributeNameCheck instanceof RegExp&&_s(He.attributeNameCheck,Pe)||He.attributeNameCheck instanceof Function&&He.attributeNameCheck(Pe,be))||Pe==="is"&&He.allowCustomizedBuiltInElements&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,Qe)||He.tagNameCheck instanceof Function&&He.tagNameCheck(Qe))))return!1}}return!0},ji=Sn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),on=function(be){return!ji[bm(be)]&&_s(we,be)},ds=function(be,Pe,Qe,Et){if(R&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Qe)switch(g.getAttributeType(be,Pe)){case"TrustedHTML":return Y(Et);case"TrustedScriptURL":return V(Et)}return Et},Wi=function(be,Pe,Qe,Et){try{Qe?be.setAttributeNS(Qe,Pe,Et):be.setAttribute(Pe,Et),Bt(be)?kn(be):y1(n.removed)}catch{Vn(Pe,be)}},Es=function(be){us(J.beforeSanitizeAttributes,be,null);const Pe=be.attributes;if(!Pe||Bt(be))return;const Qe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:xt,forceKeepAttr:void 0};let Et=Pe.length;const en=_n(be.nodeName);for(;Et--;){const ln=Pe[Et],$n=ln.name,En=ln.namespaceURI,er=ln.value,Ln=_n($n),sr=er;let Nn=$n==="value"?sr:P3(sr);if(Qe.attrName=Ln,Qe.attrValue=Nn,Qe.keepAttr=!0,Qe.forceKeepAttr=void 0,us(J.uponSanitizeAttribute,be,Qe),Nn=Qe.attrValue,Ta&&(Ln==="id"||Ln==="name")&&b1(Nn,Vo)!==0&&(Vn($n,be),Nn=Vo+Nn),On&&_s(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Nn)){Vn($n,be);continue}if(Ln==="attributename"&&v1(Nn,"href")){Vn($n,be);continue}if(!Qe.forceKeepAttr){if(!Qe.keepAttr){Vn($n,be);continue}if(!kt&&_s(tA,Nn)){Vn($n,be);continue}if(Kt&&(Nn=cs(Nn)),!Ps(en,Ln,Nn)){Vn($n,be);continue}Nn=ds(en,Ln,En,Nn),Nn!==sr&&Wi(be,$n,En,Nn)}}us(J.afterSanitizeAttributes,be,null)},Ke=function(be){let Pe=null;const Qe=ki(be);for(us(J.beforeSanitizeShadowDOM,be,null);Pe=Qe.nextNode();)if(us(J.uponSanitizeShadowNode,Pe,null),Wr(Pe),Es(Pe),Gn(Pe.content)&&Ke(Pe.content),(N?N(Pe):Pe.nodeType)===fa.element){const en=_(Pe);Gn(en)&&(qr(en),Ke(en))}us(J.afterSanitizeShadowDOM,be,null)},qr=function(be){const Pe=[{node:be,shadow:null}];for(;Pe.length>0;){const Qe=Pe.pop();if(Qe.shadow){Ke(Qe.shadow);continue}const Et=Qe.node,ln=(N?N(Et):Et.nodeType)===fa.element,$n=y(Et);if($n)for(let En=$n.length-1;En>=0;--En)Pe.push({node:$n[En],shadow:null});if(ln){const En=$?$(Et):null;if(typeof En=="string"&&_n(En)==="template"){const er=Et.content;Gn(er)&&Pe.push({node:er,shadow:null})}}if(ln){const En=_(Et);Gn(En)&&Pe.push({node:null,shadow:En},{node:En,shadow:null})}}};return n.sanitize=function(ft){let be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Pe=null,Qe=null,Et=null,en=null;if(Qs=!ft,Qs&&(ft="<!-->"),typeof ft!="string"&&!Si(ft)&&(ft=B3(ft),typeof ft!="string"))throw bu("dirty is not a string, aborting");if(!n.isSupported)return ft;Br?(Je=Tr,xt=nt):$a(be),(J.uponSanitizeElement.length>0||J.uponSanitizeAttribute.length>0)&&(Je=Vs(Je)),J.uponSanitizeAttribute.length>0&&(xt=Vs(xt)),n.removed=[];const ln=yn&&typeof ft!="string"&&Si(ft);if(ln){const er=$?$(ft):ft.nodeName;if(typeof er=="string"){const Ln=_n(er);if(!Je[Ln]||bt[Ln])throw bu("root node is forbidden and cannot be sanitized in-place")}if(Bt(ft))throw bu("root node is clobbered and cannot be sanitized in-place");try{qr(ft)}catch(Ln){throw Mr(ft),Ln}}else if(Si(ft))Pe=Hi("<!---->"),Qe=Pe.ownerDocument.importNode(ft,!0),Qe.nodeType===fa.element&&Qe.nodeName==="BODY"||Qe.nodeName==="HTML"?Pe=Qe:Pe.appendChild(Qe),qr(Qe);else{if(!Tt&&!Kt&&!Rn&&ft.indexOf("<")===-1)return R&&nn?Y(ft):ft;if(Pe=Hi(ft),!Pe)return Tt?null:nn?O:""}Pe&&St&&kn(Pe.firstChild);const $n=ki(ln?ft:Pe);try{for(;Et=$n.nextNode();)Wr(Et),Es(Et),Gn(Et.content)&&Ke(Et.content)}catch(er){throw ln&&Mr(ft),er}if(ln)return Jp(n.removed,er=>{er.element&&ni(er.element)}),Kt&&gr(ft),ft;if(Tt){if(Kt&&gr(Pe),cn)for(en=ie.call(Pe.ownerDocument);Pe.firstChild;)en.appendChild(Pe.firstChild);else en=Pe;return(xt.shadowroot||xt.shadowrootmode)&&(en=Q.call(i,en,!0)),en}let En=Rn?Pe.outerHTML:Pe.innerHTML;return Rn&&Je["!doctype"]&&Pe.ownerDocument&&Pe.ownerDocument.doctype&&Pe.ownerDocument.doctype.name&&_s(J3,Pe.ownerDocument.doctype.name)&&(En="<!DOCTYPE "+Pe.ownerDocument.doctype.name+`>
|
|
2962
|
-
`+En),Kt&&(En=cs(En)),R&&nn?Y(En):En},n.setConfig=function(){let ft=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$a(ft),Br=!0,Tr=Je,nt=xt},n.clearConfig=function(){Ct=null,Br=!1,Tr=null,nt=null,R=I,O=""},n.isValidAttribute=function(ft,be,Pe){Ct||$a({});const Qe=_n(ft),Et=_n(be);return Ps(Qe,Et,Pe)},n.addHook=function(ft,be){typeof be=="function"&&ns(J,ft)&&Eh(J[ft],be)},n.removeHook=function(ft,be){if(ns(J,ft)){if(be!==void 0){const Pe=M3(J[ft],be);return Pe===-1?void 0:I3(J[ft],Pe,1)[0]}return y1(J[ft])}},n.removeHooks=function(ft){ns(J,ft)&&(J[ft]=[])},n.removeAllHooks=function(){J=T1()},n}var d0=TC();const by=new wn.Renderer,sA=by.table.bind(by);by.table=e=>`<div class="prose-chat-table-wrap">${sA(e)}</div>`;function iA(e){return d0.sanitize(wn.parse(e,{async:!1,breaks:!0,renderer:by}))}async function $C(e,n=""){if(!e)return;const r=e.replace(/(?::\d+)+$/,""),i=a1(e,n),o=await window.api.files.read(i.absPath);if(!o.ok&&o.error==="path outside home"){Le.error("That path is outside the project and can't be opened.");return}let l=o.ok?i:null,d=0;if(!l&&!r.startsWith("/")){const u=Array.from(new Set(vt.getState().tabs.map(h=>h.cwd).filter(h=>h&&h!==n)));for(const h of u){const m=a1(e,h),x=await window.api.files.read(m.absPath);if(d++,x.ok){l=m;break}}}if(!l){const u=d===1?"tab":"tabs";Le.error(`${o.error||"Not found"} under ${n} (tried ${d} other open ${u})`);return}Tn.getState().openFile(l.absPath,{line:l.line,col:l.col}),window.dispatchEvent(new CustomEvent("sm:open-editor"))}async function oA(e,n=""){const r=e.target,i=r.closest("a");if(i){const d=i.getAttribute("href")||"";/^https?:\/\//i.test(d)&&(e.preventDefault(),window.api.shell.open({as:"external",url:d}).catch(()=>{}));return}const o=r.closest(`[${Zb}]`);if(!o)return;const l=o.getAttribute(Zb)??"";await $C(l,n)}function aA(e,n){var r;return e.text.trim().length>0?"text":n?"working":(r=e.toolUses)!=null&&r.length?"placeholder":"suppress"}function lA(e){switch(e){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed"}}function cA(e,n,r){return[...e,...n?[n]:[],...r]}let rw=null;function uA(e){rw=e,window.dispatchEvent(new CustomEvent("sm:select-prd",{detail:e}))}function dA(){const e=rw;return rw=null,e}const $1=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function hA(e){let n=0;for(let r=0;r<e.length;r++)n=n*31+e.charCodeAt(r)>>>0;return n}function bc(e){return $1[hA(e)%$1.length]}function Wo(e){if(!e)return null;const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function fA(e,n){const r=e?Wo(e)??"":n??"";return bc(r)}const pA={running:"bg-accent text-white",pending:"bg-bg text-fg-dim border border-line",completed:"bg-sage/20 text-sage",needs_review:"bg-butter/25 text-fg-dim",failed:"bg-accent/15 text-accent"},mA={pending:"○",completed:"✓",needs_review:"!",failed:"✕"};function AC({status:e}){const n=mA[e];return s.jsxs("span",{className:`inline-flex items-center gap-1.5 shrink-0 px-2.5 py-1 rounded-lg min-w-[104px] justify-center text-xs font-semibold tracking-wide ${pA[e]}`,role:"status","aria-label":`Status: ${e.replace("_"," ")}`,children:[e==="running"?s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):n&&s.jsx("span",{"aria-hidden":"true",children:n}),e.replace("_"," ")]})}function h0({cwd:e,name:n}){const r=n??(e?Wo(e)??e:"—"),i=fA(e,n);return s.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:i},"aria-hidden":"true"}),r]})}function gc({label:e,children:n}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:e}),s.jsx("div",{className:"grid gap-1.5",children:n})]})}function ss({k:e,v:n,wrap:r}){return s.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[s.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:e}),s.jsx("span",{className:`text-fg ${r?"break-all":""}`,children:n})]})}function qv({dotClass:e,n,label:r}){return s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-fg-dim",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${e}`,"aria-hidden":"true"}),s.jsx("strong",{className:"text-fg font-mono text-[13.5px]",children:n})," ",r]})}const gA={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes",no_verdict_sentinel:"no commit or verdict sentinel",pass_no_commit:"PASS sentinel but no commit landed"};function wy(e){return gA[e]??e}function Ph(e){const n=e.match(/^(\d+)-/);return n?n[1]:null}function RC({n:e}){return s.jsxs("span",{className:"font-mono text-[12px] font-semibold text-fg-faint shrink-0 tracking-tight select-none","aria-hidden":"true",children:["#",e]})}const xA={running:{bg:"bg-butter/30",text:"text-fg-dim",border:!1,label:"running"},queued:{bg:"bg-sage/25",text:"text-sage",border:!1,label:"queued"},ready:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"ready to run"},draft:{bg:"bg-bg",text:"text-fg-faint",border:!0,label:"draft"},completed:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"completed"},failed:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"failed"},needs_review:{bg:"bg-butter/25",text:"text-fg-dim",border:!1,label:"needs review"},dispatched:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"dispatched to PRD"}};function A1(e){return e?e.status==="pending"?"queued":e.status:"ready"}function sw({status:e}){const n=xA[e];return s.jsx("span",{role:"status","aria-label":`Status: ${n.label}`,className:`text-[11.5px] font-semibold px-[9px] py-0.5 rounded-full ${n.bg} ${n.text}${n.border?" ring-1 ring-inset ring-line":""}`,children:n.label})}function MC({path:e,onDismiss:n}){const[r,i]=L.useState(!1);return r?null:s.jsxs("div",{className:"mb-2 inline-flex max-w-[160px] items-start gap-1.5 rounded-md border border-line bg-elev p-1.5",children:[s.jsx("img",{src:Qy(e),alt:"Pasted clipboard image",className:"max-h-[120px] max-w-[120px] rounded object-contain",draggable:!1,onError:()=>i(!0)}),s.jsx("button",{type:"button",onClick:n,title:"Dismiss preview",className:"shrink-0 rounded text-fg-faint hover:bg-hi hover:text-fg",children:"✕"})]})}function Vt({title:e,hint:n}){return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("div",{className:"mb-2 text-fg-dim",children:e}),n&&s.jsx("div",{className:"text-fg-faint",children:n})]})})}const yA=/^\s*(?:[-*+]\s+.+|\d+\.\s+.+)/m;function vA(e){return yA.test(e)}function IC(e,n){window.api.clipboard.writeText(e).then(r=>n(!!(r!=null&&r.ok))).catch(()=>n(!1))}function bA({url:e}){const[n,r]=L.useState(!1),i=()=>{IC(e,o=>{o?(r(!0),setTimeout(()=>r(!1),1100)):Le.error("Copy failed")})};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"🔗"}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-fg-dim",children:e}),s.jsx("button",{onClick:i,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:n?"Copied":"Copy"})]})}function wA({path:e,cwd:n}){const[r,i]=L.useState(!1),o=()=>{IC(e,d=>{d?(i(!0),setTimeout(()=>i(!1),1100)):Le.error("Copy failed")})},l=()=>{$C(e,n)};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"📄"}),s.jsx("button",{onClick:l,title:"Open in Editor",className:"min-w-0 flex-1 truncate text-left font-mono text-fg-dim hover:text-fg hover:underline",children:e}),s.jsx("button",{onClick:o,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:r?"Copied":"Copy"})]})}const PC={skill:"border-sage/60 bg-sage/10 text-sage",mcp:"border-accent/60 bg-accent/10 text-accent",tool:"border-line bg-elev text-fg-dim"},DC={skill:"🧩",mcp:"🔌",tool:"⚙"};function OC(e){const n=[];for(const r of e){const i=n[n.length-1];i&&i.kind===r.kind&&i.label===r.label?(i.count+=1,i.id=r.id):n.push({id:r.id,kind:r.kind,label:r.label,count:1})}return n}function LC(e){return e.count>1?`${e.label} ×${e.count}`:e.label}function iw({items:e,running:n=!1}){if(!(e!=null&&e.length))return null;const r=OC(e),i=r.length-1;return s.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[r.map((o,l)=>{const d=n&&l===i;return s.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-mono font-medium ${d?"border-accent/40 bg-accent/10 text-accent":PC[o.kind]}`,children:[DC[o.kind]," ",LC(o)]},o.id)}),s.jsxs("span",{className:"text-[10px] font-mono text-fg-dim",children:["· ",e.length," steps"]})]})}const zC="text-[#8a2f28]",_A="border-[#b8443c]/40 bg-[#b8443c]/10",em="text-[#7a5416]",bx="border-[#8e641a]/40 bg-[#8e641a]/10",kA=1180,R1={overview:"Overview",terminal:"Terminal",browser:"Browser","system-prompt":"System Prompt",settings:"Settings",permissions:"Permissions",skills:"Skills",plugins:"Plugins",mcp:"MCP Servers",hooks:"Hooks",subagents:"Subagents",memory:"Memory",projects:"Projects",history:"History",keybindings:"Keybindings",usage:"Usage",scheduler:"Scheduler",editor:"Editor",voice:"Voice",repoviz:"Repo Viz",search:"Search",remote:"Remote"};function SA(){const[e,n]=L.useState(()=>window.innerWidth);return L.useEffect(()=>{const r=()=>n(window.innerWidth);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function CA({cwd:e,label:n,running:r,queuedPosition:i,stream:o,liveToolUses:l}){const d=OC(l),u=r&&!o?d.length-1:-1;return s.jsxs("div",{className:"w-[280px] shrink-0 overflow-y-auto border-l border-rule px-3 py-4",children:[s.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5",children:[s.jsx("div",{className:"text-xs font-semibold text-fg",children:n}),s.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-fg-dim",title:e,children:e}),s.jsx("div",{className:"mt-2 flex items-center gap-1.5 text-[11px] text-fg-dim",children:r?i>0?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-butter"}),"queued · #",i]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-accent"}),"running"]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-line"}),"idle"]})})]}),s.jsx("div",{className:"mt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"This turn"}),d.length===0?s.jsx("div",{className:"mt-1.5 text-[11px] text-fg-faint",children:"No tool activity yet."}):s.jsx("ul",{className:"mt-1.5 space-y-1",children:d.map((h,m)=>s.jsxs("li",{className:`flex items-center gap-1.5 rounded border px-1.5 py-1 text-[11px] font-mono ${m===u?"border-accent/40 bg-accent/10 text-accent":PC[h.kind]}`,children:[m===u?s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}):s.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:DC[h.kind]}),s.jsx("span",{className:"truncate",children:LC(h)})]},h.id))})]})}function jA(e){uA(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function EA({tickets:e}){return s.jsxs("div",{className:"w-[260px] shrink-0 overflow-y-auto border-l border-rule px-3 py-4","data-testid":"chat-queue-panel",children:[s.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Prompt queue"}),e.length===0?s.jsx(Vt,{title:"No prompts queued",hint:"Prompts sent while a turn is running will show up here."}):s.jsx("ul",{className:"space-y-2",children:e.map(n=>{var r;return s.jsxs("li",{className:"rounded-lg border border-line bg-elev px-2.5 py-2","data-testid":"chat-queue-ticket",children:[s.jsx(sw,{status:lA(n.status)}),s.jsx("div",{className:"mt-1.5 truncate text-xs text-fg-dim",title:n.text,children:n.text}),n.status==="dispatched-to-prd"&&!!((r=n.prdSlugs)!=null&&r.length)&&s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:n.prdSlugs.map(i=>s.jsxs("button",{onClick:()=>jA(i),title:`Open PRD "${i}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[10px] text-accent hover:bg-hi",children:["#",i]},i))})]},n.id)})})]})}const NA="needs interactive consent for an MCP server";function TA({turn:e,cwd:n,tabId:r,runActive:i=!1,consentActionDisabled:o=!1}){const l=L.useRef(null),d=e.role==="assistant"?aA(e,i):null;if(L.useEffect(()=>{e.role==="assistant"&&d==="text"&&l.current&&D$(l.current)},[e.role,d,e.text]),e.role==="user")return s.jsx("div",{className:"flex justify-end",children:s.jsx("div",{className:"max-w-[80%] rounded-tl-lg rounded-tr-lg rounded-bl-lg rounded-br-sm bg-accent/15 px-3 py-2 text-sm text-fg whitespace-pre-wrap",children:e.text})});if(e.role==="error")return s.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${_A} ${zC}`,children:e.text});if(e.role==="question")return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsx(iw,{items:e.toolUses}),s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"❓"}),"Needs your answer"]}),s.jsx("ul",{className:"list-disc space-y-1 pl-5",children:(e.questions??[e.text]).map((x,g)=>s.jsx("li",{children:x},g))}),s.jsx("div",{className:`mt-2 border-t pt-2 text-[11px] opacity-70 ${bx}`,children:"Reply in the composer below to answer."})]});if(e.role==="notice"){const x=e.text.includes(NA),g=()=>{vt.getState().queueRawCommand(r,"/design consent"),vt.getState().wakeTab(r)};return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"ℹ️"}),"Needs your attention"]}),e.text,x&&s.jsx("div",{className:`mt-2 border-t pt-2 ${bx}`,children:s.jsx("button",{onClick:g,disabled:o,title:o?"Cancel or wait for the current run before opening a raw session":"Open a live interactive claude session with /design consent pre-typed",className:`rounded border px-2 py-1 text-xs font-medium hover:bg-white/10 disabled:opacity-40 disabled:hover:bg-transparent ${em} border-current`,children:"Grant consent →"})})]})}if(d==="suppress")return null;const u=F$(e.text),h=L$(e.text),m=vA(e.text);return s.jsxs("div",{className:"flex max-w-[90%] items-start gap-2",children:[s.jsx("div",{className:"flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border border-line bg-elev text-xs font-semibold text-accent",children:"C"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx(iw,{items:e.toolUses,running:d==="working"}),d==="working"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"working…"]})}):d==="placeholder"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm italic text-fg-dim",children:"(no textual reply — see tool activity above)"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:l,className:`prose-chat rounded-lg bg-elev px-3 py-2 text-sm leading-relaxed text-fg ${m?"prose-chat--plan":""}`,onClick:x=>{oA(x,n)},dangerouslySetInnerHTML:{__html:iA(e.text)}}),u.map(x=>s.jsx(bA,{url:x},x)),h.map(x=>s.jsx(wA,{path:x,cwd:n},x))]})]})]})}function $A({tabId:e,cwd:n}){const r=vt(oe=>oe.tabs.find(ie=>ie.id===e)),i=(r==null?void 0:r.sessionId)??e,o=Gs(oe=>oe.chats[e]),l=Gs(oe=>oe.send),d=Gs(oe=>oe.hydrate),u=Gs(oe=>oe.resetThread),h=Gs(oe=>oe.pushNotice),[m,x]=L.useState(""),[g,v]=L.useState(!1),[S,E]=L.useState(null),j=L.useRef(null),y=L.useRef(null),_=SA()>kA,C=(o==null?void 0:o.turns)??[],N=(o==null?void 0:o.running)??!1,$=(o==null?void 0:o.stream)??"",R=(o==null?void 0:o.queuedPosition)??0,O=(o==null?void 0:o.liveToolUses)??[],I=cA((o==null?void 0:o.ticketHistory)??[],o==null?void 0:o.activeTicket,(o==null?void 0:o.queue)??[]);L.useEffect(()=>{d({tabId:e,cwd:n,sessionId:i})},[e]),L.useEffect(()=>{var oe;(oe=j.current)==null||oe.scrollTo({top:j.current.scrollHeight})},[C.length,$,N]);const z=()=>{if(!m.trim())return;const oe=W$(m.trim());if(oe.type==="nav"){x(""),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:oe.key}));const ie=`→ opened ${R1[oe.key]} — showing the live list`;h(e,ie),Le.info(`Opened ${R1[oe.key]} — showing the live list`);return}oe.type==="warn-unrouted"&&Le.info('Interactive prompts (consent/approval dialogs) need a real terminal — use "Open raw session" if this command asks you something and nothing appears.'),l({tabId:e,sessionId:i,cwd:n,prompt:m}),x(""),E(null)},U=oe=>{oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),z())},W=oe=>{const ie=oe.currentTarget,X=ie.selectionStart??m.length,Q=ie.selectionEnd??X;oe.preventDefault(),(async()=>{try{const J=await q$({pasteImage:()=>window.api.clipboard.pasteImage(),readText:()=>window.api.clipboard.pasteText().then(le=>le.ok?le.text:"")},m,X,Q);x(J.value),J.toast&&Le.info(J.toast),J.imagePath&&E(J.imagePath),requestAnimationFrame(()=>{try{ie.setSelectionRange(J.caret,J.caret)}catch{}})}catch(J){Le.error(J instanceof Error?J.message:"Paste failed — clipboard unavailable")}})()};L.useEffect(()=>{if(!g)return;const oe=ie=>{var X;(X=y.current)!=null&&X.contains(ie.target)||v(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[g]);const Y=()=>{vt.getState().wakeTab(e)},V=oe=>{vt.getState().wakeTab(e,oe),v(!1)},[H,te]=L.useState(!1),ae=()=>{if(!N){if(!H){te(!0);return}vt.getState().newSession(e),u(e),te(!1)}};return s.jsxs("div",{className:"flex h-full w-full flex-col bg-bg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"font-serif text-base text-fg",children:"Chat"}),s.jsx("div",{className:"text-xs text-fg-dim",children:"Chat · headless session — no process runs between commands"}),s.jsx(Zy,{active:"terminal"})]}),s.jsxs("div",{className:"flex items-stretch gap-2",children:[s.jsx("button",{onClick:ae,onBlur:()=>te(!1),disabled:N,title:"Start a brand-new session (clears this conversation's context; shared by both Chat and Raw)",className:`rounded border px-2 py-1 text-xs hover:bg-elev disabled:opacity-40 disabled:hover:bg-transparent ${H?"border-accent/60 text-accent":"border-line text-fg-dim hover:text-fg"}`,children:H?"Confirm new session?":"New session"}),s.jsxs("div",{ref:y,className:"relative flex items-stretch",children:[s.jsx("button",{onClick:Y,disabled:N,className:"rounded-l border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:N?"Cancel or wait for the current run before opening a raw session":"Drop into a live interactive claude session in this directory",children:"Open raw session ⌃"}),s.jsx("button",{onClick:()=>v(oe=>!oe),disabled:N,className:"rounded-r border border-l-0 border-line px-1.5 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:"Choose model for this raw session",children:"▾"}),g&&s.jsx("div",{className:"absolute right-0 top-full z-10 mt-1 w-32 rounded border border-line bg-hi shadow-lg",children:Yw.map(oe=>s.jsx("button",{onClick:()=>V(oe),className:"block w-full px-3 py-1.5 text-left text-xs text-fg-dim hover:bg-elev hover:text-fg",children:oe.charAt(0).toUpperCase()+oe.slice(1)},oe))})]})]})]}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{ref:j,className:"min-w-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[C.length===0&&!N&&s.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Type a command to start a session. It runs, reports back, and asks if it needs you."}),C.map((oe,ie)=>s.jsx(TA,{turn:oe,cwd:n,tabId:e,runActive:N&&oe.role==="assistant"&&ie===C.length-1,consentActionDisabled:N},oe.id)),N&&s.jsxs("div",{className:"max-w-[90%]",children:[s.jsx(iw,{items:O,running:N&&!$}),s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:R>0?s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",R," — waiting for a free run slot"]}):$?s.jsx("span",{className:"whitespace-pre-wrap",children:$}):s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})]})]}),s.jsx(EA,{tickets:I}),_&&s.jsx(CA,{cwd:n,label:(r==null?void 0:r.label)??n,running:N,queuedPosition:R,stream:$,liveToolUses:O})]}),s.jsxs("div",{className:"border-t border-rule p-3",children:[S&&s.jsx(MC,{path:S,onDismiss:()=>E(null)},S),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsx("textarea",{value:m,onChange:oe=>x(oe.target.value),onKeyDown:U,onPaste:W,rows:2,placeholder:N?"Running… send to queue a follow-up prompt":"Type a command (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),N&&s.jsx("button",{onClick:()=>window.api.chat.cancel(e),className:`rounded-md border px-3 py-2 text-sm hover:bg-[#b8443c]/10 ${zC} border-[#b8443c]/40`,children:"Cancel"}),s.jsx("button",{onClick:z,disabled:!m.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})]})]})}const ow="\x1B[38;5;240m",aw="\x1B[0m",AA=/\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;function RA(e){return e.replace(AA,"")}function MA(e){var l;if(!e||typeof e!="object")return null;const n=e,r=n.type==="user"?"You":n.type==="assistant"?"Claude":null;if(!r)return null;const i=(l=n.message)==null?void 0:l.content;if(!Array.isArray(i))return null;const o=i.filter(d=>(d==null?void 0:d.type)==="text"&&typeof d.text=="string").map(d=>RA(d.text).trim()).filter(Boolean).join(`
|
|
2962
|
+
`+En),Kt&&(En=cs(En)),R&&nn?Y(En):En},n.setConfig=function(){let ft=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$a(ft),Br=!0,Tr=Je,nt=xt},n.clearConfig=function(){Ct=null,Br=!1,Tr=null,nt=null,R=I,O=""},n.isValidAttribute=function(ft,be,Pe){Ct||$a({});const Qe=_n(ft),Et=_n(be);return Ps(Qe,Et,Pe)},n.addHook=function(ft,be){typeof be=="function"&&ns(J,ft)&&Eh(J[ft],be)},n.removeHook=function(ft,be){if(ns(J,ft)){if(be!==void 0){const Pe=M3(J[ft],be);return Pe===-1?void 0:I3(J[ft],Pe,1)[0]}return y1(J[ft])}},n.removeHooks=function(ft){ns(J,ft)&&(J[ft]=[])},n.removeAllHooks=function(){J=T1()},n}var d0=TC();const by=new wn.Renderer,sA=by.table.bind(by);by.table=e=>`<div class="prose-chat-table-wrap">${sA(e)}</div>`;function iA(e){return d0.sanitize(wn.parse(e,{async:!1,breaks:!0,renderer:by}))}async function $C(e,n=""){if(!e)return;const r=e.replace(/(?::\d+)+$/,""),i=a1(e,n),o=await window.api.files.read(i.absPath);if(!o.ok&&o.error==="path outside home"){Le.error("That path is outside the project and can't be opened.");return}let l=o.ok?i:null,d=0;if(!l&&!r.startsWith("/")){const u=Array.from(new Set(vt.getState().tabs.map(h=>h.cwd).filter(h=>h&&h!==n)));for(const h of u){const m=a1(e,h),x=await window.api.files.read(m.absPath);if(d++,x.ok){l=m;break}}}if(!l){const u=d===1?"tab":"tabs";Le.error(`${o.error||"Not found"} under ${n} (tried ${d} other open ${u})`);return}Tn.getState().openFile(l.absPath,{line:l.line,col:l.col}),window.dispatchEvent(new CustomEvent("sm:open-editor"))}async function oA(e,n=""){const r=e.target,i=r.closest("a");if(i){const d=i.getAttribute("href")||"";/^https?:\/\//i.test(d)&&(e.preventDefault(),window.api.shell.open({as:"external",url:d}).catch(()=>{}));return}const o=r.closest(`[${Zb}]`);if(!o)return;const l=o.getAttribute(Zb)??"";await $C(l,n)}function aA(e,n){var r;return e.text.trim().length>0?"text":n?"working":(r=e.toolUses)!=null&&r.length?"placeholder":"suppress"}function lA(e){switch(e){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed"}}function cA(e,n,r){return[...e,...n?[n]:[],...r]}let rw=null;function uA(e){rw=e,window.dispatchEvent(new CustomEvent("sm:select-prd",{detail:e}))}function dA(){const e=rw;return rw=null,e}const $1=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function hA(e){let n=0;for(let r=0;r<e.length;r++)n=n*31+e.charCodeAt(r)>>>0;return n}function bc(e){return $1[hA(e)%$1.length]}function Wo(e){if(!e)return null;const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function fA(e,n){const r=e?Wo(e)??"":n??"";return bc(r)}const pA={running:"bg-accent text-white",pending:"bg-bg text-fg-dim border border-line",completed:"bg-sage/20 text-sage",needs_review:"bg-butter/25 text-fg-dim",failed:"bg-accent/15 text-accent"},mA={pending:"○",completed:"✓",needs_review:"!",failed:"✕"};function AC({status:e}){const n=mA[e];return s.jsxs("span",{className:`inline-flex items-center gap-1.5 shrink-0 px-2.5 py-1 rounded-lg min-w-[104px] justify-center text-xs font-semibold tracking-wide ${pA[e]}`,role:"status","aria-label":`Status: ${e.replace("_"," ")}`,children:[e==="running"?s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):n&&s.jsx("span",{"aria-hidden":"true",children:n}),e.replace("_"," ")]})}function h0({cwd:e,name:n}){const r=n??(e?Wo(e)??e:"—"),i=fA(e,n);return s.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:i},"aria-hidden":"true"}),r]})}function gc({label:e,children:n}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:e}),s.jsx("div",{className:"grid gap-1.5",children:n})]})}function ss({k:e,v:n,wrap:r}){return s.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[s.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:e}),s.jsx("span",{className:`text-fg ${r?"break-all":""}`,children:n})]})}function qv({dotClass:e,n,label:r}){return s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-fg-dim",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${e}`,"aria-hidden":"true"}),s.jsx("strong",{className:"text-fg font-mono text-[13.5px]",children:n})," ",r]})}const gA={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes",no_verdict_sentinel:"no commit or verdict sentinel",pass_no_commit:"PASS sentinel but no commit landed"};function wy(e){return gA[e]??e}function Ph(e){const n=e.match(/^(\d+)-/);return n?n[1]:null}function RC({n:e}){return s.jsxs("span",{className:"font-mono text-[12px] font-semibold text-fg-faint shrink-0 tracking-tight select-none","aria-hidden":"true",children:["#",e]})}const xA={running:{bg:"bg-butter/30",text:"text-fg-dim",border:!1,label:"running"},queued:{bg:"bg-sage/25",text:"text-sage",border:!1,label:"queued"},ready:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"ready to run"},draft:{bg:"bg-bg",text:"text-fg-faint",border:!0,label:"draft"},completed:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"completed"},failed:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"failed"},needs_review:{bg:"bg-butter/25",text:"text-fg-dim",border:!1,label:"needs review"},dispatched:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"dispatched to PRD"}};function A1(e){return e?e.status==="pending"?"queued":e.status:"ready"}function sw({status:e}){const n=xA[e];return s.jsx("span",{role:"status","aria-label":`Status: ${n.label}`,className:`text-[11.5px] font-semibold px-[9px] py-0.5 rounded-full ${n.bg} ${n.text}${n.border?" ring-1 ring-inset ring-line":""}`,children:n.label})}function MC({path:e,onDismiss:n}){const[r,i]=L.useState(!1);return r?null:s.jsxs("div",{className:"mb-2 inline-flex max-w-[160px] items-start gap-1.5 rounded-md border border-line bg-elev p-1.5",children:[s.jsx("img",{src:Qy(e),alt:"Pasted clipboard image",className:"max-h-[120px] max-w-[120px] rounded object-contain",draggable:!1,onError:()=>i(!0)}),s.jsx("button",{type:"button",onClick:n,title:"Dismiss preview",className:"shrink-0 rounded text-fg-faint hover:bg-hi hover:text-fg",children:"✕"})]})}function Vt({title:e,hint:n}){return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("div",{className:"mb-2 text-fg-dim",children:e}),n&&s.jsx("div",{className:"text-fg-faint",children:n})]})})}const yA=/^\s*(?:[-*+]\s+.+|\d+\.\s+.+)/m;function vA(e){return yA.test(e)}function IC(e,n){window.api.clipboard.writeText(e).then(r=>n(!!(r!=null&&r.ok))).catch(()=>n(!1))}function bA({url:e}){const[n,r]=L.useState(!1),i=()=>{IC(e,o=>{o?(r(!0),setTimeout(()=>r(!1),1100)):Le.error("Copy failed")})};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"🔗"}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-fg-dim",children:e}),s.jsx("button",{onClick:i,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:n?"Copied":"Copy"})]})}function wA({path:e,cwd:n}){const[r,i]=L.useState(!1),o=()=>{IC(e,d=>{d?(i(!0),setTimeout(()=>i(!1),1100)):Le.error("Copy failed")})},l=()=>{$C(e,n)};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"📄"}),s.jsx("button",{onClick:l,title:"Open in Editor",className:"min-w-0 flex-1 truncate text-left font-mono text-fg-dim hover:text-fg hover:underline",children:e}),s.jsx("button",{onClick:o,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:r?"Copied":"Copy"})]})}const PC={skill:"border-sage/60 bg-sage/10 text-sage",mcp:"border-accent/60 bg-accent/10 text-accent",tool:"border-line bg-elev text-fg-dim"},DC={skill:"🧩",mcp:"🔌",tool:"⚙"};function OC(e){const n=[];for(const r of e){const i=n[n.length-1];i&&i.kind===r.kind&&i.label===r.label?(i.count+=1,i.id=r.id):n.push({id:r.id,kind:r.kind,label:r.label,count:1})}return n}function LC(e){return e.count>1?`${e.label} ×${e.count}`:e.label}function iw({items:e,running:n=!1}){if(!(e!=null&&e.length))return null;const r=OC(e),i=r.length-1;return s.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[r.map((o,l)=>{const d=n&&l===i;return s.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-mono font-medium ${d?"border-accent/40 bg-accent/10 text-accent":PC[o.kind]}`,children:[DC[o.kind]," ",LC(o)]},o.id)}),s.jsxs("span",{className:"text-[10px] font-mono text-fg-dim",children:["· ",e.length," steps"]})]})}const zC="text-[#8a2f28]",_A="border-[#b8443c]/40 bg-[#b8443c]/10",em="text-[#7a5416]",bx="border-[#8e641a]/40 bg-[#8e641a]/10",kA=1180,R1={overview:"Overview",terminal:"Terminal",browser:"Browser","system-prompt":"System Prompt",settings:"Settings",permissions:"Permissions",skills:"Skills",plugins:"Plugins",mcp:"MCP Servers",hooks:"Hooks",subagents:"Subagents",memory:"Memory",projects:"Projects",history:"History",keybindings:"Keybindings",usage:"Usage",scheduler:"Scheduler",editor:"Editor",voice:"Voice",repoviz:"Repo Viz",search:"Search",remote:"Remote"};function SA(){const[e,n]=L.useState(()=>window.innerWidth);return L.useEffect(()=>{const r=()=>n(window.innerWidth);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function CA({cwd:e,label:n,running:r,queuedPosition:i,stream:o,liveToolUses:l}){const d=OC(l),u=r&&!o?d.length-1:-1;return s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto border-b border-rule px-3 py-4",children:[s.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5",children:[s.jsx("div",{className:"text-xs font-semibold text-fg",children:n}),s.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-fg-dim",title:e,children:e}),s.jsx("div",{className:"mt-2 flex items-center gap-1.5 text-[11px] text-fg-dim",children:r?i>0?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-butter"}),"queued · #",i]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-accent"}),"running"]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-line"}),"idle"]})})]}),s.jsx("div",{className:"mt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"This turn"}),d.length===0?s.jsx("div",{className:"mt-1.5 text-[11px] text-fg-faint",children:"No tool activity yet."}):s.jsx("ul",{className:"mt-1.5 space-y-1",children:d.map((h,m)=>s.jsxs("li",{className:`flex items-center gap-1.5 rounded border px-1.5 py-1 text-[11px] font-mono ${m===u?"border-accent/40 bg-accent/10 text-accent":PC[h.kind]}`,children:[m===u?s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}):s.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:DC[h.kind]}),s.jsx("span",{className:"truncate",children:LC(h)})]},h.id))})]})}function jA(e){uA(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function EA({tickets:e}){const n=L.useRef(null),r=L.useRef(!0),i=()=>{const l=n.current;l&&(r.current=l.scrollHeight-l.scrollTop-l.clientHeight<8)},o=e.map(l=>`${l.id}:${l.status}`).join(",");return L.useEffect(()=>{const l=n.current;l&&r.current&&(l.scrollTop=l.scrollHeight)},[o]),s.jsxs("div",{ref:n,onScroll:i,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4","data-testid":"chat-queue-panel",children:[s.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Prompt queue"}),e.length===0?s.jsx(Vt,{title:"No prompts queued",hint:"Prompts sent while a turn is running will show up here."}):s.jsx("ul",{className:"space-y-2",children:e.map(l=>{var d;return s.jsxs("li",{className:"rounded-lg border border-line bg-elev px-2.5 py-2","data-testid":"chat-queue-ticket",children:[s.jsx(sw,{status:lA(l.status)}),s.jsx("div",{className:"mt-1.5 truncate text-xs text-fg-dim",title:l.text,children:l.text}),l.status==="dispatched-to-prd"&&!!((d=l.prdSlugs)!=null&&d.length)&&s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:l.prdSlugs.map(u=>s.jsxs("button",{onClick:()=>jA(u),title:`Open PRD "${u}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[10px] text-accent hover:bg-hi",children:["#",u]},u))})]},l.id)})})]})}const NA="needs interactive consent for an MCP server";function TA({turn:e,cwd:n,tabId:r,runActive:i=!1,consentActionDisabled:o=!1}){const l=L.useRef(null),d=e.role==="assistant"?aA(e,i):null;if(L.useEffect(()=>{e.role==="assistant"&&d==="text"&&l.current&&D$(l.current)},[e.role,d,e.text]),e.role==="user")return s.jsx("div",{className:"flex justify-end",children:s.jsx("div",{className:"max-w-[80%] rounded-tl-lg rounded-tr-lg rounded-bl-lg rounded-br-sm bg-accent/15 px-3 py-2 text-sm text-fg whitespace-pre-wrap",children:e.text})});if(e.role==="error")return s.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${_A} ${zC}`,children:e.text});if(e.role==="question")return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsx(iw,{items:e.toolUses}),s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"❓"}),"Needs your answer"]}),s.jsx("ul",{className:"list-disc space-y-1 pl-5",children:(e.questions??[e.text]).map((x,g)=>s.jsx("li",{children:x},g))}),s.jsx("div",{className:`mt-2 border-t pt-2 text-[11px] opacity-70 ${bx}`,children:"Reply in the composer below to answer."})]});if(e.role==="notice"){const x=e.text.includes(NA),g=()=>{vt.getState().queueRawCommand(r,"/design consent"),vt.getState().wakeTab(r)};return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"ℹ️"}),"Needs your attention"]}),e.text,x&&s.jsx("div",{className:`mt-2 border-t pt-2 ${bx}`,children:s.jsx("button",{onClick:g,disabled:o,title:o?"Cancel or wait for the current run before opening a raw session":"Open a live interactive claude session with /design consent pre-typed",className:`rounded border px-2 py-1 text-xs font-medium hover:bg-white/10 disabled:opacity-40 disabled:hover:bg-transparent ${em} border-current`,children:"Grant consent →"})})]})}if(d==="suppress")return null;const u=F$(e.text),h=L$(e.text),m=vA(e.text);return s.jsxs("div",{className:"flex max-w-[90%] items-start gap-2",children:[s.jsx("div",{className:"flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border border-line bg-elev text-xs font-semibold text-accent",children:"C"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx(iw,{items:e.toolUses,running:d==="working"}),d==="working"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"working…"]})}):d==="placeholder"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm italic text-fg-dim",children:"(no textual reply — see tool activity above)"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:l,className:`prose-chat rounded-lg bg-elev px-3 py-2 text-sm leading-relaxed text-fg ${m?"prose-chat--plan":""}`,onClick:x=>{oA(x,n)},dangerouslySetInnerHTML:{__html:iA(e.text)}}),u.map(x=>s.jsx(bA,{url:x},x)),h.map(x=>s.jsx(wA,{path:x,cwd:n},x))]})]})]})}function $A({tabId:e,cwd:n}){const r=vt(oe=>oe.tabs.find(ie=>ie.id===e)),i=(r==null?void 0:r.sessionId)??e,o=Gs(oe=>oe.chats[e]),l=Gs(oe=>oe.send),d=Gs(oe=>oe.hydrate),u=Gs(oe=>oe.resetThread),h=Gs(oe=>oe.pushNotice),[m,x]=L.useState(""),[g,v]=L.useState(!1),[S,E]=L.useState(null),j=L.useRef(null),y=L.useRef(null),_=SA()>kA,C=(o==null?void 0:o.turns)??[],N=(o==null?void 0:o.running)??!1,$=(o==null?void 0:o.stream)??"",R=(o==null?void 0:o.queuedPosition)??0,O=(o==null?void 0:o.liveToolUses)??[],I=cA((o==null?void 0:o.ticketHistory)??[],o==null?void 0:o.activeTicket,(o==null?void 0:o.queue)??[]);L.useEffect(()=>{d({tabId:e,cwd:n,sessionId:i})},[e]),L.useEffect(()=>{var oe;(oe=j.current)==null||oe.scrollTo({top:j.current.scrollHeight})},[C.length,$,N]);const z=()=>{if(!m.trim())return;const oe=W$(m.trim());if(oe.type==="nav"){x(""),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:oe.key}));const ie=`→ opened ${R1[oe.key]} — showing the live list`;h(e,ie),Le.info(`Opened ${R1[oe.key]} — showing the live list`);return}oe.type==="warn-unrouted"&&Le.info('Interactive prompts (consent/approval dialogs) need a real terminal — use "Open raw session" if this command asks you something and nothing appears.'),l({tabId:e,sessionId:i,cwd:n,prompt:m}),x(""),E(null)},U=oe=>{oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),z())},W=oe=>{const ie=oe.currentTarget,X=ie.selectionStart??m.length,Q=ie.selectionEnd??X;oe.preventDefault(),(async()=>{try{const J=await q$({pasteImage:()=>window.api.clipboard.pasteImage(),readText:()=>window.api.clipboard.pasteText().then(le=>le.ok?le.text:"")},m,X,Q);x(J.value),J.toast&&Le.info(J.toast),J.imagePath&&E(J.imagePath),requestAnimationFrame(()=>{try{ie.setSelectionRange(J.caret,J.caret)}catch{}})}catch(J){Le.error(J instanceof Error?J.message:"Paste failed — clipboard unavailable")}})()};L.useEffect(()=>{if(!g)return;const oe=ie=>{var X;(X=y.current)!=null&&X.contains(ie.target)||v(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[g]);const Y=()=>{vt.getState().wakeTab(e)},V=oe=>{vt.getState().wakeTab(e,oe),v(!1)},[H,te]=L.useState(!1),ae=()=>{if(!N){if(!H){te(!0);return}vt.getState().newSession(e),u(e),te(!1)}};return s.jsxs("div",{className:"flex h-full w-full flex-col bg-bg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"font-serif text-base text-fg",children:"Chat"}),s.jsx("div",{className:"text-xs text-fg-dim",children:"Chat · headless session — no process runs between commands"}),s.jsx(Zy,{active:"terminal"})]}),s.jsxs("div",{className:"flex items-stretch gap-2",children:[s.jsx("button",{onClick:ae,onBlur:()=>te(!1),disabled:N,title:"Start a brand-new session (clears this conversation's context; shared by both Chat and Raw)",className:`rounded border px-2 py-1 text-xs hover:bg-elev disabled:opacity-40 disabled:hover:bg-transparent ${H?"border-accent/60 text-accent":"border-line text-fg-dim hover:text-fg"}`,children:H?"Confirm new session?":"New session"}),s.jsxs("div",{ref:y,className:"relative flex items-stretch",children:[s.jsx("button",{onClick:Y,disabled:N,className:"rounded-l border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:N?"Cancel or wait for the current run before opening a raw session":"Drop into a live interactive claude session in this directory",children:"Open raw session ⌃"}),s.jsx("button",{onClick:()=>v(oe=>!oe),disabled:N,className:"rounded-r border border-l-0 border-line px-1.5 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:"Choose model for this raw session",children:"▾"}),g&&s.jsx("div",{className:"absolute right-0 top-full z-10 mt-1 w-32 rounded border border-line bg-hi shadow-lg",children:Yw.map(oe=>s.jsx("button",{onClick:()=>V(oe),className:"block w-full px-3 py-1.5 text-left text-xs text-fg-dim hover:bg-elev hover:text-fg",children:oe.charAt(0).toUpperCase()+oe.slice(1)},oe))})]})]})]}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{ref:j,className:"min-w-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[C.length===0&&!N&&s.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Type a command to start a session. It runs, reports back, and asks if it needs you."}),C.map((oe,ie)=>s.jsx(TA,{turn:oe,cwd:n,tabId:e,runActive:N&&oe.role==="assistant"&&ie===C.length-1,consentActionDisabled:N},oe.id)),N&&s.jsxs("div",{className:"max-w-[90%]",children:[s.jsx(iw,{items:O,running:N&&!$}),s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:R>0?s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",R," — waiting for a free run slot"]}):$?s.jsx("span",{className:"whitespace-pre-wrap",children:$}):s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})]})]}),s.jsxs("div",{className:"flex h-full w-[280px] shrink-0 flex-col border-l border-rule",children:[_&&s.jsx(CA,{cwd:n,label:(r==null?void 0:r.label)??n,running:N,queuedPosition:R,stream:$,liveToolUses:O}),s.jsx(EA,{tickets:I})]})]}),s.jsxs("div",{className:"border-t border-rule p-3",children:[S&&s.jsx(MC,{path:S,onDismiss:()=>E(null)},S),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsx("textarea",{value:m,onChange:oe=>x(oe.target.value),onKeyDown:U,onPaste:W,rows:2,placeholder:N?"Running… send to queue a follow-up prompt":"Type a command (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),N&&s.jsx("button",{onClick:()=>window.api.chat.cancel(e),className:`rounded-md border px-3 py-2 text-sm hover:bg-[#b8443c]/10 ${zC} border-[#b8443c]/40`,children:"Cancel"}),s.jsx("button",{onClick:z,disabled:!m.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})]})]})}const ow="\x1B[38;5;240m",aw="\x1B[0m",AA=/\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;function RA(e){return e.replace(AA,"")}function MA(e){var l;if(!e||typeof e!="object")return null;const n=e,r=n.type==="user"?"You":n.type==="assistant"?"Claude":null;if(!r)return null;const i=(l=n.message)==null?void 0:l.content;if(!Array.isArray(i))return null;const o=i.filter(d=>(d==null?void 0:d.type)==="text"&&typeof d.text=="string").map(d=>RA(d.text).trim()).filter(Boolean).join(`
|
|
2963
2963
|
`);return o?`${ow}[${r}] ${o}${aw}\r
|
|
2964
2964
|
`:null}function IA(e){const n=e.filter(r=>r.kind==="message").map(r=>MA(r.data)).filter(r=>r!==null);return n.length===0?null:`${ow}── prior conversation (from transcript) ──${aw}\r
|
|
2965
2965
|
`+n.join("")+`${ow}── end prior conversation ──${aw}\r
|
|
@@ -3390,7 +3390,7 @@ tools:
|
|
|
3390
3390
|
|
|
3391
3391
|
${r}`}const km={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},OO=["popover","review","diff"],wj=["popover","review"];function LO(e,n){switch(n.type){case"SELECT":return{...km,editCount:e.editCount,phase:"popover",selection:n.selection};case"CANCEL":return{...km,editCount:e.editCount};case"LISTEN":return wj.includes(e.phase)?{...e,phase:"listening",transcript:"",modelStatus:null}:e;case"HEARD":return e.phase!=="listening"?e:{...e,phase:"review",transcript:n.transcript,modelStatus:null};case"RUN":return OO.includes(e.phase)?{...e,phase:"thinking",instruction:n.recordInstruction?n.instruction:e.instruction}:e;case"RUN_OK":return e.phase!=="thinking"?e:{...e,phase:"diff",diff:n.diff};case"RUN_ERR":return e.phase!=="thinking"?e:{...e,phase:"popover",transcript:"",diff:null};case"ACCEPT":return e.phase!=="diff"?e:{...km,editCount:e.editCount+1};case"RESET_FILE":return{...km,editCount:0};case"MODEL_STATUS":return e.phase!=="listening"?e:{...e,modelStatus:`${n.status}: ${n.message}`};default:return e}}function zO(e,n){let r=null;for(const i of n){const o=i.cwd;!o||!(e===o||e.startsWith(o.endsWith("/")?o:`${o}/`))||(r===null||o.length>r.length)&&(r=o)}return r}function BO(e,n,r){var l;let i=null,o=-1/0;for(const d of n){if(d.cwd!==e||d.status!=="dormant")continue;const u=((l=r[d.id])==null?void 0:l.lastEventAt)??0;(i===null||u>o)&&(i=d,o=u)}return i}const FO="sonnet";function UO(e,n){const[r,i]=L.useReducer(LO,km),o=L.useRef(0),l=L.useRef(null),d=L.useRef(e),u=L.useRef(new Map);L.useEffect(()=>window.api.docEdit.onSessionResult(C=>{const N=u.current.get(C.requestId);N&&(u.current.delete(C.requestId),N(C))}),[]),L.useEffect(()=>{d.current!==e&&(d.current=e,o.current+=1,h(),i({type:"RESET_FILE"}))},[e]);function h(){const C=l.current;C&&(l.current=null,C.stop().catch(()=>{}),C.destroy(),$t.setState({externalRecording:!1}))}const m=L.useCallback(C=>{o.current+=1,h(),i({type:"SELECT",selection:C})},[]),x=L.useCallback(()=>{o.current+=1,h(),i({type:"CANCEL"})},[]),g=L.useCallback(()=>{if(!wj.includes(r.phase))return;if($t.getState().isRecording){Le.error("Microphone is already in use");return}if(!Xy()){Le.error("Microphone or Web Worker not available");return}const C=++o.current;i({type:"LISTEN"}),$t.setState({externalRecording:!0});const N=()=>{l.current===$&&(l.current=null),$t.setState({externalRecording:!1})},$=G2({onFinal:R=>{if(o.current!==C)return;$.stop().catch(()=>{}),$.destroy(),N();const O=R.trim();if(!O){i({type:"CANCEL"});return}i({type:"HEARD",transcript:O})},onError:R=>{o.current===C&&($.destroy(),N(),Le.error(`Microphone error: ${R}`),i({type:"CANCEL"}))},onModelStatus:(R,O)=>{o.current===C&&i({type:"MODEL_STATUS",status:R,message:O})},onProgress:R=>{o.current===C&&i({type:"MODEL_STATUS",status:"loading",message:`${R}%`})}});l.current=$,$.start().catch(R=>{o.current===C&&($.destroy(),N(),Le.error(`Could not start mic: ${R instanceof Error?R.message:String(R)}`),i({type:"CANCEL"}))})},[r.phase]),v=L.useCallback(()=>{const C=zO(e,vt.getState().tabs);if(!C)return null;const N=BO(C,vt.getState().tabs,$m.getState().tabs);return!N||Gs.getState().get(N.id).running?null:N},[e]),S=L.useCallback((C,N,$,R,O,I)=>{const z=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{u.current.set(z,U),window.api.docEdit.runInSession({tabId:C,sessionId:N,cwd:$,before:R,instruction:O,documentText:I,requestId:z})})},[]),E=L.useCallback(async(C,N)=>{const $=r.selection;if(!$)return;const R=++o.current;i({type:"RUN",instruction:C,recordInstruction:N});const O=DO(n);try{const I=v(),z=I?await S(I.id,I.sessionId,I.cwd,$.text,C,O):await window.api.docEdit.run({path:e,before:$.text,instruction:C,documentText:O});if(o.current!==R)return;if(!z.ok){Le.error(z.error||"Edit failed"),i({type:"RUN_ERR"});return}i({type:"RUN_OK",diff:{before:$.text,after:z.after??""}})}catch(I){if(o.current!==R)return;Le.error(I instanceof Error?I.message:"Edit failed"),i({type:"RUN_ERR"})}},[e,r.selection,n,v,S]),j=L.useCallback(C=>{E(C,!0)},[E]),y=L.useCallback(()=>{r.phase==="review"&&E(r.transcript,!0)},[E,r.phase,r.transcript]),b=L.useCallback(()=>{const C=r.instruction;C&&E(`${C}
|
|
3392
3392
|
|
|
3393
|
-
(Give a different rewrite than the last one.)`,!1)},[E,r.instruction]),_=L.useCallback(C=>{const N=r.diff;if(!N)return{ok:!1,reason:"not-found"};const $=IO(C,N.before,N.after);return $.ok?(o.current+=1,i({type:"ACCEPT"})):Le.error($.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),$},[r.diff]);return{state:r,select:m,cancel:x,listen:g,sendHeard:y,run:j,retry:b,accept:_}}const HO=[{label:"Make concise",instruction:"Rewrite this text to be concise and specific. Preserve meaning and any markdown structure."},{label:"To bullet list",instruction:"Convert this text into a tight markdown bullet list."},{label:"Fix the tone",instruction:"Fix the tone: direct, professional, no hedging. Preserve meaning."}],Ck=320,om=8;function WO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function qO(e){const n=typeof window<"u"?window.innerWidth:1024,r=Math.min(Math.max(e.left,om),Math.max(om,n-Ck-om)),i=Math.max(e.top-om,om);return{position:"fixed",left:r,top:i,width:Ck,transform:"translateY(-100%)",zIndex:50}}function VO({phase:e,rect:n,diff:r,transcript:i,modelStatus:o,onQuickAction:l,onRunCustom:d,onListen:u,onSendHeard:h,onCancel:m,onAccept:x,onReject:g,onRetry:v}){const[S,E]=L.useState(""),j=()=>{const y=S.trim();y&&(d(y),E(""))};return s.jsxs("div",{"data-doc-edit-popover":!0,style:qO(n),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[e==="popover"&&s.jsxs("div",{className:"p-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex flex-wrap gap-1",children:[s.jsx("button",{onClick:u,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),HO.map(y=>s.jsx("button",{onClick:()=>l(y.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:y.label},y.label))]}),s.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),s.jsx("input",{autoFocus:!0,value:S,onChange:y=>E(y.target.value),onKeyDown:y=>{y.key==="Enter"?j():y.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),e==="listening"&&s.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[s.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(WO,{}),"Listening…"]}),o&&s.jsx("span",{className:"text-[10px] text-fg-faint",children:o})]}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[s.jsxs("p",{className:"italic text-fg mb-2",children:["«",i,"»"]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsxs("div",{className:"p-3 flex items-center justify-between",children:[s.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="diff"&&r&&s.jsxs("div",{className:"p-3",children:[s.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function GO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function jk({phase:e,transcript:n,diff:r,editCount:i,modelStatus:o,onListen:l,onSendHeard:d,onCancel:u,onAccept:h,onReject:m,onRetry:x}){return s.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[s.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),s.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Zm(FO)})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[e==="idle"&&s.jsxs("div",{className:"text-fg-faint",children:[s.jsx("p",{children:"Select text in the doc…"}),s.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),e==="popover"&&s.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),e==="listening"&&s.jsxs("div",{children:[s.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[s.jsx(GO,{}),"Listening…"]}),o&&s.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:o}),s.jsx("button",{onClick:u,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{children:[s.jsxs("p",{className:"italic text-fg mb-3",children:["«",n,"»"]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),e==="diff"&&r&&s.jsxs("div",{children:[s.jsxs("div",{className:"mb-3 space-y-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function Ek(e){return e.split("/").filter(Boolean).pop()||e}function KO({path:e,onRenamed:n,onDeleted:r}){const[i,o]=L.useState(!1),[l,d]=L.useState(!1),[u,h]=L.useState(""),[m,x]=L.useState(!1),g=Tn(U=>U.buffers[e]),v=Tn(U=>U.openFile),S=Tn(U=>U.renameOpenFile),E=Tn(U=>U.closeFile),j=uo(),y=Ek(e),b=()=>o(!1),_=()=>{h(y),d(!0),b()},C=async()=>{const U=u.trim();if(!U||U===y){d(!1);return}try{const W=await window.api.files.rename(e,U);if(W.ok){const Y=e.slice(0,e.lastIndexOf("/")),V=W.newPath??`${Y}/${U}`;S(e,V),n==null||n(e,V),Le.info(`Renamed to ${U}`)}else Le.error(W.error??`Couldn't rename ${y}`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't rename ${y}`)}d(!1)},N=async()=>{b();try{const U=await window.api.files.duplicate(e);U.ok&&U.path?(v(U.path),Le.info(`Duplicated as ${Ek(U.path)}`)):Le.error(U.error??`Couldn't duplicate ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't duplicate ${y}`)}},$=async()=>{try{const U=await window.api.files.delete(e);U.ok?(E(e),r==null||r(e),Le.info(`Deleted ${y}`)):Le.error(U.error??`Couldn't delete ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't delete ${y}`)}x(!1)},R=async()=>{b();const U=g??"";try{await navigator.clipboard.writeText(U),Le.info(`Copied ${U.length} chars`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't copy ${y}`)}},O=()=>{if(b(),!j){Le.error("No terminal tab is active");return}window.api.pty.write({tabId:j.id,data:`@${e} `}),Le.info(`Added ${y} to Claude context`)},I=()=>{b(),window.api.shell.open({as:"openPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't open ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't open ${y}`))},z=()=>{b(),window.api.shell.open({as:"revealPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't reveal ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't reveal ${y}`))};return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>o(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:b}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[s.jsx(ob,{children:"Edit"}),s.jsx(_u,{label:"Rename",onClick:_}),s.jsx(_u,{label:"Duplicate",onClick:N}),s.jsx(_u,{label:"Delete document",danger:!0,onClick:()=>{b(),x(!0)}}),s.jsx(Nk,{}),s.jsx(ob,{children:"Open"}),s.jsx(_u,{label:"Open in default app",onClick:I}),s.jsx(_u,{label:"Reveal in OS",onClick:z}),s.jsx(Nk,{}),s.jsx(ob,{children:"Export"}),s.jsx(_u,{label:"Copy as Markdown",onClick:R}),s.jsx(_u,{label:"Add to Claude context",onClick:O,disabled:!j,title:j?void 0:"No terminal tab is active"})]})]}),l&&s.jsx(XO,{value:u,onChange:h,onCancel:()=>d(!1),onConfirm:()=>void C()}),m&&s.jsx(YO,{name:y,onCancel:()=>x(!1),onConfirm:()=>void $()})]})}function ob({children:e}){return s.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:e})}function _u({label:e,onClick:n,danger:r,disabled:i,title:o}){return s.jsx("button",{onClick:n,disabled:i,title:o,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${r?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:e})}function Nk(){return s.jsx("div",{className:"my-1 border-t border-line"})}function XO({value:e,onChange:n,onCancel:r,onConfirm:i}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:o=>{o.target===o.currentTarget&&r()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),s.jsx("input",{autoFocus:!0,value:e,onChange:o=>n(o.target.value),onKeyDown:o=>{o.key==="Enter"?i():o.key==="Escape"&&r()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function YO({name:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",e,"? This cannot be undone."]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function JO(){const[e,n]=L.useState(!1),r=Oh();return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>n(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),e&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>n(!1)}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[s.jsx(Th,{label:"Text size",children:s.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[s.jsx("button",{onClick:()=>r.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),s.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:r.fontSize}),s.jsx("button",{onClick:()=>r.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),s.jsx(Th,{label:"Word wrap",children:s.jsx(Tx,{on:r.wordWrap,onClick:r.toggleWordWrap})}),s.jsx(Th,{label:"Minimap",children:s.jsx(Tx,{on:r.minimap,onClick:r.toggleMinimap})}),s.jsx(Th,{label:"Theme",children:s.jsx("button",{onClick:()=>r.setTheme(r.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:r.theme==="dark"?"Dark":"Paper"})}),s.jsx(Th,{label:"Autosave",children:s.jsx(Tx,{on:r.autosave,onClick:r.toggleAutosave})}),s.jsx(Th,{label:"Wide measure",children:s.jsx(Tx,{on:r.wideMeasure,onClick:r.toggleWideMeasure})})]})]})]})}function Th({label:e,children:n}){return s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:e}),n]})}function Tx({on:e,onClick:n}){return s.jsx("button",{onClick:n,className:`px-2 py-0.5 text-[10px] rounded border border-line ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:e?"On":"Off"})}const QO=L.lazy(()=>Jm(()=>import("./TiptapBody-R9igz9Iz.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.TiptapBody})));function $x(e){return e.split("/").filter(Boolean).pop()||e}function Ax(e,n){if(!n.length)return e;const r=new Set(n),i={};for(const[o,l]of Object.entries(e))r.has(o)||(i[o]=l);return i}function Rx(e){return aC(e)||lC(e)}function yw(){const e=Tn(Ye=>Ye.openFiles),n=Tn(Ye=>Ye.activeFilePath),r=Tn(Ye=>Ye.dirty),i=Tn(Ye=>Ye.viewMode),o=Tn(Ye=>Ye.buffers),l=Tn(Ye=>Ye.setActive),d=Tn(Ye=>Ye.closeFile),u=Tn(Ye=>Ye.closeOthers),h=Tn(Ye=>Ye.closeToTheRight),m=Tn(Ye=>Ye.closeAll),x=Tn(Ye=>Ye.loadBuffer),g=Tn(Ye=>Ye.setBuffer),v=Tn(Ye=>Ye.markSaved),S=Tn(Ye=>Ye.setViewMode),E=Oh(),[j,y]=L.useState({}),[b,_]=L.useState({}),[C,N]=L.useState(null),[$,R]=L.useState(null),[O,I]=L.useState(!1),[z,U]=L.useState(!1),[W,Y]=L.useState(!0),V=L.useRef(null),H=L.useRef(null),te=L.useRef(void 0),ae=L.useRef(null),oe=L.useRef(null),ie=UO(n??"",o[n??""]??""),X=L.useCallback(Ye=>{V.current=Ye},[]),Q=L.useCallback(()=>V.current,[]);L.useEffect(()=>{const Ye=n;if(!Ye||Rx(Ye))return;if(Tn.getState().hasBuffer(Ye)){y(kt=>kt[Ye]==="ready"?kt:{...kt,[Ye]:"ready"});return}let yt=!1;return y(kt=>({...kt,[Ye]:"loading"})),window.api.files.read(Ye).then(kt=>{yt||(kt.binary?y(Kt=>({...Kt,[Ye]:{binary:!0,size:kt.size??0,mime:kt.mime??"application/octet-stream",reason:kt.error??"Binary file"}})):kt.ok?(x(Ye,kt.text),y(Kt=>({...Kt,[Ye]:"ready"}))):y(Kt=>({...Kt,[Ye]:{error:kt.error??"failed to read"}})))}),()=>{yt=!0}},[n,x]),L.useEffect(()=>{R(null)},[n]);const J=L.useCallback(async(Ye,yt=!1)=>{const kt=Tn.getState().buffers[Ye];if(kt==null)return;yt&&I(!0);const Kt=await window.api.files.write(Ye,kt);Kt.ok?(v(Ye),_(On=>({...On,[Ye]:(On[Ye]??0)+1})),yt||Le.info(`Saved ${$x(Ye)}`)):Le.error(Kt.error??`Couldn't save ${$x(Ye)}`),yt&&I(!1)},[v]);L.useEffect(()=>{if(!E.autosave)return;const Ye=n;if(!(!Ye||Rx(Ye)||!r[Ye]))return window.clearTimeout(te.current),te.current=window.setTimeout(()=>{J(Ye,!0)},1200),()=>window.clearTimeout(te.current)},[E.autosave,n,r,o,J]);const le=L.useCallback(Ye=>{Ye.length&&(y(yt=>Ax(yt,Ye)),_(yt=>Ax(yt,Ye)))},[]),ce=L.useCallback((Ye,yt)=>{y(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt),_(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt)},[]),pe=L.useCallback(Ye=>{r[Ye]?N({kind:"one",path:Ye}):(d(Ye),le([Ye]))},[r,d,le]),Ae=L.useCallback(Ye=>{e.some(kt=>kt.path!==Ye&&r[kt.path])?N({kind:"others",path:Ye}):(u(Ye),le(e.filter(kt=>kt.path!==Ye).map(kt=>kt.path)))},[e,r,u,le]),Se=L.useCallback(Ye=>{const yt=e.findIndex(Kt=>Kt.path===Ye);yt!==-1&&e.slice(yt+1).some(Kt=>r[Kt.path])?N({kind:"right",path:Ye}):(h(Ye),le(yt!==-1?e.slice(yt+1).map(Kt=>Kt.path):[]))},[e,r,h,le]);L.useEffect(()=>{const Ye=yt=>{if((yt.metaKey||yt.ctrlKey)&&(yt.key==="s"||yt.key==="S")){const kt=Tn.getState().activeFilePath;kt&&!Rx(kt)&&(yt.preventDefault(),J(kt))}else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="f"||yt.key==="F"))yt.preventDefault(),U(kt=>!kt);else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="w"||yt.key==="W")){const kt=Tn.getState().activeFilePath;kt&&Tn.getState().openFiles.length>1&&(yt.preventDefault(),Ae(kt))}else yt.key==="Escape"&&ie.state.phase!=="idle"?ie.cancel():yt.key==="Escape"&&z&&U(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[J,z,Ae,ie.state.phase,ie.cancel]),L.useEffect(()=>{if(ie.state.phase==="idle")return;const Ye=yt=>{var Kt,On;const kt=yt.target;(Kt=oe.current)!=null&&Kt.contains(kt)||(On=ae.current)!=null&&On.contains(kt)||ie.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[ie.state.phase,ie.cancel]),L.useEffect(()=>{ie.cancel()},[n,ie.cancel]);const ye=L.useCallback(()=>{e.some(yt=>r[yt.path])?N({kind:"all",path:""}):(m(),y({}),_({}))},[e,r,m]),ne=()=>{if(C){if(C.kind==="one")d(C.path),le([C.path]);else if(C.kind==="others"){const Ye=e.filter(yt=>yt.path!==C.path).map(yt=>yt.path);u(C.path),le(Ye)}else if(C.kind==="right"){const Ye=e.findIndex(kt=>kt.path===C.path),yt=Ye!==-1?e.slice(Ye+1).map(kt=>kt.path):[];h(C.path),le(yt)}else m(),y({}),_({});N(null)}};if(e.length===0)return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"mb-2",children:"no file open"}),s.jsxs("div",{children:["open the ",s.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const we=n,Ne=we?$x(we):"",Je=we?j[we]:void 0,lt=we?dC(we):!1,xt=we?E$(we):!1,Rt=we&<?i[we]??N$(we):"edit",He=!!we&&!Rx(we)&&Je==="ready",bt=He,st=xt?["edit","wysiwyg","preview","split"]:lt?["edit","preview"]:[],an=we&&s.jsx(pO,{path:we,name:Ne,value:o[we]??"",onChange:Ye=>g(we,Ye),onSave:()=>void J(we),onReady:X,onCursor:R}),sn=O?"Saving…":we&&r[we]?E.autosave?"Editing…":"Unsaved":"All changes saved";return s.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!z&&s.jsx(uO,{openFiles:e,activeFilePath:n,dirty:r,onSelectFile:l,onCloseFile:pe,onCloseOthers:Ae,onCloseToTheRight:Se,onCloseAll:ye}),we&&!z&&s.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[s.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ne}),s.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:we}),He&&s.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",sn]}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:()=>Y(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${W?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),st.length>0&&s.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:st.map(Ye=>s.jsx("button",{onClick:()=>S(we,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${Rt===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),s.jsx("div",{className:"flex-1"}),s.jsx(KO,{path:we,onRenamed:ce,onDeleted:Ye=>le([Ye])}),He&&s.jsx(JO,{}),s.jsx("button",{onClick:()=>U(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),z&&s.jsx("button",{onClick:()=>U(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),s.jsx("div",{className:"flex-1 min-h-0",children:we?aC(we)?s.jsx(CO,{path:we,name:Ne}):lC(we)?s.jsx(jO,{path:we}):Je&&typeof Je=="object"&&"binary"in Je?s.jsx(MO,{path:we,name:Ne,size:Je.size,mime:Je.mime,reason:Je.reason}):Je&&typeof Je=="object"&&"error"in Je?s.jsx("div",{className:"p-6 text-xs text-red-400",children:Je.error}):Je!=="ready"?s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):Rt==="wysiwyg"&&cl(we)?s.jsx(L.Suspense,{fallback:s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:s.jsx(QO,{value:o[we]??"",onChange:Ye=>g(we,Ye)},we)}):Rt==="split"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(_k,{text:o[we]??"",scrollRef:H}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[s.jsx(wk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(bk,{ref:H,text:o[we]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(jk,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(_k,{text:o[we]??"",scrollRef:H}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(bk,{ref:H,text:o[we]??"",wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(jk,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&oC(we)?s.jsx(kO,{path:we,dirty:!!r[we],reloadToken:b[we]??0}):Rt==="preview"&&cC(we)?s.jsx(NO,{path:we,text:o[we]??""}):Rt==="preview"&&uC(we)?s.jsx(AO,{path:we,text:o[we]??""}):cl(we)?s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(wk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}):an:null}),bt&&s.jsx(_O,{text:o[we]??"",cursor:$,language:zi(we)||void 0}),we&&cl(we)&&(Rt==="preview"||Rt==="split")&&ie.state.phase!=="idle"&&ie.state.selection&&s.jsx("div",{ref:oe,children:s.jsx(VO,{phase:ie.state.phase,rect:ie.state.selection.rect,diff:ie.state.diff,transcript:ie.state.transcript,modelStatus:ie.state.modelStatus,onQuickAction:ie.run,onRunCustom:ie.run,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onReject:ie.cancel,onRetry:ie.retry,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)}})}),C&&s.jsx(ZO,{message:C.kind==="one"?`Discard unsaved changes to ${$x(C.path)}?`:C.kind==="others"?"Discard unsaved changes in the other open files?":C.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:ne})]})}function ZO({message:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:e}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Tk={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},e5={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function ab(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":String(e)}function t5({open:e,onClose:n,variant:r="overlay"}){const i=vt($=>$.tabs.find(R=>R.id===$.activeTabId)??null),o=(i==null?void 0:i.cwd)??null,[l,d]=L.useState(null),[u,h]=L.useState(!1),[m,x]=L.useState(null),g=L.useRef(null),v=L.useCallback(async $=>{h(!0),x(null);try{const R=await window.api.repo.analyze($);R.ok?d(R):(x(R.error||"Analysis failed"),d(null))}catch(R){x(R instanceof Error?R.message:String(R)),d(null)}finally{h(!1)}},[]);L.useEffect(()=>{if(e){if(!o){x("No active session — open a tab in a folder first.");return}v(o)}},[e,o,v]),L.useEffect(()=>{var R;if(!e)return;const $=O=>{O.key==="Escape"&&(O.stopPropagation(),n())};return window.addEventListener("keydown",$),(R=g.current)==null||R.focus(),()=>window.removeEventListener("keydown",$)},[e,n]);const S=L.useCallback(()=>{o&&v(o)},[o,v]),E=L.useMemo(()=>l?Object.entries(l.languageBreakdown).map(([R,O])=>[R,O.files,O.lines]).sort((R,O)=>O[1]-R[1]).slice(0,12):[],[l]),j=L.useMemo(()=>E.length===0?1:E[0][1],[E]),y=L.useMemo(()=>{if(!l)return[];const $=l.topDirectories;if($.length===0)return[];const R=$.map(I=>Math.sqrt(Math.max(1,I.fileCount))),O=R.reduce((I,z)=>I+z,0)||1;return $.map((I,z)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:R[z]/O*100}))},[l]);if(!e)return null;const b=$=>{$.target===$.currentTarget&&n()},_=o?o.split("/").filter(Boolean).pop()||o:"no folder",C=r==="page",N=s.jsx("div",{className:C?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:C?void 0:b,"data-testid":"repoviz-backdrop",children:s.jsxs("div",{ref:g,role:C?void 0:"dialog","aria-modal":C?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:C?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[s.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),s.jsxs("div",{className:"text-xs text-fg-dim truncate",title:o??"",children:[_,(l==null?void 0:l.gitStatus.branch)&&s.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",l.gitStatus.branch,")"]}),(l==null?void 0:l.truncated)&&s.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[l&&l.gitStatus.uncommitted>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${l.gitStatus.uncommitted} uncommitted files`,children:[l.gitStatus.uncommitted," uncommitted"]}),s.jsxs("button",{type:"button",onClick:S,disabled:u||!o,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[u?"…":"↻"," Refresh"]}),s.jsx("button",{type:"button",onClick:n,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:u&&!l?s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[s.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),s.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),s.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):m?s.jsxs("div",{className:"py-16 text-center",children:[s.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),s.jsx("div",{className:"text-sm text-red-400",children:m})]}):l?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsx(lb,{label:"Files",value:ab(l.totalFiles)}),s.jsx(lb,{label:"Lines of code",value:ab(l.totalLines)}),s.jsx(lb,{label:"Uncommitted",value:String(l.gitStatus.uncommitted),tone:l.gitStatus.uncommitted>0?"warn":"neutral"})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),E.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):s.jsx("div",{className:"space-y-1.5",children:E.map(([$,R,O])=>{const I=Tk[$]??Tk.other,z=e5[$]??$,U=R/j*100;return s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"w-24 text-fg-dim truncate",title:z,children:z}),s.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:s.jsx("div",{className:"h-full rounded",style:{width:`${U}%`,backgroundColor:I}})}),s.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[R," files"]}),s.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[ab(O)," L"]})]},$)})})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),y.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):s.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:y.map($=>s.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max($.basis,6)}%`,flexGrow:$.basis>15?1:0},title:`${$.path} — ${$.fileCount} files, ${$.totalLines.toLocaleString()} lines`,children:[s.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:$.path}),s.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[$.fileCount," files"]})]},$.path))})]}),s.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",l.durationMs,"ms",l.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):s.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!C&&typeof document<"u"&&document.body?Hu.createPortal(N,document.body):N}function lb({label:e,value:n,tone:r="neutral"}){const i=r==="warn"?"text-amber-400":"text-fg";return s.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[s.jsx("div",{className:`text-xl font-medium ${i}`,children:n}),s.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:e})]})}function qu({options:e,active:n,onChange:r}){return s.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:e.map(({key:i,label:o})=>s.jsx("button",{onClick:()=>r(i),className:`px-2 py-0.5 text-xs ${n===i?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:o},i))})}const $k=e=>/[/\\\-_.\s]/.test(e),Ak=e=>e>="A"&&e<="Z";function n5(e,n,r){if(!e)return{match:!0,score:0,matched:[]};const i=e.toLowerCase(),o=n.toLowerCase(),l=(r||n).toLowerCase(),d=n.split("/").pop()||n,u=d.toLowerCase();if(u===i)return{match:!0,score:1e3,matched:Array.from({length:d.length},(b,_)=>_)};if(u.startsWith(i))return{match:!0,score:900,matched:Array.from({length:e.length},(b,_)=>_)};let h=0;for(const b of l.split("/")){if(b===i)return{match:!0,score:800,matched:[]};b.startsWith(i)&&(h=Math.max(h,700))}const m=u.indexOf(i);if(m!==-1)return{match:!0,score:m===0||$k(u[m-1])||Ak(d[m])?650:600,matched:Array.from({length:e.length},(_,C)=>m+C)};if(l.includes(i))return{match:!0,score:Math.max(500,h),matched:[]};let x=0,g=0,v=0,S=-1,E=0;const j=[];for(let b=0;b<o.length&&x<i.length;b++)o[b]===i[x]&&(j.push(b),g+=10,S===b-1?(v++,g+=v*8):v=0,(b===0||$k(o[b-1])||Ak(n[b]))&&(E++,g+=15,b===0&&(g+=10)),S=b,x++);if(x!==i.length)return{match:!1,score:0,matched:[]};const y=Math.max(0,50-(o.length-i.length));if(g+=y,E>=i.length*.5&&(g+=30),j.length>1){const b=j[j.length-1]-j[0];b>i.length*3&&(g-=Math.min(50,(b-i.length*3)*2))}return{match:!0,score:Math.max(1,g),matched:j}}function cb(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function Rk(e){const n=e.lastIndexOf("/");return n<0?"":e.slice(0,n)}const Mk="session-manager.quickopen.recent",r5=8;function s5({open:e,onClose:n,variant:r="overlay"}){const i=vt(z=>z.tabs.find(U=>U.id===z.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState([]),[m,x]=L.useState(!1),[g,v]=L.useState(0),[S,E]=L.useState([]),j=L.useRef(null),y=L.useRef(null);L.useEffect(()=>{if(e)try{const z=localStorage.getItem(Mk);z&&E(JSON.parse(z))}catch{}},[e]),L.useEffect(()=>{if(!e){d(""),v(0);return}const z=setTimeout(()=>{var U;return(U=j.current)==null?void 0:U.focus()},0);return()=>clearTimeout(z)},[e]),L.useEffect(()=>{if(!e||!o)return;let z=!1;return x(!0),window.api.search.files(o,"",{limit:5e3}).then(U=>{if(!z){if(!U.ok){Le.error(`File search failed: ${U.error??"unknown error"}`),h([]);return}h(U.files)}}).catch(U=>{const W=U instanceof Error?U.message:String(U);dt.error("quick-open","search.files threw",{error:W}),Le.error(`File search failed: ${W}`),h([])}).finally(()=>{z||x(!1)}),()=>{z=!0}},[e,o]);const b=L.useMemo(()=>{if(!l.trim())return[...u].sort((Y,V)=>Y.name.localeCompare(V.name)).slice(0,100).map(Y=>({file:Y,score:0,matched:[]}));const z=l.trim(),U=[];for(const W of u){const Y=n5(z,W.name,W.path);Y.match&&U.push({file:W,score:Y.score,matched:Y.matched})}return U.sort((W,Y)=>Y.score-W.score),U.slice(0,100)},[u,l]),_=L.useMemo(()=>l.trim()?[]:S.map(z=>u.find(U=>U.path===z)||null).filter(z=>z!==null).slice(0,5),[S,u,l]);L.useEffect(()=>{const z=_.length+b.length;g>=z&&v(Math.max(0,z-1))},[_.length,b.length,g]),L.useEffect(()=>{if(!y.current)return;const z=y.current.querySelector(`[data-row="${g}"]`);z&&z.scrollIntoView({block:"nearest"})},[g]);const C=L.useCallback(z=>{try{const V=[z,...S.filter(H=>H!==z)].slice(0,r5);E(V),localStorage.setItem(Mk,JSON.stringify(V))}catch{}const U=i==null?void 0:i.id;if(!U){Le.error("No active tab to receive file path");return}const Y=(o?cb(z,o):z)||z;try{window.api.pty.write({tabId:U,data:Y})}catch(V){const H=V instanceof Error?V.message:String(V);dt.error("quick-open","pty.write failed",{error:H}),Le.error(`Failed to write to terminal: ${H}`);return}n()},[i==null?void 0:i.id,o,S,n]),N=L.useCallback(z=>{const U=_.length+b.length;if(z.key==="Escape"){z.preventDefault(),n();return}if(z.key==="ArrowDown"){if(z.preventDefault(),U===0)return;v(W=>Math.min(U-1,W+1));return}if(z.key==="ArrowUp"){if(z.preventDefault(),U===0)return;v(W=>Math.max(0,W-1));return}if(z.key==="Enter"){if(z.preventDefault(),g<_.length){const V=_[g];V&&C(V.path);return}const W=g-_.length,Y=b[W];Y&&C(Y.file.path)}},[g,b,_,C,n]);if(!e)return null;const $=(z,U)=>{if(U.length===0)return z;const W=new Set(U);return z.split("").map((Y,V)=>s.jsx("span",{className:W.has(V)?"text-accent font-semibold":"",children:Y},V))};let R=-1;const O=r==="page",I=s.jsx("div",{className:O?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:O?void 0:z=>{z.target===z.currentTarget&&n()},"data-testid":"quick-open-backdrop",children:s.jsxs("div",{role:O?void 0:"dialog","aria-modal":O?void 0:"true","aria-label":"Quick Open",className:O?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:N,children:[s.jsx("div",{className:"border-b border-line p-2",children:s.jsx("input",{ref:j,type:"text",value:l,onChange:z=>{d(z.target.value),v(0)},placeholder:o?"Search files in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),s.jsx("div",{ref:y,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:m?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):o?_.length===0&&b.length===0?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:l?"No files match.":"No files found in this project."}):s.jsxs(s.Fragment,{children:[_.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),_.map(z=>{R++;const U=R,W=U===g;return s.jsxs("button",{"data-row":U,role:"option","aria-selected":W,onClick:()=>C(z.path),onMouseEnter:()=>v(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${W?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:z.name}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Rk(z.path),o)})]},`r:${z.path}`)})]}),b.length>0&&s.jsxs("div",{children:[_.length>0&&s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),b.map(({file:z,matched:U})=>{R++;const W=R,Y=W===g;return s.jsxs("button",{"data-row":W,role:"option","aria-selected":Y,onClick:()=>C(z.path),onMouseEnter:()=>v(W),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Y?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:$(z.name,U)}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Rk(z.path),o)})]},z.path)})]})]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[b.length+_.length," ",b.length+_.length===1?"file":"files"]})]})]})});return!O&&typeof document<"u"&&document.body?Hu.createPortal(I,document.body):I}function Ik(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function i5(e,n,r){if(!n)return e;const i=r?e:e.toLowerCase(),o=r?n:n.toLowerCase(),l=i.indexOf(o);return l<0?e:s.jsxs(s.Fragment,{children:[e.slice(0,l),s.jsx("span",{className:"text-accent font-semibold",children:e.slice(l,l+n.length)}),e.slice(l+n.length)]})}function o5({open:e,onClose:n,variant:r="overlay"}){const i=vt(V=>V.tabs.find(H=>H.id===V.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState(!1),[m,x]=L.useState([]),[g,v]=L.useState(!1),[S,E]=L.useState(null),[j,y]=L.useState(0),[b,_]=L.useState(null),C=L.useRef(null),N=L.useRef(null),$=L.useRef(0);L.useEffect(()=>{if(!e){d(""),x([]),E(null),y(0);return}const V=setTimeout(()=>{var H;return(H=C.current)==null?void 0:H.focus()},0);return()=>clearTimeout(V)},[e]),L.useEffect(()=>{if(!e||!o)return;const V=l.trim();if(!V){x([]),E(null),v(!1);return}const H=++$.current;v(!0);const te=setTimeout(()=>{window.api.search.text(o,V,{caseSensitive:u,limit:500}).then(ae=>{H===$.current&&(ae.ok?(x(ae.matches),E(null)):(E(ae.error??"unknown error"),x([])),_(ae.usedRipgrep))}).catch(ae=>{if(H!==$.current)return;const oe=ae instanceof Error?ae.message:String(ae);dt.error("global-search","search.text threw",{error:oe}),E(oe),x([])}).finally(()=>{H===$.current&&v(!1)})},250);return()=>clearTimeout(te)},[e,o,l,u]);const R=L.useMemo(()=>{const V=new Map;for(const te of m){const ae=V.get(te.path);ae?ae.push(te):V.set(te.path,[te])}const H=[];for(const[te,ae]of V)H.push({path:te,matches:ae});return H.sort((te,ae)=>ae.matches.length-te.matches.length||te.path.localeCompare(ae.path)),H},[m]),O=L.useMemo(()=>m,[m]);L.useEffect(()=>{j>=O.length&&y(Math.max(0,O.length-1))},[O.length,j]),L.useEffect(()=>{if(!N.current)return;const V=N.current.querySelector(`[data-match="${j}"]`);V&&V.scrollIntoView({block:"nearest"})},[j]);const I=L.useCallback(V=>{const H=i==null?void 0:i.id;if(!H){Le.error("No active tab to receive path");return}const ae=`${(o?Ik(V.path,o):V.path)||V.path}:${V.line}`;try{window.api.pty.write({tabId:H,data:ae})}catch(oe){const ie=oe instanceof Error?oe.message:String(oe);dt.error("global-search","pty.write failed",{error:ie}),Le.error(`Failed to write to terminal: ${ie}`);return}n()},[i==null?void 0:i.id,o,n]),z=L.useCallback(V=>{if(V.key==="Escape"){V.preventDefault(),n();return}if(V.key==="ArrowDown"){if(V.preventDefault(),O.length===0)return;y(H=>Math.min(O.length-1,H+1));return}if(V.key==="ArrowUp"){if(V.preventDefault(),O.length===0)return;y(H=>Math.max(0,H-1));return}if(V.key==="Enter"){V.preventDefault();const H=O[j];H&&I(H)}},[O,j,I,n]);if(!e)return null;const U=r==="page";let W=-1;const Y=s.jsx("div",{className:U?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:U?void 0:V=>{V.target===V.currentTarget&&n()},"data-testid":"global-search-backdrop",children:s.jsxs("div",{role:U?void 0:"dialog","aria-modal":U?void 0:"true","aria-label":"Search in project",className:U?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:z,children:[s.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[s.jsx("input",{ref:C,type:"text",value:l,onChange:V=>{d(V.target.value),y(0)},placeholder:o?"Search in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),s.jsx("button",{type:"button",onClick:()=>h(V=>!V),className:`px-2 py-1 text-xs rounded border ${u?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":u,children:"Aa"})]}),s.jsx("div",{ref:N,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:o?l.trim()?g?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):S?s.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:S}):O.length===0?s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(l),"."]}):s.jsx("div",{children:R.map(V=>s.jsxs("div",{children:[s.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[Ik(V.path,o)," ",s.jsxs("span",{className:"text-fg-faint",children:["(",V.matches.length,")"]})]}),V.matches.map(H=>{W++;const te=W,ae=te===j;return s.jsxs("button",{"data-match":te,role:"option","aria-selected":ae,onClick:()=>I(H),onMouseEnter:()=>y(te),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ae?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:H.line}),s.jsx("span",{className:"truncate",children:i5(H.text,l,u)})]},`${H.path}:${H.line}:${H.column}:${te}`)})]},V.path))}):s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",s.jsx("span",{className:"font-mono",children:o}),"."]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[O.length," ",O.length===1?"match":"matches",b===!1&&" · fs walk (rg missing)"]})]})]})});return!U&&typeof document<"u"&&document.body?Hu.createPortal(Y,document.body):Y}const a5=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function l5({open:e,onClose:n,variant:r="page",initialMode:i="files"}){const[o,l]=L.useState(i);return L.useEffect(()=>{l(i)},[i]),e?s.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[s.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[s.jsx(qu,{options:a5,active:o,onChange:l}),s.jsx("span",{className:"text-[11px] text-fg-faint",children:o==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),s.jsx("div",{className:"flex-1 min-h-0",children:o==="files"?s.jsx(s5,{open:!0,onClose:n,variant:"page"}):s.jsx(o5,{open:!0,onClose:n,variant:"page"})})]}):null}class _j extends L.Component{constructor(){super(...arguments);Fn(this,"state",{error:null});Fn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,i){console.error("[ErrorBoundary]",r,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):s.jsxs("div",{className:"p-6 text-xs",children:[s.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),s.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),s.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function c5({open:e,onClose:n,title:r,children:i,variant:o="overlay"}){return s.jsxs(Wu,{open:e,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:o,children:[o==="overlay"&&s.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[s.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:r}),s.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(_j,{children:i})})]})}function u5(e){return/^monitor of /i.test(e.trim())}function Pk(e){return e.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Dk(e,n,r){if(e){const d=r.find(u=>u.deviceId===e);if(d)return d}if(!n)return null;const i=r.filter(d=>d.label===n);if(i.length===1)return i[0];if(i.length>1)return null;const o=Pk(n),l=r.filter(d=>d.label&&Pk(d.label)===o);return l.length===1?l[0]:null}async function Ok(e){var r;return(r=navigator.mediaDevices)!=null&&r.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(i=>!(i.kind!=="audioinput"||i.label&&u5(i.label))):[]}const Lk=!1;function kj(){const e=$t(m=>m.isRecording);$t(m=>m.startRecording),$t(m=>m.stopRecording);const[n,r]=L.useState([]),[i,o]=L.useState(null),[l,d]=L.useState(null);L.useEffect(()=>{let m=!1;return(async()=>{try{const x=await window.api.voice.getDevicePref();if(m)return;const g=await Ok(Lk);if(m)return;r(g),d(x.selectedLabel);const v=Dk(x.selectedDeviceId,x.selectedLabel,g);v?(o(v.deviceId),x.selectedDeviceId&&v.deviceId!==x.selectedDeviceId&&(dt.info("voice","device-picker rebind-by-label",{fromIdPrefix:x.selectedDeviceId.slice(0,8),toIdPrefix:v.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||x.selectedLabel}).catch(()=>{}))):((x.selectedDeviceId||x.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:x.selectedLabel,hadId:!!x.selectedDeviceId}),dt.warn("voice","device-picker selected-unavailable",{hadId:!!x.selectedDeviceId})),o(null))}catch(x){dt.warn("voice","device-picker init failed",{error:x instanceof Error?x.message:String(x)})}})(),()=>{m=!0}},[]);const u=L.useCallback(async()=>{try{const m=await Ok(Lk);if(r(m),i&&!m.some(x=>x.deviceId===i)){const x=Dk(null,l,m);x?(o(x.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:x.deviceId,selectedLabel:x.label||l}).catch(()=>{})):o(null)}}catch(m){dt.warn("voice","device-picker refresh failed",{error:m instanceof Error?m.message:String(m)})}},[i,l]);L.useEffect(()=>{const m=()=>{u()};return window.addEventListener("mic-device-change",m),()=>window.removeEventListener("mic-device-change",m)},[u]);const h=async m=>{var S;const x=m.target.value,g=x===""?null:x,v=g?((S=n.find(E=>E.deviceId===g))==null?void 0:S.label)??null:null;o(g),d(v);try{await window.api.voice.setDevicePref({selectedDeviceId:g,selectedLabel:v}),dt.info("voice","device-picker selected",{deviceIdPrefix:g?g.slice(0,8):null})}catch(E){dt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(e)try{await $t.getState().restartWithDevice()}catch(E){dt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};return s.jsxs("select",{value:i??"",onChange:h,onFocus:()=>{u()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[s.jsx("option",{value:"",children:"Default"}),n.map(m=>s.jsx("option",{value:m.deviceId,children:m.label||`Mic ${m.deviceId.slice(0,6)}`},m.deviceId))]})}function d5(){const e=$t(S=>S.isRecording),n=$t(S=>S.levelMeterEnabled),[r,i]=L.useState(0),[o,l]=L.useState(0),d=L.useRef(0);d.current=o;const[u,h]=L.useState(0),[m,x]=L.useState(!1),g=L.useRef(null);if(L.useEffect(()=>{if(!e||!n){i(0),l(0);return}let S=0,E=!1,j=null,y=null;const b=()=>{if(E)return;const C=y??Y2();if(!C){S=requestAnimationFrame(b);return}y!==C&&(y=C,j=new Uint8Array(new ArrayBuffer(C.fftSize)));const N=j;C.getByteTimeDomainData(N);let $=0;for(let z=0;z<N.length;z++){const U=N[z]-128;$+=U*U}const R=Math.sqrt($/N.length)/128,O=R>0?20*Math.log10(R):-60,I=Math.max(0,Math.min(1,(O+60)/60));l(R),i(I),R>=.95&&(x(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(!1),150)),S=requestAnimationFrame(b)};S=requestAnimationFrame(b);const _=setInterval(()=>{E||h(Math.round(d.current*100))},250);return()=>{E=!0,cancelAnimationFrame(S),clearInterval(_),g.current&&(clearTimeout(g.current),g.current=null)}},[e,n]),!e||!n)return null;const v=m?"bg-red-500":o>=.7?"bg-amber-400":"bg-green-500";return s.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":u,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${m?"ring-1 ring-red-500":""}`,children:s.jsx("div",{className:`h-full ${v} transition-[width] duration-75 ease-out`,style:{width:`${r*100}%`}})})}function h5({open:e,onClose:n,variant:r="overlay"}){return s.jsx(c5,{open:e,onClose:n,title:"Voice / Microphone",variant:r,children:s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsx(g5,{}),s.jsx(FC,{}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Q2,{}),s.jsx(kj,{}),s.jsx(e$,{})]}),s.jsx(f5,{}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[s.jsx("button",{type:"button",onClick:()=>$t.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),s.jsx(m5,{})]}),s.jsx(d5,{})]})})}function f5(){const e=$t(l=>l.isRecording),[n,r]=L.useState(null);if(L.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(u=>{l||r(u)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(u=>r(u));return()=>{l=!0,d()}},[]),e||!n)return null;const i=n.mode==="hold"?"Hold":"Press",o=p5(n.accelerator);return s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("span",{children:[i," "]}),s.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:o}),s.jsx("span",{children:" to record"})]})}function p5(e){const n=typeof navigator<"u"&&/Mac/.test(navigator.platform);return e.replace(/CommandOrControl/g,n?"⌘":"Ctrl").replace(/CmdOrCtrl/g,n?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,n?"⌥":"Alt").replace(/Shift/g,n?"⇧":"Shift")}function m5(){const[e,n]=L.useState(null);if(L.useEffect(()=>{let i=!1;window.api.voice.getHotkeyConfig().then(l=>{i||n(l)}).catch(l=>dt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const o=window.api.voice.onHotkeyConfigChanged(l=>{n(l)});return()=>{i=!0,o()}},[]),!e)return null;const r=async i=>{if(e.mode===i)return;const o={...e,mode:i};n(o);try{await window.api.voice.setHotkeyConfig(o)}catch(l){dt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return s.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="toggle",onChange:()=>r("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),s.jsx("span",{children:"Tap on/off"})]}),s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="hold",onChange:()=>r("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),s.jsx("span",{children:"Hold to talk"})]})]})}function g5(){const e=$t(l=>l.isRecording),n=$t(l=>l.lastTranscript),r=$t(l=>l.error),i=$t(l=>l.modelStatus),o=$t(l=>l.loadingProgress);return r?s.jsxs("div",{className:"text-[11px] text-red-400",title:r,children:["⚠ ",r]}):e?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[s.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),s.jsx("span",{className:"truncate",title:n,children:n||"Listening…"})]}):i==="loading"?s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("span",{children:"Loading speech model"}),s.jsxs("span",{className:"font-mono",children:[o,"%"]})]}),s.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:s.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${o}%`}})})]}):null}let ub=null;function x5(){return ub||(ub=Jm(()=>import("./monaco-editor-BW5C4Iv1.js").then(e=>e.b),__vite__mapDeps([1,2]),import.meta.url).then(e=>(f0.config({monaco:e}),e))),ub}function Sj({value:e,onChange:n,path:r,readOnly:i}){const o=L.useRef(null),l=d=>{o.current=d};return s.jsx(p0,{path:`file://${r}`,defaultLanguage:"json",value:e,onChange:d=>n(d??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:i,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let zk=!1;async function y5(e){if(zk)return;const n=await x5(),r=await Promise.all(e.map(async o=>{let l=o.schema;if(!l){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const u=new URL(o.uri).origin;if(!d.includes(u))throw new Error("untrusted origin");const h=await fetch(o.uri);h.ok&&(l=await h.json())}catch{}}return{uri:o.uri,fileMatch:o.fileMatch,schema:l}}));n.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:r.filter(o=>o.schema),enableSchemaRequest:!0}),zk=!0}function b0({node:e,targetScope:n,onOverride:r,schema:i,rootLabel:o}){const[l,d]=L.useState(""),[u,h]=L.useState(!0),m=[],x=e.kind==="object"&&Object.keys(e.children).length===0,v=((i==null?void 0:i.rootKeys())??[]).length>0;return s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",s.jsx("span",{className:"text-fg-dim",children:os[n].label})]}),v&&s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:S=>h(S.target.checked),className:"accent-accent"}),"show unset keys"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:l,onChange:S=>d(S.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),s.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:x&&!u?s.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):s.jsx(Cj,{node:e,path:m,label:o??"(root)",targetScope:n,onOverride:r,filter:l,depth:0,schema:i,showGhosts:u,defaultOpen:!0})})]})}function Cj(e){return e.node.kind==="object"?s.jsx(v5,{...e,node:e.node}):e.node.kind==="array"?s.jsx(b5,{...e,node:e.node}):s.jsx(w5,{...e,node:e.node})}function Bk(e,n){return n.trim()?e.toLowerCase().includes(n.toLowerCase()):!0}function Zh(e,n,r){return!!(!r.trim()||e.some(i=>Bk(i,r))||n!=null&&n.description&&Bk(n.description,r))}function v5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u,showGhosts:h,defaultOpen:m}){const[x,g]=L.useState(m??d<2),v=(u==null?void 0:u.at(n))??null,S=new Set(Object.keys(e.children)),E=h?(v==null?void 0:v.knownChildren)??[]:[],j=Array.from(new Set([...S,...E])).sort(),y=L.useMemo(()=>l.trim()?j.filter(_=>{const C=(u==null?void 0:u.at([...n,_]))??null;return Zh([...n,_],C,l)?!0:S.has(_)?jj(e.children[_],[...n,_],l,u):!1}):j,[j.join(","),l,e,n.join("."),u]);if(l.trim()&&y.length===0&&!Zh(n,v,l))return null;if(n.length===0)return s.jsx("div",{children:y.map(_=>b(_))});return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>g(!x),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:x?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" {",S.size,E.length>S.size?`/${new Set([...S,...E]).size}`:"","}"]}),(v==null?void 0:v.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:v.description,children:["— ",v.description]})]}),x&&y.map(_=>b(_))]});function b(_){if(S.has(_))return s.jsx(Cj,{node:e.children[_],path:[...n,_],label:_,targetScope:i,onOverride:o,filter:l,depth:d+1,schema:u,showGhosts:h},_);const C=(u==null?void 0:u.at([...n,_]))??null;return C?s.jsx(_5,{path:[...n,_],label:_,info:C,targetScope:i,onSet:o,depth:d+1,filter:l},_):null}}function jj(e,n,r,i){const o=(i==null?void 0:i.at(n))??null;if(Zh(n,o,r))return!0;if(e.kind!=="object")return!1;for(const l of Object.keys(e.children))if(jj(e.children[l],[...n,l],r,i))return!0;return!1}function b5({node:e,path:n,label:r,filter:i,depth:o,schema:l}){const[d,u]=L.useState(!0),h=(l==null?void 0:l.at(n))??null;return Zh(n,h,i)?s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:o*14},onClick:()=>u(!d),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" [",e.items.length,"]"]}),s.jsx(Hm,{tone:"warn",children:"accumulated"}),(h==null?void 0:h.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:h.description,children:["— ",h.description]})]}),d&&e.items.map((m,x)=>s.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(o+1)*14},children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),s.jsxs("span",{className:"text-fg-faint",children:[x,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:$y(m.value)}),s.jsx(vw,{scope:m.fromScope})]},x))]}):null}function w5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u}){const[h,m]=L.useState(!1),x=(u==null?void 0:u.at(n))??null;if(!Zh(n,x,l))return null;const g=e.winner!==i,v=e.shadowed.length>0;return s.jsxs("div",{children:[s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[s.jsx("span",{className:`w-3 shrink-0 ${v?"text-fg-faint cursor-pointer":""}`,onClick:()=>v&&m(!h),children:v?h?"▾":"▸":""}),s.jsxs("span",{className:"text-fg",children:[r,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-md",children:$y(e.value)}),s.jsx(vw,{scope:e.winner}),(x==null?void 0:x.deprecated)&&s.jsx(Hm,{tone:"warn",children:"deprecated"}),(x==null?void 0:x.default)!==void 0&&k5(e.value,x.default)&&s.jsx(Hm,{tone:"dim",children:"= default"}),e.typeMismatch&&s.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(x==null?void 0:x.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:x.description,children:["— ",x.description]}),s.jsx("div",{className:"flex-1"}),(x==null?void 0:x.enum)&&s.jsx(Ej,{values:x.enum}),s.jsx("button",{disabled:!g,onClick:()=>o(n,e.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${g?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:g?`copy into ${os[i].label} draft`:`already winning in ${os[i].label}`,children:"override"})]}),h&&e.shadowed.map((S,E)=>s.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[s.jsx("span",{children:"shadowed:"}),s.jsx("span",{className:"truncate max-w-xl",children:$y(S.value)}),s.jsx(vw,{scope:S.scope,dim:!0})]},E))]})}function _5({path:e,label:n,info:r,targetScope:i,onSet:o,depth:l,filter:d}){if(!Zh(e,r,d))return null;const u=r.default!==void 0?r.default:S5(r.type),h=Array.isArray(r.type)?r.type.join("|"):r.type??"?";return s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:l*14},children:[s.jsx("span",{className:"w-3 shrink-0"}),s.jsx("span",{className:"text-fg-dim",children:n}),s.jsx(Hm,{tone:"dim",children:h}),r.required&&s.jsx(Hm,{tone:"warn",children:"required"}),r.default!==void 0&&s.jsxs("span",{className:"text-fg-faint",children:["default: ",$y(r.default)]}),r.description&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:r.description,children:["— ",r.description]}),s.jsx("div",{className:"flex-1"}),r.enum&&s.jsx(Ej,{values:r.enum}),s.jsx("button",{onClick:()=>o(e,u),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${os[i].label} draft`,children:"set"})]})}function k5(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function S5(e){switch(Array.isArray(e)?e[0]:e){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function $y(e){if(typeof e=="string")return JSON.stringify(e);if(e===null)return"null";if(typeof e=="object"){const n=JSON.stringify(e);return n.length>100?n.slice(0,100)+"…":n}return String(e)}function vw({scope:e,dim:n}){const r=e==="user"?"bg-bg-hi text-fg-dim border-line":e==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r} ${n?"opacity-60":""}`,children:os[e].label})}function Hm({children:e,tone:n="default"}){const r={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[n];return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r}`,children:e})}function Ej({values:e}){const n=e.map(r=>String(r)).join(" | ");return s.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${n}`,children:["∈ ",n.length>30?n.slice(0,30)+"…":n]})}const C5=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],j5={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function Nj(e){return e.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((i,o)=>{const l=j5[i];return l||(o===0?i.charAt(0).toUpperCase()+i.slice(1):i)}).join(" ")}function Tj(e){const n=new Set,r=[];for(const o of C5){const l=o.keys.filter(d=>e.has(d));l.forEach(d=>n.add(d)),l.length!==0&&r.push({id:o.id,title:o.title,summary:o.summary,advanced:!!o.advanced,keys:l})}const i=Array.from(e).filter(o=>!n.has(o)&&o!=="$schema").sort();return i.length>0&&r.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:i}),r}function E5(e,n){return Tj(e).map(r=>({id:r.id,title:r.title,advanced:r.advanced,total:r.keys.length,setCount:r.keys.filter(i=>n.has(i)).length}))}const N5={};function $j(e,n){if(n)return{text:n,authored:!1};const r=N5[e];return r?{text:r,authored:!0}:null}const T5={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},$5=["user","project","local","default"],A5={user:"user",project:"project",local:"local",default:"default"};function R5({node:e,targetScope:n,onOverride:r,schema:i}){const[o,l]=L.useState(""),[d,u]=L.useState(!1),[h,m]=L.useState(!0),x=e.kind==="object"?e:null,g=x?Object.keys(x.children):[],v=i.rootKeys(),S=new Set([...g,...v]),E=L.useMemo(()=>Tj(S),[Array.from(S).sort().join(",")]),j=L.useMemo(()=>E5(S,new Set(g)),[Array.from(S).sort().join(","),g.join(",")]),[y,b]=L.useState(null),_=N=>{const $=E.find(R=>R.id===N);$!=null&&$.advanced&&!d&&u(!0),b(N)};L.useEffect(()=>{if(!y)return;const N=document.getElementById(`settings-group-${y}`);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),b(null))});const C=L.useMemo(()=>E.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter($=>{const R=(x==null?void 0:x.children[$])!==void 0;if(!h&&!R)return!1;if(!o.trim())return!0;const O=i.at([$]);return[$,Nj($),(O==null?void 0:O.description)??""].join(" ").toLowerCase().includes(o.toLowerCase())})})).filter(N=>N.keys.length>0),[E,o,d,h,x,i]);return s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[s.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",s.jsx("span",{className:"text-fg-dim font-medium",children:os[n].label})]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:N=>m(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:N=>u(N.target.checked),className:"accent-accent"}),"show advanced"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:o,onChange:N=>l(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),s.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[s.jsx(M5,{groups:j,onJump:_}),s.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[C.map(N=>s.jsx(I5,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map($=>{const R=x==null?void 0:x.children[$],O=i.at([$]);return s.jsx(P5,{keyName:$,node:R,info:O,targetScope:n,onOverride:(I,z)=>r([$],I,z)},$)})},N.id)),C.length===0&&s.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',o,'"']})]})]})]})}function M5({groups:e,onJump:n}){return s.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:e.map(r=>s.jsxs("button",{onClick:()=>n(r.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${r.title}`,children:[s.jsx(dn,{name:T5[r.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:r.title}),s.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[r.setCount,"/",r.total]})]},r.id))})}function I5({id:e,title:n,summary:r,advanced:i,children:o}){const[l,d]=L.useState(!0);return s.jsxs("section",{id:`settings-group-${e}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[s.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>d(!l),children:[s.jsx("span",{className:"text-fg-faint w-3",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h2",{className:"text-fg text-base font-semibold",children:n}),i&&s.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),s.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:r})]})]}),l&&s.jsx("div",{className:"divide-y divide-line/60",children:o})]})}function P5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const[l,d]=L.useState(!1),[u,h]=L.useState(!1),m=Nj(e),x=n!==void 0,v=(n==null?void 0:n.kind)==="leaf"?n:null,S=(n==null?void 0:n.kind)==="object"||(n==null?void 0:n.kind)==="array",E=r==null?void 0:r.default,j=v&&E!==void 0&&Rj(v.value,E),y=H5({isSet:x,leafNode:v,defaultVal:E,isDefault:!!j,node:n}),b=D5(v,E),_=b.length>=2,C=!!v&&!j,N=$j(e,r==null?void 0:r.description);return s.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("button",{onClick:()=>d(!l),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:l?"collapse":"expand",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[s.jsx("h3",{className:"text-fg text-sm",children:m}),s.jsx(W5,{kind:y.kind,label:y.label}),_&&s.jsxs("button",{onClick:$=>{$.stopPropagation(),l||d(!0),h(R=>!R)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",b.map($=>A5[$]).join(" · ")]}),C&&v&&s.jsx("button",{onClick:$=>{$.stopPropagation(),o(void 0,v.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${os[v.winner].label}`,children:"↺ reset"}),(r==null?void 0:r.deprecated)&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(r==null?void 0:r.required)&&!x&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),N&&s.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${N.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:N.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:q5(N.text)}),l&&u&&v&&s.jsx(O5,{leaf:v,defaultVal:E,onReset:$=>o(void 0,$)}),l&&s.jsx(L5,{keyName:e,node:n,info:r,targetScope:i,onOverride:$=>o($)})]}),s.jsx("div",{className:"shrink-0",children:!l&&s.jsx(U5,{node:n,info:r,onSet:$=>{o($)},disabled:S&&x})})]})})}function D5(e,n){if(!e)return[];const r=new Set;r.add(e.winner);for(const i of e.shadowed)r.add(i.scope);return n!==void 0&&r.add("default"),$5.filter(i=>r.has(i))}function O5({leaf:e,defaultVal:n,onReset:r}){const i={};i[e.winner]={value:e.value,winner:!0};for(const o of e.shadowed)i[o.scope]={value:o.value,winner:!1};return s.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[s.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),s.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(o=>{const l=i[o],d=l!==void 0;return s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:os[o].label}),s.jsx("span",{className:`font-mono truncate ${l!=null&&l.winner?"text-accent":"text-fg-dim"}`,children:d?Vh(l.value):s.jsx("span",{className:"text-fg-faint",children:"—"})}),d?s.jsx("button",{onClick:()=>r(o),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${os[o].label}`,children:"↺"}):s.jsx("span",{})]},o)}),s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:"Default"}),s.jsx("span",{className:"font-mono text-fg-dim truncate",children:n!==void 0?Vh(n):s.jsx("span",{className:"text-fg-faint",children:"—"})}),s.jsx("span",{})]})]})]})}function L5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const d=(n==null?void 0:n.kind)==="leaf"?n:null,u=$j(e,r==null?void 0:r.description);return s.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[u&&s.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${u.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:u.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:u.text}),s.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(r==null?void 0:r.type)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Type"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(r.type)?r.type.join(" | "):r.type})]}),(r==null?void 0:r.default)!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Default"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Vh(r.default)})]}),(r==null?void 0:r.enum)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Options"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:r.enum.map(h=>String(h)).join(" | ")})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Current"}),s.jsxs("dd",{className:"font-mono",children:[s.jsx("span",{className:"text-fg-dim",children:Vh(d.value)}),s.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",os[d.winner].label]})]})]}),d&&d.shadowed.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Shadowed"}),s.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((h,m)=>s.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Vh(h.value)," —"," ",s.jsx("span",{className:"no-underline",children:os[h.scope].label})]},m))})]}),(n==null?void 0:n.kind)==="array"&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Accumulated"}),s.jsxs("dd",{className:"text-fg-dim",children:[n.items.length," items across all scopes"]})]})]}),s.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:s.jsx(z5,{keyName:e,node:n,info:r,onChange:o,targetScope:i})})]})}function z5({node:e,info:n,onChange:r,targetScope:i}){const l=(e==null?void 0:e.kind)==="leaf"?e.value:n==null?void 0:n.default,d=Aj(n==null?void 0:n.type);if(d==="boolean"){const u=l===!0;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:h,label:m})=>s.jsx("button",{onClick:()=>r(h),className:`px-3 py-0.5 text-xs transition-colors ${u===h?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:m},m))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]})}return n!=null&&n.enum?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-fg-faint",children:"Choose:"}),n.enum.map(u=>{const h=Rj(l,u);return s.jsx("button",{onClick:()=>r(u),className:`px-2 py-0.5 text-xs rounded border ${h?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(u)},String(u))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]}):d==="integer"||d==="number"?s.jsx(B5,{value:typeof l=="number"?l:void 0,integer:d==="integer",onCommit:r,target:os[i].label}):d==="string"?s.jsx(F5,{value:typeof l=="string"?l:"",onCommit:r,target:os[i].label}):s.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",s.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function B5({value:e,integer:n,onCommit:r,target:i}){const[o,l]=L.useState(e!==void 0?String(e):""),d=()=>{const u=n?parseInt(o,10):parseFloat(o);Number.isNaN(u)||r(u)};return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("input",{type:"number",value:o,onChange:u=>l(u.target.value),onBlur:d,onKeyDown:u=>{u.key==="Enter"&&u.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:d,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",i]})]})}function F5({value:e,onCommit:n,target:r}){const[i,o]=L.useState(e);return s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[s.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),s.jsx("input",{type:"text",value:i,onChange:l=>o(l.target.value),onKeyDown:l=>{l.key==="Enter"&&n(i)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:()=>n(i),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function U5({node:e,info:n,onSet:r,disabled:i}){const o=(e==null?void 0:e.kind)==="leaf",l=Aj(n==null?void 0:n.type);if(i)return null;if(l==="boolean"){const d=o&&e.value===!0;return s.jsx("button",{onClick:()=>r(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:d?"on":"off"})}return null}function H5({isSet:e,leafNode:n,defaultVal:r,isDefault:i,node:o}){return e?(o==null?void 0:o.kind)==="array"?{kind:"accumulated",label:`${o.items.length} items`}:(o==null?void 0:o.kind)==="object"?{kind:"set",label:"configured"}:n?i?{kind:"default",label:`= default · ${os[n.winner].label}`}:n.shadowed.length>0?{kind:"override",label:`overriding ${n.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${os[n.winner].label}`}:{kind:"set",label:"configured"}:r!==void 0?{kind:"default",label:`using default: ${Vh(r)}`}:{kind:"unset",label:"not configured"}}function W5({kind:e,label:n}){const r={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[e];return s.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${r}`,children:n})}function Aj(e){if(e)return Array.isArray(e)?e.find(r=>r!=="null")??e[0]:e}function Rj(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function q5(e){const n=e.trim().split(`
|
|
3393
|
+
(Give a different rewrite than the last one.)`,!1)},[E,r.instruction]),_=L.useCallback(C=>{const N=r.diff;if(!N)return{ok:!1,reason:"not-found"};const $=IO(C,N.before,N.after);return $.ok?(o.current+=1,i({type:"ACCEPT"})):Le.error($.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),$},[r.diff]);return{state:r,select:m,cancel:x,listen:g,sendHeard:y,run:j,retry:b,accept:_}}const HO=[{label:"Make concise",instruction:"Rewrite this text to be concise and specific. Preserve meaning and any markdown structure."},{label:"To bullet list",instruction:"Convert this text into a tight markdown bullet list."},{label:"Fix the tone",instruction:"Fix the tone: direct, professional, no hedging. Preserve meaning."}],Ck=320,om=8;function WO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function qO(e){const n=typeof window<"u"?window.innerWidth:1024,r=Math.min(Math.max(e.left,om),Math.max(om,n-Ck-om)),i=Math.max(e.top-om,om);return{position:"fixed",left:r,top:i,width:Ck,transform:"translateY(-100%)",zIndex:50}}function VO({phase:e,rect:n,diff:r,transcript:i,modelStatus:o,onQuickAction:l,onRunCustom:d,onListen:u,onSendHeard:h,onCancel:m,onAccept:x,onReject:g,onRetry:v}){const[S,E]=L.useState(""),j=()=>{const y=S.trim();y&&(d(y),E(""))};return s.jsxs("div",{"data-doc-edit-popover":!0,style:qO(n),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[e==="popover"&&s.jsxs("div",{className:"p-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex flex-wrap gap-1",children:[s.jsx("button",{onClick:u,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),HO.map(y=>s.jsx("button",{onClick:()=>l(y.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:y.label},y.label))]}),s.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),s.jsx("input",{autoFocus:!0,value:S,onChange:y=>E(y.target.value),onKeyDown:y=>{y.key==="Enter"?j():y.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),e==="listening"&&s.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[s.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(WO,{}),"Listening…"]}),o&&s.jsx("span",{className:"text-[10px] text-fg-faint",children:o})]}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[s.jsxs("p",{className:"italic text-fg mb-2",children:["«",i,"»"]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsxs("div",{className:"p-3 flex items-center justify-between",children:[s.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="diff"&&r&&s.jsxs("div",{className:"p-3",children:[s.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function GO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function jk({phase:e,transcript:n,diff:r,editCount:i,modelStatus:o,onListen:l,onSendHeard:d,onCancel:u,onAccept:h,onReject:m,onRetry:x}){return s.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[s.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),s.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Zm(FO)})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[e==="idle"&&s.jsxs("div",{className:"text-fg-faint",children:[s.jsx("p",{children:"Select text in the doc…"}),s.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),e==="popover"&&s.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),e==="listening"&&s.jsxs("div",{children:[s.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[s.jsx(GO,{}),"Listening…"]}),o&&s.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:o}),s.jsx("button",{onClick:u,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{children:[s.jsxs("p",{className:"italic text-fg mb-3",children:["«",n,"»"]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),e==="diff"&&r&&s.jsxs("div",{children:[s.jsxs("div",{className:"mb-3 space-y-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function Ek(e){return e.split("/").filter(Boolean).pop()||e}function KO({path:e,onRenamed:n,onDeleted:r}){const[i,o]=L.useState(!1),[l,d]=L.useState(!1),[u,h]=L.useState(""),[m,x]=L.useState(!1),g=Tn(U=>U.buffers[e]),v=Tn(U=>U.openFile),S=Tn(U=>U.renameOpenFile),E=Tn(U=>U.closeFile),j=uo(),y=Ek(e),b=()=>o(!1),_=()=>{h(y),d(!0),b()},C=async()=>{const U=u.trim();if(!U||U===y){d(!1);return}try{const W=await window.api.files.rename(e,U);if(W.ok){const Y=e.slice(0,e.lastIndexOf("/")),V=W.newPath??`${Y}/${U}`;S(e,V),n==null||n(e,V),Le.info(`Renamed to ${U}`)}else Le.error(W.error??`Couldn't rename ${y}`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't rename ${y}`)}d(!1)},N=async()=>{b();try{const U=await window.api.files.duplicate(e);U.ok&&U.path?(v(U.path),Le.info(`Duplicated as ${Ek(U.path)}`)):Le.error(U.error??`Couldn't duplicate ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't duplicate ${y}`)}},$=async()=>{try{const U=await window.api.files.delete(e);U.ok?(E(e),r==null||r(e),Le.info(`Deleted ${y}`)):Le.error(U.error??`Couldn't delete ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't delete ${y}`)}x(!1)},R=async()=>{b();const U=g??"";try{await navigator.clipboard.writeText(U),Le.info(`Copied ${U.length} chars`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't copy ${y}`)}},O=()=>{if(b(),!j){Le.error("No terminal tab is active");return}window.api.pty.write({tabId:j.id,data:`@${e} `}),Le.info(`Added ${y} to Claude context`)},I=()=>{b(),window.api.shell.open({as:"openPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't open ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't open ${y}`))},z=()=>{b(),window.api.shell.open({as:"revealPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't reveal ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't reveal ${y}`))};return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>o(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:b}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[s.jsx(ob,{children:"Edit"}),s.jsx(_u,{label:"Rename",onClick:_}),s.jsx(_u,{label:"Duplicate",onClick:N}),s.jsx(_u,{label:"Delete document",danger:!0,onClick:()=>{b(),x(!0)}}),s.jsx(Nk,{}),s.jsx(ob,{children:"Open"}),s.jsx(_u,{label:"Open in default app",onClick:I}),s.jsx(_u,{label:"Reveal in OS",onClick:z}),s.jsx(Nk,{}),s.jsx(ob,{children:"Export"}),s.jsx(_u,{label:"Copy as Markdown",onClick:R}),s.jsx(_u,{label:"Add to Claude context",onClick:O,disabled:!j,title:j?void 0:"No terminal tab is active"})]})]}),l&&s.jsx(XO,{value:u,onChange:h,onCancel:()=>d(!1),onConfirm:()=>void C()}),m&&s.jsx(YO,{name:y,onCancel:()=>x(!1),onConfirm:()=>void $()})]})}function ob({children:e}){return s.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:e})}function _u({label:e,onClick:n,danger:r,disabled:i,title:o}){return s.jsx("button",{onClick:n,disabled:i,title:o,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${r?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:e})}function Nk(){return s.jsx("div",{className:"my-1 border-t border-line"})}function XO({value:e,onChange:n,onCancel:r,onConfirm:i}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:o=>{o.target===o.currentTarget&&r()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),s.jsx("input",{autoFocus:!0,value:e,onChange:o=>n(o.target.value),onKeyDown:o=>{o.key==="Enter"?i():o.key==="Escape"&&r()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function YO({name:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",e,"? This cannot be undone."]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function JO(){const[e,n]=L.useState(!1),r=Oh();return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>n(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),e&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>n(!1)}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[s.jsx(Th,{label:"Text size",children:s.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[s.jsx("button",{onClick:()=>r.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),s.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:r.fontSize}),s.jsx("button",{onClick:()=>r.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),s.jsx(Th,{label:"Word wrap",children:s.jsx(Tx,{on:r.wordWrap,onClick:r.toggleWordWrap})}),s.jsx(Th,{label:"Minimap",children:s.jsx(Tx,{on:r.minimap,onClick:r.toggleMinimap})}),s.jsx(Th,{label:"Theme",children:s.jsx("button",{onClick:()=>r.setTheme(r.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:r.theme==="dark"?"Dark":"Paper"})}),s.jsx(Th,{label:"Autosave",children:s.jsx(Tx,{on:r.autosave,onClick:r.toggleAutosave})}),s.jsx(Th,{label:"Wide measure",children:s.jsx(Tx,{on:r.wideMeasure,onClick:r.toggleWideMeasure})})]})]})]})}function Th({label:e,children:n}){return s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:e}),n]})}function Tx({on:e,onClick:n}){return s.jsx("button",{onClick:n,className:`px-2 py-0.5 text-[10px] rounded border border-line ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:e?"On":"Off"})}const QO=L.lazy(()=>Jm(()=>import("./TiptapBody-Dz0cPmSN.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.TiptapBody})));function $x(e){return e.split("/").filter(Boolean).pop()||e}function Ax(e,n){if(!n.length)return e;const r=new Set(n),i={};for(const[o,l]of Object.entries(e))r.has(o)||(i[o]=l);return i}function Rx(e){return aC(e)||lC(e)}function yw(){const e=Tn(Ye=>Ye.openFiles),n=Tn(Ye=>Ye.activeFilePath),r=Tn(Ye=>Ye.dirty),i=Tn(Ye=>Ye.viewMode),o=Tn(Ye=>Ye.buffers),l=Tn(Ye=>Ye.setActive),d=Tn(Ye=>Ye.closeFile),u=Tn(Ye=>Ye.closeOthers),h=Tn(Ye=>Ye.closeToTheRight),m=Tn(Ye=>Ye.closeAll),x=Tn(Ye=>Ye.loadBuffer),g=Tn(Ye=>Ye.setBuffer),v=Tn(Ye=>Ye.markSaved),S=Tn(Ye=>Ye.setViewMode),E=Oh(),[j,y]=L.useState({}),[b,_]=L.useState({}),[C,N]=L.useState(null),[$,R]=L.useState(null),[O,I]=L.useState(!1),[z,U]=L.useState(!1),[W,Y]=L.useState(!0),V=L.useRef(null),H=L.useRef(null),te=L.useRef(void 0),ae=L.useRef(null),oe=L.useRef(null),ie=UO(n??"",o[n??""]??""),X=L.useCallback(Ye=>{V.current=Ye},[]),Q=L.useCallback(()=>V.current,[]);L.useEffect(()=>{const Ye=n;if(!Ye||Rx(Ye))return;if(Tn.getState().hasBuffer(Ye)){y(kt=>kt[Ye]==="ready"?kt:{...kt,[Ye]:"ready"});return}let yt=!1;return y(kt=>({...kt,[Ye]:"loading"})),window.api.files.read(Ye).then(kt=>{yt||(kt.binary?y(Kt=>({...Kt,[Ye]:{binary:!0,size:kt.size??0,mime:kt.mime??"application/octet-stream",reason:kt.error??"Binary file"}})):kt.ok?(x(Ye,kt.text),y(Kt=>({...Kt,[Ye]:"ready"}))):y(Kt=>({...Kt,[Ye]:{error:kt.error??"failed to read"}})))}),()=>{yt=!0}},[n,x]),L.useEffect(()=>{R(null)},[n]);const J=L.useCallback(async(Ye,yt=!1)=>{const kt=Tn.getState().buffers[Ye];if(kt==null)return;yt&&I(!0);const Kt=await window.api.files.write(Ye,kt);Kt.ok?(v(Ye),_(On=>({...On,[Ye]:(On[Ye]??0)+1})),yt||Le.info(`Saved ${$x(Ye)}`)):Le.error(Kt.error??`Couldn't save ${$x(Ye)}`),yt&&I(!1)},[v]);L.useEffect(()=>{if(!E.autosave)return;const Ye=n;if(!(!Ye||Rx(Ye)||!r[Ye]))return window.clearTimeout(te.current),te.current=window.setTimeout(()=>{J(Ye,!0)},1200),()=>window.clearTimeout(te.current)},[E.autosave,n,r,o,J]);const le=L.useCallback(Ye=>{Ye.length&&(y(yt=>Ax(yt,Ye)),_(yt=>Ax(yt,Ye)))},[]),ce=L.useCallback((Ye,yt)=>{y(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt),_(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt)},[]),pe=L.useCallback(Ye=>{r[Ye]?N({kind:"one",path:Ye}):(d(Ye),le([Ye]))},[r,d,le]),Ae=L.useCallback(Ye=>{e.some(kt=>kt.path!==Ye&&r[kt.path])?N({kind:"others",path:Ye}):(u(Ye),le(e.filter(kt=>kt.path!==Ye).map(kt=>kt.path)))},[e,r,u,le]),Se=L.useCallback(Ye=>{const yt=e.findIndex(Kt=>Kt.path===Ye);yt!==-1&&e.slice(yt+1).some(Kt=>r[Kt.path])?N({kind:"right",path:Ye}):(h(Ye),le(yt!==-1?e.slice(yt+1).map(Kt=>Kt.path):[]))},[e,r,h,le]);L.useEffect(()=>{const Ye=yt=>{if((yt.metaKey||yt.ctrlKey)&&(yt.key==="s"||yt.key==="S")){const kt=Tn.getState().activeFilePath;kt&&!Rx(kt)&&(yt.preventDefault(),J(kt))}else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="f"||yt.key==="F"))yt.preventDefault(),U(kt=>!kt);else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="w"||yt.key==="W")){const kt=Tn.getState().activeFilePath;kt&&Tn.getState().openFiles.length>1&&(yt.preventDefault(),Ae(kt))}else yt.key==="Escape"&&ie.state.phase!=="idle"?ie.cancel():yt.key==="Escape"&&z&&U(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[J,z,Ae,ie.state.phase,ie.cancel]),L.useEffect(()=>{if(ie.state.phase==="idle")return;const Ye=yt=>{var Kt,On;const kt=yt.target;(Kt=oe.current)!=null&&Kt.contains(kt)||(On=ae.current)!=null&&On.contains(kt)||ie.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[ie.state.phase,ie.cancel]),L.useEffect(()=>{ie.cancel()},[n,ie.cancel]);const ye=L.useCallback(()=>{e.some(yt=>r[yt.path])?N({kind:"all",path:""}):(m(),y({}),_({}))},[e,r,m]),ne=()=>{if(C){if(C.kind==="one")d(C.path),le([C.path]);else if(C.kind==="others"){const Ye=e.filter(yt=>yt.path!==C.path).map(yt=>yt.path);u(C.path),le(Ye)}else if(C.kind==="right"){const Ye=e.findIndex(kt=>kt.path===C.path),yt=Ye!==-1?e.slice(Ye+1).map(kt=>kt.path):[];h(C.path),le(yt)}else m(),y({}),_({});N(null)}};if(e.length===0)return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"mb-2",children:"no file open"}),s.jsxs("div",{children:["open the ",s.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const we=n,Ne=we?$x(we):"",Je=we?j[we]:void 0,lt=we?dC(we):!1,xt=we?E$(we):!1,Rt=we&<?i[we]??N$(we):"edit",He=!!we&&!Rx(we)&&Je==="ready",bt=He,st=xt?["edit","wysiwyg","preview","split"]:lt?["edit","preview"]:[],an=we&&s.jsx(pO,{path:we,name:Ne,value:o[we]??"",onChange:Ye=>g(we,Ye),onSave:()=>void J(we),onReady:X,onCursor:R}),sn=O?"Saving…":we&&r[we]?E.autosave?"Editing…":"Unsaved":"All changes saved";return s.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!z&&s.jsx(uO,{openFiles:e,activeFilePath:n,dirty:r,onSelectFile:l,onCloseFile:pe,onCloseOthers:Ae,onCloseToTheRight:Se,onCloseAll:ye}),we&&!z&&s.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[s.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ne}),s.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:we}),He&&s.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",sn]}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:()=>Y(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${W?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),st.length>0&&s.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:st.map(Ye=>s.jsx("button",{onClick:()=>S(we,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${Rt===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),s.jsx("div",{className:"flex-1"}),s.jsx(KO,{path:we,onRenamed:ce,onDeleted:Ye=>le([Ye])}),He&&s.jsx(JO,{}),s.jsx("button",{onClick:()=>U(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),z&&s.jsx("button",{onClick:()=>U(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),s.jsx("div",{className:"flex-1 min-h-0",children:we?aC(we)?s.jsx(CO,{path:we,name:Ne}):lC(we)?s.jsx(jO,{path:we}):Je&&typeof Je=="object"&&"binary"in Je?s.jsx(MO,{path:we,name:Ne,size:Je.size,mime:Je.mime,reason:Je.reason}):Je&&typeof Je=="object"&&"error"in Je?s.jsx("div",{className:"p-6 text-xs text-red-400",children:Je.error}):Je!=="ready"?s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):Rt==="wysiwyg"&&cl(we)?s.jsx(L.Suspense,{fallback:s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:s.jsx(QO,{value:o[we]??"",onChange:Ye=>g(we,Ye)},we)}):Rt==="split"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(_k,{text:o[we]??"",scrollRef:H}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[s.jsx(wk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(bk,{ref:H,text:o[we]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(jk,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(_k,{text:o[we]??"",scrollRef:H}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(bk,{ref:H,text:o[we]??"",wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(jk,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&oC(we)?s.jsx(kO,{path:we,dirty:!!r[we],reloadToken:b[we]??0}):Rt==="preview"&&cC(we)?s.jsx(NO,{path:we,text:o[we]??""}):Rt==="preview"&&uC(we)?s.jsx(AO,{path:we,text:o[we]??""}):cl(we)?s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(wk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}):an:null}),bt&&s.jsx(_O,{text:o[we]??"",cursor:$,language:zi(we)||void 0}),we&&cl(we)&&(Rt==="preview"||Rt==="split")&&ie.state.phase!=="idle"&&ie.state.selection&&s.jsx("div",{ref:oe,children:s.jsx(VO,{phase:ie.state.phase,rect:ie.state.selection.rect,diff:ie.state.diff,transcript:ie.state.transcript,modelStatus:ie.state.modelStatus,onQuickAction:ie.run,onRunCustom:ie.run,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onReject:ie.cancel,onRetry:ie.retry,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)}})}),C&&s.jsx(ZO,{message:C.kind==="one"?`Discard unsaved changes to ${$x(C.path)}?`:C.kind==="others"?"Discard unsaved changes in the other open files?":C.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:ne})]})}function ZO({message:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:e}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Tk={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},e5={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function ab(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":String(e)}function t5({open:e,onClose:n,variant:r="overlay"}){const i=vt($=>$.tabs.find(R=>R.id===$.activeTabId)??null),o=(i==null?void 0:i.cwd)??null,[l,d]=L.useState(null),[u,h]=L.useState(!1),[m,x]=L.useState(null),g=L.useRef(null),v=L.useCallback(async $=>{h(!0),x(null);try{const R=await window.api.repo.analyze($);R.ok?d(R):(x(R.error||"Analysis failed"),d(null))}catch(R){x(R instanceof Error?R.message:String(R)),d(null)}finally{h(!1)}},[]);L.useEffect(()=>{if(e){if(!o){x("No active session — open a tab in a folder first.");return}v(o)}},[e,o,v]),L.useEffect(()=>{var R;if(!e)return;const $=O=>{O.key==="Escape"&&(O.stopPropagation(),n())};return window.addEventListener("keydown",$),(R=g.current)==null||R.focus(),()=>window.removeEventListener("keydown",$)},[e,n]);const S=L.useCallback(()=>{o&&v(o)},[o,v]),E=L.useMemo(()=>l?Object.entries(l.languageBreakdown).map(([R,O])=>[R,O.files,O.lines]).sort((R,O)=>O[1]-R[1]).slice(0,12):[],[l]),j=L.useMemo(()=>E.length===0?1:E[0][1],[E]),y=L.useMemo(()=>{if(!l)return[];const $=l.topDirectories;if($.length===0)return[];const R=$.map(I=>Math.sqrt(Math.max(1,I.fileCount))),O=R.reduce((I,z)=>I+z,0)||1;return $.map((I,z)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:R[z]/O*100}))},[l]);if(!e)return null;const b=$=>{$.target===$.currentTarget&&n()},_=o?o.split("/").filter(Boolean).pop()||o:"no folder",C=r==="page",N=s.jsx("div",{className:C?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:C?void 0:b,"data-testid":"repoviz-backdrop",children:s.jsxs("div",{ref:g,role:C?void 0:"dialog","aria-modal":C?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:C?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[s.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),s.jsxs("div",{className:"text-xs text-fg-dim truncate",title:o??"",children:[_,(l==null?void 0:l.gitStatus.branch)&&s.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",l.gitStatus.branch,")"]}),(l==null?void 0:l.truncated)&&s.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[l&&l.gitStatus.uncommitted>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${l.gitStatus.uncommitted} uncommitted files`,children:[l.gitStatus.uncommitted," uncommitted"]}),s.jsxs("button",{type:"button",onClick:S,disabled:u||!o,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[u?"…":"↻"," Refresh"]}),s.jsx("button",{type:"button",onClick:n,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:u&&!l?s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[s.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),s.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),s.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):m?s.jsxs("div",{className:"py-16 text-center",children:[s.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),s.jsx("div",{className:"text-sm text-red-400",children:m})]}):l?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsx(lb,{label:"Files",value:ab(l.totalFiles)}),s.jsx(lb,{label:"Lines of code",value:ab(l.totalLines)}),s.jsx(lb,{label:"Uncommitted",value:String(l.gitStatus.uncommitted),tone:l.gitStatus.uncommitted>0?"warn":"neutral"})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),E.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):s.jsx("div",{className:"space-y-1.5",children:E.map(([$,R,O])=>{const I=Tk[$]??Tk.other,z=e5[$]??$,U=R/j*100;return s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"w-24 text-fg-dim truncate",title:z,children:z}),s.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:s.jsx("div",{className:"h-full rounded",style:{width:`${U}%`,backgroundColor:I}})}),s.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[R," files"]}),s.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[ab(O)," L"]})]},$)})})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),y.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):s.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:y.map($=>s.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max($.basis,6)}%`,flexGrow:$.basis>15?1:0},title:`${$.path} — ${$.fileCount} files, ${$.totalLines.toLocaleString()} lines`,children:[s.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:$.path}),s.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[$.fileCount," files"]})]},$.path))})]}),s.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",l.durationMs,"ms",l.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):s.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!C&&typeof document<"u"&&document.body?Hu.createPortal(N,document.body):N}function lb({label:e,value:n,tone:r="neutral"}){const i=r==="warn"?"text-amber-400":"text-fg";return s.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[s.jsx("div",{className:`text-xl font-medium ${i}`,children:n}),s.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:e})]})}function qu({options:e,active:n,onChange:r}){return s.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:e.map(({key:i,label:o})=>s.jsx("button",{onClick:()=>r(i),className:`px-2 py-0.5 text-xs ${n===i?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:o},i))})}const $k=e=>/[/\\\-_.\s]/.test(e),Ak=e=>e>="A"&&e<="Z";function n5(e,n,r){if(!e)return{match:!0,score:0,matched:[]};const i=e.toLowerCase(),o=n.toLowerCase(),l=(r||n).toLowerCase(),d=n.split("/").pop()||n,u=d.toLowerCase();if(u===i)return{match:!0,score:1e3,matched:Array.from({length:d.length},(b,_)=>_)};if(u.startsWith(i))return{match:!0,score:900,matched:Array.from({length:e.length},(b,_)=>_)};let h=0;for(const b of l.split("/")){if(b===i)return{match:!0,score:800,matched:[]};b.startsWith(i)&&(h=Math.max(h,700))}const m=u.indexOf(i);if(m!==-1)return{match:!0,score:m===0||$k(u[m-1])||Ak(d[m])?650:600,matched:Array.from({length:e.length},(_,C)=>m+C)};if(l.includes(i))return{match:!0,score:Math.max(500,h),matched:[]};let x=0,g=0,v=0,S=-1,E=0;const j=[];for(let b=0;b<o.length&&x<i.length;b++)o[b]===i[x]&&(j.push(b),g+=10,S===b-1?(v++,g+=v*8):v=0,(b===0||$k(o[b-1])||Ak(n[b]))&&(E++,g+=15,b===0&&(g+=10)),S=b,x++);if(x!==i.length)return{match:!1,score:0,matched:[]};const y=Math.max(0,50-(o.length-i.length));if(g+=y,E>=i.length*.5&&(g+=30),j.length>1){const b=j[j.length-1]-j[0];b>i.length*3&&(g-=Math.min(50,(b-i.length*3)*2))}return{match:!0,score:Math.max(1,g),matched:j}}function cb(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function Rk(e){const n=e.lastIndexOf("/");return n<0?"":e.slice(0,n)}const Mk="session-manager.quickopen.recent",r5=8;function s5({open:e,onClose:n,variant:r="overlay"}){const i=vt(z=>z.tabs.find(U=>U.id===z.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState([]),[m,x]=L.useState(!1),[g,v]=L.useState(0),[S,E]=L.useState([]),j=L.useRef(null),y=L.useRef(null);L.useEffect(()=>{if(e)try{const z=localStorage.getItem(Mk);z&&E(JSON.parse(z))}catch{}},[e]),L.useEffect(()=>{if(!e){d(""),v(0);return}const z=setTimeout(()=>{var U;return(U=j.current)==null?void 0:U.focus()},0);return()=>clearTimeout(z)},[e]),L.useEffect(()=>{if(!e||!o)return;let z=!1;return x(!0),window.api.search.files(o,"",{limit:5e3}).then(U=>{if(!z){if(!U.ok){Le.error(`File search failed: ${U.error??"unknown error"}`),h([]);return}h(U.files)}}).catch(U=>{const W=U instanceof Error?U.message:String(U);dt.error("quick-open","search.files threw",{error:W}),Le.error(`File search failed: ${W}`),h([])}).finally(()=>{z||x(!1)}),()=>{z=!0}},[e,o]);const b=L.useMemo(()=>{if(!l.trim())return[...u].sort((Y,V)=>Y.name.localeCompare(V.name)).slice(0,100).map(Y=>({file:Y,score:0,matched:[]}));const z=l.trim(),U=[];for(const W of u){const Y=n5(z,W.name,W.path);Y.match&&U.push({file:W,score:Y.score,matched:Y.matched})}return U.sort((W,Y)=>Y.score-W.score),U.slice(0,100)},[u,l]),_=L.useMemo(()=>l.trim()?[]:S.map(z=>u.find(U=>U.path===z)||null).filter(z=>z!==null).slice(0,5),[S,u,l]);L.useEffect(()=>{const z=_.length+b.length;g>=z&&v(Math.max(0,z-1))},[_.length,b.length,g]),L.useEffect(()=>{if(!y.current)return;const z=y.current.querySelector(`[data-row="${g}"]`);z&&z.scrollIntoView({block:"nearest"})},[g]);const C=L.useCallback(z=>{try{const V=[z,...S.filter(H=>H!==z)].slice(0,r5);E(V),localStorage.setItem(Mk,JSON.stringify(V))}catch{}const U=i==null?void 0:i.id;if(!U){Le.error("No active tab to receive file path");return}const Y=(o?cb(z,o):z)||z;try{window.api.pty.write({tabId:U,data:Y})}catch(V){const H=V instanceof Error?V.message:String(V);dt.error("quick-open","pty.write failed",{error:H}),Le.error(`Failed to write to terminal: ${H}`);return}n()},[i==null?void 0:i.id,o,S,n]),N=L.useCallback(z=>{const U=_.length+b.length;if(z.key==="Escape"){z.preventDefault(),n();return}if(z.key==="ArrowDown"){if(z.preventDefault(),U===0)return;v(W=>Math.min(U-1,W+1));return}if(z.key==="ArrowUp"){if(z.preventDefault(),U===0)return;v(W=>Math.max(0,W-1));return}if(z.key==="Enter"){if(z.preventDefault(),g<_.length){const V=_[g];V&&C(V.path);return}const W=g-_.length,Y=b[W];Y&&C(Y.file.path)}},[g,b,_,C,n]);if(!e)return null;const $=(z,U)=>{if(U.length===0)return z;const W=new Set(U);return z.split("").map((Y,V)=>s.jsx("span",{className:W.has(V)?"text-accent font-semibold":"",children:Y},V))};let R=-1;const O=r==="page",I=s.jsx("div",{className:O?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:O?void 0:z=>{z.target===z.currentTarget&&n()},"data-testid":"quick-open-backdrop",children:s.jsxs("div",{role:O?void 0:"dialog","aria-modal":O?void 0:"true","aria-label":"Quick Open",className:O?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:N,children:[s.jsx("div",{className:"border-b border-line p-2",children:s.jsx("input",{ref:j,type:"text",value:l,onChange:z=>{d(z.target.value),v(0)},placeholder:o?"Search files in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),s.jsx("div",{ref:y,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:m?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):o?_.length===0&&b.length===0?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:l?"No files match.":"No files found in this project."}):s.jsxs(s.Fragment,{children:[_.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),_.map(z=>{R++;const U=R,W=U===g;return s.jsxs("button",{"data-row":U,role:"option","aria-selected":W,onClick:()=>C(z.path),onMouseEnter:()=>v(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${W?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:z.name}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Rk(z.path),o)})]},`r:${z.path}`)})]}),b.length>0&&s.jsxs("div",{children:[_.length>0&&s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),b.map(({file:z,matched:U})=>{R++;const W=R,Y=W===g;return s.jsxs("button",{"data-row":W,role:"option","aria-selected":Y,onClick:()=>C(z.path),onMouseEnter:()=>v(W),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Y?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:$(z.name,U)}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Rk(z.path),o)})]},z.path)})]})]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[b.length+_.length," ",b.length+_.length===1?"file":"files"]})]})]})});return!O&&typeof document<"u"&&document.body?Hu.createPortal(I,document.body):I}function Ik(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function i5(e,n,r){if(!n)return e;const i=r?e:e.toLowerCase(),o=r?n:n.toLowerCase(),l=i.indexOf(o);return l<0?e:s.jsxs(s.Fragment,{children:[e.slice(0,l),s.jsx("span",{className:"text-accent font-semibold",children:e.slice(l,l+n.length)}),e.slice(l+n.length)]})}function o5({open:e,onClose:n,variant:r="overlay"}){const i=vt(V=>V.tabs.find(H=>H.id===V.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState(!1),[m,x]=L.useState([]),[g,v]=L.useState(!1),[S,E]=L.useState(null),[j,y]=L.useState(0),[b,_]=L.useState(null),C=L.useRef(null),N=L.useRef(null),$=L.useRef(0);L.useEffect(()=>{if(!e){d(""),x([]),E(null),y(0);return}const V=setTimeout(()=>{var H;return(H=C.current)==null?void 0:H.focus()},0);return()=>clearTimeout(V)},[e]),L.useEffect(()=>{if(!e||!o)return;const V=l.trim();if(!V){x([]),E(null),v(!1);return}const H=++$.current;v(!0);const te=setTimeout(()=>{window.api.search.text(o,V,{caseSensitive:u,limit:500}).then(ae=>{H===$.current&&(ae.ok?(x(ae.matches),E(null)):(E(ae.error??"unknown error"),x([])),_(ae.usedRipgrep))}).catch(ae=>{if(H!==$.current)return;const oe=ae instanceof Error?ae.message:String(ae);dt.error("global-search","search.text threw",{error:oe}),E(oe),x([])}).finally(()=>{H===$.current&&v(!1)})},250);return()=>clearTimeout(te)},[e,o,l,u]);const R=L.useMemo(()=>{const V=new Map;for(const te of m){const ae=V.get(te.path);ae?ae.push(te):V.set(te.path,[te])}const H=[];for(const[te,ae]of V)H.push({path:te,matches:ae});return H.sort((te,ae)=>ae.matches.length-te.matches.length||te.path.localeCompare(ae.path)),H},[m]),O=L.useMemo(()=>m,[m]);L.useEffect(()=>{j>=O.length&&y(Math.max(0,O.length-1))},[O.length,j]),L.useEffect(()=>{if(!N.current)return;const V=N.current.querySelector(`[data-match="${j}"]`);V&&V.scrollIntoView({block:"nearest"})},[j]);const I=L.useCallback(V=>{const H=i==null?void 0:i.id;if(!H){Le.error("No active tab to receive path");return}const ae=`${(o?Ik(V.path,o):V.path)||V.path}:${V.line}`;try{window.api.pty.write({tabId:H,data:ae})}catch(oe){const ie=oe instanceof Error?oe.message:String(oe);dt.error("global-search","pty.write failed",{error:ie}),Le.error(`Failed to write to terminal: ${ie}`);return}n()},[i==null?void 0:i.id,o,n]),z=L.useCallback(V=>{if(V.key==="Escape"){V.preventDefault(),n();return}if(V.key==="ArrowDown"){if(V.preventDefault(),O.length===0)return;y(H=>Math.min(O.length-1,H+1));return}if(V.key==="ArrowUp"){if(V.preventDefault(),O.length===0)return;y(H=>Math.max(0,H-1));return}if(V.key==="Enter"){V.preventDefault();const H=O[j];H&&I(H)}},[O,j,I,n]);if(!e)return null;const U=r==="page";let W=-1;const Y=s.jsx("div",{className:U?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:U?void 0:V=>{V.target===V.currentTarget&&n()},"data-testid":"global-search-backdrop",children:s.jsxs("div",{role:U?void 0:"dialog","aria-modal":U?void 0:"true","aria-label":"Search in project",className:U?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:z,children:[s.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[s.jsx("input",{ref:C,type:"text",value:l,onChange:V=>{d(V.target.value),y(0)},placeholder:o?"Search in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),s.jsx("button",{type:"button",onClick:()=>h(V=>!V),className:`px-2 py-1 text-xs rounded border ${u?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":u,children:"Aa"})]}),s.jsx("div",{ref:N,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:o?l.trim()?g?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):S?s.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:S}):O.length===0?s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(l),"."]}):s.jsx("div",{children:R.map(V=>s.jsxs("div",{children:[s.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[Ik(V.path,o)," ",s.jsxs("span",{className:"text-fg-faint",children:["(",V.matches.length,")"]})]}),V.matches.map(H=>{W++;const te=W,ae=te===j;return s.jsxs("button",{"data-match":te,role:"option","aria-selected":ae,onClick:()=>I(H),onMouseEnter:()=>y(te),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ae?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:H.line}),s.jsx("span",{className:"truncate",children:i5(H.text,l,u)})]},`${H.path}:${H.line}:${H.column}:${te}`)})]},V.path))}):s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",s.jsx("span",{className:"font-mono",children:o}),"."]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[O.length," ",O.length===1?"match":"matches",b===!1&&" · fs walk (rg missing)"]})]})]})});return!U&&typeof document<"u"&&document.body?Hu.createPortal(Y,document.body):Y}const a5=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function l5({open:e,onClose:n,variant:r="page",initialMode:i="files"}){const[o,l]=L.useState(i);return L.useEffect(()=>{l(i)},[i]),e?s.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[s.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[s.jsx(qu,{options:a5,active:o,onChange:l}),s.jsx("span",{className:"text-[11px] text-fg-faint",children:o==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),s.jsx("div",{className:"flex-1 min-h-0",children:o==="files"?s.jsx(s5,{open:!0,onClose:n,variant:"page"}):s.jsx(o5,{open:!0,onClose:n,variant:"page"})})]}):null}class _j extends L.Component{constructor(){super(...arguments);Fn(this,"state",{error:null});Fn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,i){console.error("[ErrorBoundary]",r,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):s.jsxs("div",{className:"p-6 text-xs",children:[s.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),s.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),s.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function c5({open:e,onClose:n,title:r,children:i,variant:o="overlay"}){return s.jsxs(Wu,{open:e,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:o,children:[o==="overlay"&&s.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[s.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:r}),s.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(_j,{children:i})})]})}function u5(e){return/^monitor of /i.test(e.trim())}function Pk(e){return e.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Dk(e,n,r){if(e){const d=r.find(u=>u.deviceId===e);if(d)return d}if(!n)return null;const i=r.filter(d=>d.label===n);if(i.length===1)return i[0];if(i.length>1)return null;const o=Pk(n),l=r.filter(d=>d.label&&Pk(d.label)===o);return l.length===1?l[0]:null}async function Ok(e){var r;return(r=navigator.mediaDevices)!=null&&r.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(i=>!(i.kind!=="audioinput"||i.label&&u5(i.label))):[]}const Lk=!1;function kj(){const e=$t(m=>m.isRecording);$t(m=>m.startRecording),$t(m=>m.stopRecording);const[n,r]=L.useState([]),[i,o]=L.useState(null),[l,d]=L.useState(null);L.useEffect(()=>{let m=!1;return(async()=>{try{const x=await window.api.voice.getDevicePref();if(m)return;const g=await Ok(Lk);if(m)return;r(g),d(x.selectedLabel);const v=Dk(x.selectedDeviceId,x.selectedLabel,g);v?(o(v.deviceId),x.selectedDeviceId&&v.deviceId!==x.selectedDeviceId&&(dt.info("voice","device-picker rebind-by-label",{fromIdPrefix:x.selectedDeviceId.slice(0,8),toIdPrefix:v.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||x.selectedLabel}).catch(()=>{}))):((x.selectedDeviceId||x.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:x.selectedLabel,hadId:!!x.selectedDeviceId}),dt.warn("voice","device-picker selected-unavailable",{hadId:!!x.selectedDeviceId})),o(null))}catch(x){dt.warn("voice","device-picker init failed",{error:x instanceof Error?x.message:String(x)})}})(),()=>{m=!0}},[]);const u=L.useCallback(async()=>{try{const m=await Ok(Lk);if(r(m),i&&!m.some(x=>x.deviceId===i)){const x=Dk(null,l,m);x?(o(x.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:x.deviceId,selectedLabel:x.label||l}).catch(()=>{})):o(null)}}catch(m){dt.warn("voice","device-picker refresh failed",{error:m instanceof Error?m.message:String(m)})}},[i,l]);L.useEffect(()=>{const m=()=>{u()};return window.addEventListener("mic-device-change",m),()=>window.removeEventListener("mic-device-change",m)},[u]);const h=async m=>{var S;const x=m.target.value,g=x===""?null:x,v=g?((S=n.find(E=>E.deviceId===g))==null?void 0:S.label)??null:null;o(g),d(v);try{await window.api.voice.setDevicePref({selectedDeviceId:g,selectedLabel:v}),dt.info("voice","device-picker selected",{deviceIdPrefix:g?g.slice(0,8):null})}catch(E){dt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(e)try{await $t.getState().restartWithDevice()}catch(E){dt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};return s.jsxs("select",{value:i??"",onChange:h,onFocus:()=>{u()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[s.jsx("option",{value:"",children:"Default"}),n.map(m=>s.jsx("option",{value:m.deviceId,children:m.label||`Mic ${m.deviceId.slice(0,6)}`},m.deviceId))]})}function d5(){const e=$t(S=>S.isRecording),n=$t(S=>S.levelMeterEnabled),[r,i]=L.useState(0),[o,l]=L.useState(0),d=L.useRef(0);d.current=o;const[u,h]=L.useState(0),[m,x]=L.useState(!1),g=L.useRef(null);if(L.useEffect(()=>{if(!e||!n){i(0),l(0);return}let S=0,E=!1,j=null,y=null;const b=()=>{if(E)return;const C=y??Y2();if(!C){S=requestAnimationFrame(b);return}y!==C&&(y=C,j=new Uint8Array(new ArrayBuffer(C.fftSize)));const N=j;C.getByteTimeDomainData(N);let $=0;for(let z=0;z<N.length;z++){const U=N[z]-128;$+=U*U}const R=Math.sqrt($/N.length)/128,O=R>0?20*Math.log10(R):-60,I=Math.max(0,Math.min(1,(O+60)/60));l(R),i(I),R>=.95&&(x(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(!1),150)),S=requestAnimationFrame(b)};S=requestAnimationFrame(b);const _=setInterval(()=>{E||h(Math.round(d.current*100))},250);return()=>{E=!0,cancelAnimationFrame(S),clearInterval(_),g.current&&(clearTimeout(g.current),g.current=null)}},[e,n]),!e||!n)return null;const v=m?"bg-red-500":o>=.7?"bg-amber-400":"bg-green-500";return s.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":u,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${m?"ring-1 ring-red-500":""}`,children:s.jsx("div",{className:`h-full ${v} transition-[width] duration-75 ease-out`,style:{width:`${r*100}%`}})})}function h5({open:e,onClose:n,variant:r="overlay"}){return s.jsx(c5,{open:e,onClose:n,title:"Voice / Microphone",variant:r,children:s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsx(g5,{}),s.jsx(FC,{}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Q2,{}),s.jsx(kj,{}),s.jsx(e$,{})]}),s.jsx(f5,{}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[s.jsx("button",{type:"button",onClick:()=>$t.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),s.jsx(m5,{})]}),s.jsx(d5,{})]})})}function f5(){const e=$t(l=>l.isRecording),[n,r]=L.useState(null);if(L.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(u=>{l||r(u)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(u=>r(u));return()=>{l=!0,d()}},[]),e||!n)return null;const i=n.mode==="hold"?"Hold":"Press",o=p5(n.accelerator);return s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("span",{children:[i," "]}),s.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:o}),s.jsx("span",{children:" to record"})]})}function p5(e){const n=typeof navigator<"u"&&/Mac/.test(navigator.platform);return e.replace(/CommandOrControl/g,n?"⌘":"Ctrl").replace(/CmdOrCtrl/g,n?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,n?"⌥":"Alt").replace(/Shift/g,n?"⇧":"Shift")}function m5(){const[e,n]=L.useState(null);if(L.useEffect(()=>{let i=!1;window.api.voice.getHotkeyConfig().then(l=>{i||n(l)}).catch(l=>dt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const o=window.api.voice.onHotkeyConfigChanged(l=>{n(l)});return()=>{i=!0,o()}},[]),!e)return null;const r=async i=>{if(e.mode===i)return;const o={...e,mode:i};n(o);try{await window.api.voice.setHotkeyConfig(o)}catch(l){dt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return s.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="toggle",onChange:()=>r("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),s.jsx("span",{children:"Tap on/off"})]}),s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="hold",onChange:()=>r("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),s.jsx("span",{children:"Hold to talk"})]})]})}function g5(){const e=$t(l=>l.isRecording),n=$t(l=>l.lastTranscript),r=$t(l=>l.error),i=$t(l=>l.modelStatus),o=$t(l=>l.loadingProgress);return r?s.jsxs("div",{className:"text-[11px] text-red-400",title:r,children:["⚠ ",r]}):e?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[s.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),s.jsx("span",{className:"truncate",title:n,children:n||"Listening…"})]}):i==="loading"?s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("span",{children:"Loading speech model"}),s.jsxs("span",{className:"font-mono",children:[o,"%"]})]}),s.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:s.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${o}%`}})})]}):null}let ub=null;function x5(){return ub||(ub=Jm(()=>import("./monaco-editor-BW5C4Iv1.js").then(e=>e.b),__vite__mapDeps([1,2]),import.meta.url).then(e=>(f0.config({monaco:e}),e))),ub}function Sj({value:e,onChange:n,path:r,readOnly:i}){const o=L.useRef(null),l=d=>{o.current=d};return s.jsx(p0,{path:`file://${r}`,defaultLanguage:"json",value:e,onChange:d=>n(d??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:i,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let zk=!1;async function y5(e){if(zk)return;const n=await x5(),r=await Promise.all(e.map(async o=>{let l=o.schema;if(!l){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const u=new URL(o.uri).origin;if(!d.includes(u))throw new Error("untrusted origin");const h=await fetch(o.uri);h.ok&&(l=await h.json())}catch{}}return{uri:o.uri,fileMatch:o.fileMatch,schema:l}}));n.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:r.filter(o=>o.schema),enableSchemaRequest:!0}),zk=!0}function b0({node:e,targetScope:n,onOverride:r,schema:i,rootLabel:o}){const[l,d]=L.useState(""),[u,h]=L.useState(!0),m=[],x=e.kind==="object"&&Object.keys(e.children).length===0,v=((i==null?void 0:i.rootKeys())??[]).length>0;return s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",s.jsx("span",{className:"text-fg-dim",children:os[n].label})]}),v&&s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:S=>h(S.target.checked),className:"accent-accent"}),"show unset keys"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:l,onChange:S=>d(S.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),s.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:x&&!u?s.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):s.jsx(Cj,{node:e,path:m,label:o??"(root)",targetScope:n,onOverride:r,filter:l,depth:0,schema:i,showGhosts:u,defaultOpen:!0})})]})}function Cj(e){return e.node.kind==="object"?s.jsx(v5,{...e,node:e.node}):e.node.kind==="array"?s.jsx(b5,{...e,node:e.node}):s.jsx(w5,{...e,node:e.node})}function Bk(e,n){return n.trim()?e.toLowerCase().includes(n.toLowerCase()):!0}function Zh(e,n,r){return!!(!r.trim()||e.some(i=>Bk(i,r))||n!=null&&n.description&&Bk(n.description,r))}function v5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u,showGhosts:h,defaultOpen:m}){const[x,g]=L.useState(m??d<2),v=(u==null?void 0:u.at(n))??null,S=new Set(Object.keys(e.children)),E=h?(v==null?void 0:v.knownChildren)??[]:[],j=Array.from(new Set([...S,...E])).sort(),y=L.useMemo(()=>l.trim()?j.filter(_=>{const C=(u==null?void 0:u.at([...n,_]))??null;return Zh([...n,_],C,l)?!0:S.has(_)?jj(e.children[_],[...n,_],l,u):!1}):j,[j.join(","),l,e,n.join("."),u]);if(l.trim()&&y.length===0&&!Zh(n,v,l))return null;if(n.length===0)return s.jsx("div",{children:y.map(_=>b(_))});return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>g(!x),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:x?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" {",S.size,E.length>S.size?`/${new Set([...S,...E]).size}`:"","}"]}),(v==null?void 0:v.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:v.description,children:["— ",v.description]})]}),x&&y.map(_=>b(_))]});function b(_){if(S.has(_))return s.jsx(Cj,{node:e.children[_],path:[...n,_],label:_,targetScope:i,onOverride:o,filter:l,depth:d+1,schema:u,showGhosts:h},_);const C=(u==null?void 0:u.at([...n,_]))??null;return C?s.jsx(_5,{path:[...n,_],label:_,info:C,targetScope:i,onSet:o,depth:d+1,filter:l},_):null}}function jj(e,n,r,i){const o=(i==null?void 0:i.at(n))??null;if(Zh(n,o,r))return!0;if(e.kind!=="object")return!1;for(const l of Object.keys(e.children))if(jj(e.children[l],[...n,l],r,i))return!0;return!1}function b5({node:e,path:n,label:r,filter:i,depth:o,schema:l}){const[d,u]=L.useState(!0),h=(l==null?void 0:l.at(n))??null;return Zh(n,h,i)?s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:o*14},onClick:()=>u(!d),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" [",e.items.length,"]"]}),s.jsx(Hm,{tone:"warn",children:"accumulated"}),(h==null?void 0:h.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:h.description,children:["— ",h.description]})]}),d&&e.items.map((m,x)=>s.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(o+1)*14},children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),s.jsxs("span",{className:"text-fg-faint",children:[x,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:$y(m.value)}),s.jsx(vw,{scope:m.fromScope})]},x))]}):null}function w5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u}){const[h,m]=L.useState(!1),x=(u==null?void 0:u.at(n))??null;if(!Zh(n,x,l))return null;const g=e.winner!==i,v=e.shadowed.length>0;return s.jsxs("div",{children:[s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[s.jsx("span",{className:`w-3 shrink-0 ${v?"text-fg-faint cursor-pointer":""}`,onClick:()=>v&&m(!h),children:v?h?"▾":"▸":""}),s.jsxs("span",{className:"text-fg",children:[r,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-md",children:$y(e.value)}),s.jsx(vw,{scope:e.winner}),(x==null?void 0:x.deprecated)&&s.jsx(Hm,{tone:"warn",children:"deprecated"}),(x==null?void 0:x.default)!==void 0&&k5(e.value,x.default)&&s.jsx(Hm,{tone:"dim",children:"= default"}),e.typeMismatch&&s.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(x==null?void 0:x.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:x.description,children:["— ",x.description]}),s.jsx("div",{className:"flex-1"}),(x==null?void 0:x.enum)&&s.jsx(Ej,{values:x.enum}),s.jsx("button",{disabled:!g,onClick:()=>o(n,e.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${g?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:g?`copy into ${os[i].label} draft`:`already winning in ${os[i].label}`,children:"override"})]}),h&&e.shadowed.map((S,E)=>s.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[s.jsx("span",{children:"shadowed:"}),s.jsx("span",{className:"truncate max-w-xl",children:$y(S.value)}),s.jsx(vw,{scope:S.scope,dim:!0})]},E))]})}function _5({path:e,label:n,info:r,targetScope:i,onSet:o,depth:l,filter:d}){if(!Zh(e,r,d))return null;const u=r.default!==void 0?r.default:S5(r.type),h=Array.isArray(r.type)?r.type.join("|"):r.type??"?";return s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:l*14},children:[s.jsx("span",{className:"w-3 shrink-0"}),s.jsx("span",{className:"text-fg-dim",children:n}),s.jsx(Hm,{tone:"dim",children:h}),r.required&&s.jsx(Hm,{tone:"warn",children:"required"}),r.default!==void 0&&s.jsxs("span",{className:"text-fg-faint",children:["default: ",$y(r.default)]}),r.description&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:r.description,children:["— ",r.description]}),s.jsx("div",{className:"flex-1"}),r.enum&&s.jsx(Ej,{values:r.enum}),s.jsx("button",{onClick:()=>o(e,u),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${os[i].label} draft`,children:"set"})]})}function k5(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function S5(e){switch(Array.isArray(e)?e[0]:e){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function $y(e){if(typeof e=="string")return JSON.stringify(e);if(e===null)return"null";if(typeof e=="object"){const n=JSON.stringify(e);return n.length>100?n.slice(0,100)+"…":n}return String(e)}function vw({scope:e,dim:n}){const r=e==="user"?"bg-bg-hi text-fg-dim border-line":e==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r} ${n?"opacity-60":""}`,children:os[e].label})}function Hm({children:e,tone:n="default"}){const r={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[n];return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r}`,children:e})}function Ej({values:e}){const n=e.map(r=>String(r)).join(" | ");return s.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${n}`,children:["∈ ",n.length>30?n.slice(0,30)+"…":n]})}const C5=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],j5={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function Nj(e){return e.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((i,o)=>{const l=j5[i];return l||(o===0?i.charAt(0).toUpperCase()+i.slice(1):i)}).join(" ")}function Tj(e){const n=new Set,r=[];for(const o of C5){const l=o.keys.filter(d=>e.has(d));l.forEach(d=>n.add(d)),l.length!==0&&r.push({id:o.id,title:o.title,summary:o.summary,advanced:!!o.advanced,keys:l})}const i=Array.from(e).filter(o=>!n.has(o)&&o!=="$schema").sort();return i.length>0&&r.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:i}),r}function E5(e,n){return Tj(e).map(r=>({id:r.id,title:r.title,advanced:r.advanced,total:r.keys.length,setCount:r.keys.filter(i=>n.has(i)).length}))}const N5={};function $j(e,n){if(n)return{text:n,authored:!1};const r=N5[e];return r?{text:r,authored:!0}:null}const T5={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},$5=["user","project","local","default"],A5={user:"user",project:"project",local:"local",default:"default"};function R5({node:e,targetScope:n,onOverride:r,schema:i}){const[o,l]=L.useState(""),[d,u]=L.useState(!1),[h,m]=L.useState(!0),x=e.kind==="object"?e:null,g=x?Object.keys(x.children):[],v=i.rootKeys(),S=new Set([...g,...v]),E=L.useMemo(()=>Tj(S),[Array.from(S).sort().join(",")]),j=L.useMemo(()=>E5(S,new Set(g)),[Array.from(S).sort().join(","),g.join(",")]),[y,b]=L.useState(null),_=N=>{const $=E.find(R=>R.id===N);$!=null&&$.advanced&&!d&&u(!0),b(N)};L.useEffect(()=>{if(!y)return;const N=document.getElementById(`settings-group-${y}`);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),b(null))});const C=L.useMemo(()=>E.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter($=>{const R=(x==null?void 0:x.children[$])!==void 0;if(!h&&!R)return!1;if(!o.trim())return!0;const O=i.at([$]);return[$,Nj($),(O==null?void 0:O.description)??""].join(" ").toLowerCase().includes(o.toLowerCase())})})).filter(N=>N.keys.length>0),[E,o,d,h,x,i]);return s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[s.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",s.jsx("span",{className:"text-fg-dim font-medium",children:os[n].label})]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:N=>m(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:N=>u(N.target.checked),className:"accent-accent"}),"show advanced"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:o,onChange:N=>l(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),s.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[s.jsx(M5,{groups:j,onJump:_}),s.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[C.map(N=>s.jsx(I5,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map($=>{const R=x==null?void 0:x.children[$],O=i.at([$]);return s.jsx(P5,{keyName:$,node:R,info:O,targetScope:n,onOverride:(I,z)=>r([$],I,z)},$)})},N.id)),C.length===0&&s.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',o,'"']})]})]})]})}function M5({groups:e,onJump:n}){return s.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:e.map(r=>s.jsxs("button",{onClick:()=>n(r.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${r.title}`,children:[s.jsx(dn,{name:T5[r.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:r.title}),s.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[r.setCount,"/",r.total]})]},r.id))})}function I5({id:e,title:n,summary:r,advanced:i,children:o}){const[l,d]=L.useState(!0);return s.jsxs("section",{id:`settings-group-${e}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[s.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>d(!l),children:[s.jsx("span",{className:"text-fg-faint w-3",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h2",{className:"text-fg text-base font-semibold",children:n}),i&&s.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),s.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:r})]})]}),l&&s.jsx("div",{className:"divide-y divide-line/60",children:o})]})}function P5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const[l,d]=L.useState(!1),[u,h]=L.useState(!1),m=Nj(e),x=n!==void 0,v=(n==null?void 0:n.kind)==="leaf"?n:null,S=(n==null?void 0:n.kind)==="object"||(n==null?void 0:n.kind)==="array",E=r==null?void 0:r.default,j=v&&E!==void 0&&Rj(v.value,E),y=H5({isSet:x,leafNode:v,defaultVal:E,isDefault:!!j,node:n}),b=D5(v,E),_=b.length>=2,C=!!v&&!j,N=$j(e,r==null?void 0:r.description);return s.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("button",{onClick:()=>d(!l),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:l?"collapse":"expand",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[s.jsx("h3",{className:"text-fg text-sm",children:m}),s.jsx(W5,{kind:y.kind,label:y.label}),_&&s.jsxs("button",{onClick:$=>{$.stopPropagation(),l||d(!0),h(R=>!R)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",b.map($=>A5[$]).join(" · ")]}),C&&v&&s.jsx("button",{onClick:$=>{$.stopPropagation(),o(void 0,v.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${os[v.winner].label}`,children:"↺ reset"}),(r==null?void 0:r.deprecated)&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(r==null?void 0:r.required)&&!x&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),N&&s.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${N.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:N.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:q5(N.text)}),l&&u&&v&&s.jsx(O5,{leaf:v,defaultVal:E,onReset:$=>o(void 0,$)}),l&&s.jsx(L5,{keyName:e,node:n,info:r,targetScope:i,onOverride:$=>o($)})]}),s.jsx("div",{className:"shrink-0",children:!l&&s.jsx(U5,{node:n,info:r,onSet:$=>{o($)},disabled:S&&x})})]})})}function D5(e,n){if(!e)return[];const r=new Set;r.add(e.winner);for(const i of e.shadowed)r.add(i.scope);return n!==void 0&&r.add("default"),$5.filter(i=>r.has(i))}function O5({leaf:e,defaultVal:n,onReset:r}){const i={};i[e.winner]={value:e.value,winner:!0};for(const o of e.shadowed)i[o.scope]={value:o.value,winner:!1};return s.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[s.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),s.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(o=>{const l=i[o],d=l!==void 0;return s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:os[o].label}),s.jsx("span",{className:`font-mono truncate ${l!=null&&l.winner?"text-accent":"text-fg-dim"}`,children:d?Vh(l.value):s.jsx("span",{className:"text-fg-faint",children:"—"})}),d?s.jsx("button",{onClick:()=>r(o),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${os[o].label}`,children:"↺"}):s.jsx("span",{})]},o)}),s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:"Default"}),s.jsx("span",{className:"font-mono text-fg-dim truncate",children:n!==void 0?Vh(n):s.jsx("span",{className:"text-fg-faint",children:"—"})}),s.jsx("span",{})]})]})]})}function L5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const d=(n==null?void 0:n.kind)==="leaf"?n:null,u=$j(e,r==null?void 0:r.description);return s.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[u&&s.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${u.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:u.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:u.text}),s.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(r==null?void 0:r.type)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Type"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(r.type)?r.type.join(" | "):r.type})]}),(r==null?void 0:r.default)!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Default"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Vh(r.default)})]}),(r==null?void 0:r.enum)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Options"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:r.enum.map(h=>String(h)).join(" | ")})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Current"}),s.jsxs("dd",{className:"font-mono",children:[s.jsx("span",{className:"text-fg-dim",children:Vh(d.value)}),s.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",os[d.winner].label]})]})]}),d&&d.shadowed.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Shadowed"}),s.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((h,m)=>s.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Vh(h.value)," —"," ",s.jsx("span",{className:"no-underline",children:os[h.scope].label})]},m))})]}),(n==null?void 0:n.kind)==="array"&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Accumulated"}),s.jsxs("dd",{className:"text-fg-dim",children:[n.items.length," items across all scopes"]})]})]}),s.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:s.jsx(z5,{keyName:e,node:n,info:r,onChange:o,targetScope:i})})]})}function z5({node:e,info:n,onChange:r,targetScope:i}){const l=(e==null?void 0:e.kind)==="leaf"?e.value:n==null?void 0:n.default,d=Aj(n==null?void 0:n.type);if(d==="boolean"){const u=l===!0;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:h,label:m})=>s.jsx("button",{onClick:()=>r(h),className:`px-3 py-0.5 text-xs transition-colors ${u===h?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:m},m))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]})}return n!=null&&n.enum?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-fg-faint",children:"Choose:"}),n.enum.map(u=>{const h=Rj(l,u);return s.jsx("button",{onClick:()=>r(u),className:`px-2 py-0.5 text-xs rounded border ${h?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(u)},String(u))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]}):d==="integer"||d==="number"?s.jsx(B5,{value:typeof l=="number"?l:void 0,integer:d==="integer",onCommit:r,target:os[i].label}):d==="string"?s.jsx(F5,{value:typeof l=="string"?l:"",onCommit:r,target:os[i].label}):s.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",s.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function B5({value:e,integer:n,onCommit:r,target:i}){const[o,l]=L.useState(e!==void 0?String(e):""),d=()=>{const u=n?parseInt(o,10):parseFloat(o);Number.isNaN(u)||r(u)};return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("input",{type:"number",value:o,onChange:u=>l(u.target.value),onBlur:d,onKeyDown:u=>{u.key==="Enter"&&u.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:d,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",i]})]})}function F5({value:e,onCommit:n,target:r}){const[i,o]=L.useState(e);return s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[s.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),s.jsx("input",{type:"text",value:i,onChange:l=>o(l.target.value),onKeyDown:l=>{l.key==="Enter"&&n(i)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:()=>n(i),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function U5({node:e,info:n,onSet:r,disabled:i}){const o=(e==null?void 0:e.kind)==="leaf",l=Aj(n==null?void 0:n.type);if(i)return null;if(l==="boolean"){const d=o&&e.value===!0;return s.jsx("button",{onClick:()=>r(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:d?"on":"off"})}return null}function H5({isSet:e,leafNode:n,defaultVal:r,isDefault:i,node:o}){return e?(o==null?void 0:o.kind)==="array"?{kind:"accumulated",label:`${o.items.length} items`}:(o==null?void 0:o.kind)==="object"?{kind:"set",label:"configured"}:n?i?{kind:"default",label:`= default · ${os[n.winner].label}`}:n.shadowed.length>0?{kind:"override",label:`overriding ${n.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${os[n.winner].label}`}:{kind:"set",label:"configured"}:r!==void 0?{kind:"default",label:`using default: ${Vh(r)}`}:{kind:"unset",label:"not configured"}}function W5({kind:e,label:n}){const r={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[e];return s.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${r}`,children:n})}function Aj(e){if(e)return Array.isArray(e)?e.find(r=>r!=="null")??e[0]:e}function Rj(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function q5(e){const n=e.trim().split(`
|
|
3394
3394
|
`)[0],r=n.match(/^([^.!?]+[.!?])/);return r?r[1]:n.length>120?n.slice(0,120)+"…":n}function Vh(e){if(typeof e=="string")return e===""?'""':JSON.stringify(e);if(e===null)return"null";if(e===void 0)return"—";if(typeof e=="object"){const n=JSON.stringify(e);return n.length>60?n.slice(0,60)+"…":n}return String(e)}function w0(e,n,r){const i=tn(h=>h.files),o=tn(h=>h.loadJson),l=tn(h=>h.watchFile),d=tn(h=>h.unwatchFile),u=L.useMemo(()=>{const h={};for(const m of e.scopes){const x=e.resolve(m,n??"",r);x&&(h[m]=x)}return h},[e,n,r]);return L.useEffect(()=>{const h=Object.values(u).filter(Boolean);return h.forEach(m=>{i[m]||o(m),l(m)}),()=>{h.forEach(m=>d(m))}},[JSON.stringify(u)]),u}const V5=[];function Mx(e){return Array.isArray(e)?"array":e!==null&&typeof e=="object"?"object":"scalar"}function _0(e){const n=e.filter(r=>r.data!==void 0);return n.length===0?{kind:"object",children:{}}:Mj(n,[])}function Mj(e,n){const r=V5.includes(n.join(".")),i=e.every(x=>Mx(x.data)==="object"),o=e.every(x=>Mx(x.data)==="array");if(i){const x=new Set;for(const v of e)for(const S of Object.keys(v.data))x.add(S);const g={};for(const v of x){const S=e.filter(E=>v in E.data).map(E=>({scope:E.scope,data:E.data[v]}));g[v]=Mj(S,[...n,v])}return{kind:"object",children:g}}if(o&&!r){const x=[];for(const g of[...e].reverse())for(const v of g.data)x.push({value:v,fromScope:g.scope,index:x.length});return{kind:"array",items:x}}const l=[...e].reverse(),d=l[0],u=l.slice(1).map(x=>({scope:x.scope,value:x.data})),h=Mx(d.data),m=u.some(x=>Mx(x.value)!==h);return{kind:"leaf",value:d.data,winner:d.scope,shadowed:u,...m?{typeMismatch:!0}:{}}}function k0(e,n){if(n.length===0)return e;if(e.kind!=="object")return null;const[r,...i]=n,o=e.children[r];return o?k0(o,i):null}function iv(e,n,r){if(n.length===0)return r;const[i,...o]=n,l=e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{};return l[i]=iv(l[i],o,r),l}const G5=["user","project","local"];function S0(e,n){const r=[];for(const i of G5){const o=n[i];if(!o)continue;const l=e[o];if(!l||!l.exists)continue;const d=l.draftRaw??"";if(d.trim())try{r.push({scope:i,data:JSON.parse(d)})}catch{}}return r}const K5="http://json-schema.org/draft-07/schema#",X5="https://json.schemastore.org/claude-code-settings.json",Y5={permissionRule:{type:"string",description:`Tool permission rule.
|
|
3395
3395
|
See https://code.claude.com/docs/en/settings#permission-rule-syntax
|
|
3396
3396
|
See https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.`,pattern:"^((Agent|Bash|Edit|ExitPlanMode|Glob|Grep|KillShell|LSP|NotebookEdit|Read|Skill|TaskCreate|TaskGet|TaskList|TaskOutput|TaskStop|TaskUpdate|TodoWrite|ToolSearch|WebFetch|WebSearch|Write)(\\((?=.*[^)*?])[^)]+\\))?|mcp__.*)$",examples:["Bash","Bash(npm run build)","Bash(git commit *)","Bash(npm run *)","Bash(ls*)","Bash(git * main)","Edit","Edit(/src/**/*.ts)","Read(./.env)","Read(./secrets/**)","Read(//Users/alice/secrets/**)","Read(~/Documents/*.pdf)","Agent(Explore)","WebFetch","WebFetch(domain:example.com)","mcp__puppeteer","mcp__github__search_repositories"]},hookCommand:{anyOf:[{type:"object",description:"Bash command hook",additionalProperties:!1,required:["type","command"],properties:{type:{type:"string",description:"Hook type",const:"command"},command:{type:"string",description:"Shell command to execute",minLength:1},timeout:{type:"number",description:"Optional timeout in seconds",exclusiveMinimum:0},async:{type:"boolean",description:"Run this hook asynchronously without blocking Claude Code"},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"LLM prompt hook. See https://code.claude.com/docs/en/hooks#prompt-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"prompt"},prompt:{type:"string",description:"Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"Agent hook with multi-turn tool access for verification. See https://code.claude.com/docs/en/hooks#agent-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"agent"},prompt:{type:"string",description:"Prompt describing what to verify. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 60)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"HTTP webhook hook. POST JSON to a URL and receive JSON response. See https://code.claude.com/docs/en/hooks#http-hooks",additionalProperties:!1,required:["type","url"],properties:{type:{type:"string",description:"Hook type",const:"http"},url:{type:"string",description:"URL to POST hook input JSON to. Endpoint must accept POST requests and return JSON.",minLength:1},headers:{type:"object",additionalProperties:{type:"string"},description:"Custom HTTP headers (e.g., Authorization: Bearer token). Values support $VAR_NAME or ${VAR_NAME} interpolation."},allowedEnvVars:{type:"array",items:{type:"string",minLength:1},description:"List of environment variable names permitted for interpolation in headers. If not set, no env var interpolation is allowed."},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}}]},hookMatcher:{type:"object",description:"Hook matcher configuration with multiple hooks",additionalProperties:!1,required:["hooks"],properties:{matcher:{type:"string",description:"Optional pattern to match event contexts, case-sensitive. Behavior depends on event type. See https://code.claude.com/docs/en/hooks#matcher-patterns for event-specific details and examples"},hooks:{type:"array",description:"Array of hooks to execute",items:{$ref:"#/$defs/hookCommand"}}}}},J5="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",Q5=!0,Z5=!0,eL="object",tL=JSON.parse(`{"$schema":{"type":"string","description":"JSON Schema reference for Claude Code settings"},"apiKeyHelper":{"type":"string","description":"Path to a script that outputs authentication values","examples":["/bin/generate_temp_api_key.sh"],"minLength":1},"autoMemoryEnabled":{"type":"boolean","description":"Enable automatic memory saves that capture useful context to .claude/memory/. Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#auto-memory","default":true},"autoUpdatesChannel":{"type":"string","enum":["stable","latest"],"description":"Release channel to follow for updates. Use \\"stable\\" for a version that is typically about one week old and skips versions with major regressions, or \\"latest\\" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable updates entirely.","default":"latest"},"awsCredentialExport":{"type":"string","description":"Path to a script that exports AWS credentials","examples":["/bin/generate_aws_grant.sh"],"minLength":1},"awsAuthRefresh":{"type":"string","description":"Path to a script that refreshes AWS authentication","examples":["aws sso login --profile myprofile"],"minLength":1},"claudeMdExcludes":{"type":"array","items":{"type":"string","minLength":1},"description":"Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claudemd-files","examples":[["**/monorepo/CLAUDE.md","/home/user/monorepo/other-team/.claude/rules/**"]]},"cleanupPeriodDays":{"type":"integer","minimum":0,"description":"Number of days to retain chat transcripts (0 to disable cleanup)","examples":[20,30,60],"default":30},"env":{"type":"object","additionalProperties":false,"description":"Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.\\nUNDOCUMENTED: CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS (plugin marketplace git timeout in ms, default 120000, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2151).\\nUNDOCUMENTED: ENABLE_CLAUDEAI_MCP_SERVERS (set to false to opt out of claude.ai MCP servers, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2163).","examples":[{"ANTHROPIC_MODEL":"claude-opus-4-1","ANTHROPIC_SMALL_FAST_MODEL":"claude-3-5-haiku-latest"}],"default":{},"patternProperties":{"^[A-Z_][A-Z0-9_]*$":{"type":"string","description":"Environment variable value"}}},"attribution":{"type":"object","description":"Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings","additionalProperties":false,"properties":{"commit":{"type":"string","description":"Attribution for git commits, including any trailers. Empty string hides commit attribution"},"pr":{"type":"string","description":"Attribution for pull request descriptions. Empty string hides pull request attribution"}}},"includeGitInstructions":{"type":"boolean","description":"Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings","default":true},"includeCoAuthoredBy":{"type":"boolean","description":"DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)","default":true},"plansDirectory":{"type":"string","description":"Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)","default":"~/.claude/plans","examples":["./plans"]},"respectGitignore":{"type":"boolean","description":"Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions","default":true},"permissions":{"type":"object","properties":{"allow":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for allowed operations","uniqueItems":true},"deny":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for denied operations","uniqueItems":true},"ask":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules that should always prompt for confirmation","uniqueItems":true},"defaultMode":{"type":"string","enum":["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"],"description":"Default permission mode.\\n\\"default\\": prompts on first use.\\n\\"acceptEdits\\": auto-accepts file edits.\\n\\"plan\\": read-only, no modifications.\\nUNDOCUMENTED. \\"delegate\\": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS).\\n\\"dontAsk\\": auto-denies unless pre-approved via permissions.\\n\\"bypassPermissions\\": skips all prompts (use only in isolated environments).\\nSee https://code.claude.com/docs/en/permissions"},"disableBypassPermissionsMode":{"type":"string","enum":["disable"],"description":"Disable the ability to bypass permission prompts"},"additionalDirectories":{"type":"array","items":{"type":"string","minLength":1},"description":"Additional directories to include in the permission scope","examples":[["//Users/alice/Documents","~/projects"]],"uniqueItems":true}},"additionalProperties":false,"description":"Tool usage permissions configuration.\\nSee https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings\\nSee https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.","examples":[{"allow":["Bash(git add:*)"],"ask":["Bash(gh pr create:*)","Bash(git commit:*)"],"deny":["Read(*.env)","Bash(rm:*)","Bash(curl:*)"],"defaultMode":"default"}]},"language":{"type":"string","description":"Preferred language for Claude's responses","examples":["japanese","spanish","french"]},"model":{"type":"string","enum":["opus","sonnet","haiku","default"],"description":"Override the default model used by Claude Code. Accepts a short alias (opus|sonnet|haiku) or a full model ID. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config"},"availableModels":{"type":"array","items":{"type":"string"},"description":"Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection","examples":[["sonnet","haiku"]]},"modelOverrides":{"type":"object","additionalProperties":{"type":"string"},"description":"Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version","examples":[{"claude-opus-4-6":"arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"}]},"effortLevel":{"type":"string","enum":["low","medium","high"],"description":"Control Opus 4.6 adaptive reasoning effort. Lower effort is faster and cheaper for straightforward tasks, higher effort provides deeper reasoning. Defaults vary by model and plan (Opus 4.6 defaults to medium for Max and Team subscribers). Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level"},"fastMode":{"type":"boolean","description":"Enable fast mode for Opus 4.6 (research preview). Fast mode uses the same model with 2.5x faster output at higher per-token cost. Requires extra usage enabled. Alternatively, toggle with /fast command. See https://code.claude.com/docs/en/fast-mode","default":false},"fastModePerSessionOptIn":{"type":"boolean","description":"Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode","default":false},"feedbackSurveyRate":{"type":"number","minimum":0,"maximum":1,"description":"Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings","examples":[0.05]},"editorMode":{"type":"string","enum":["normal","vim"],"default":"normal","description":"Editor input mode for the Claude Code terminal prompt. 'vim' enables modal editing (Esc for normal mode, i for insert). See https://code.claude.com/docs/en/settings"},"skillOverrides":{"type":"object","additionalProperties":{"type":"string","enum":["on","name-only","user-invocable-only","off"]},"description":"Per-skill availability override map. Keys are skill names; values are one of 'on' (default), 'name-only' (skill name listed but not auto-loaded), 'user-invocable-only' (load only when user explicitly invokes), or 'off' (hidden). Requires Claude Code v2.1.129+. See https://code.claude.com/docs/en/settings","examples":[{"playwright-debug":"user-invocable-only","init":"off"}]},"disableAgentView":{"type":"boolean","default":false,"description":"Disable the Agent View feature (read-only inspection of sub-agent activity). Useful when administering managed deployments. Requires Claude Code v2.1.139+. See https://code.claude.com/docs/en/settings"},"disableRemoteControl":{"type":"boolean","default":false,"description":"Block the \`claude remote-control\` channel that allows external clients to drive this Claude Code instance. Recommended default for shared/CI environments. Requires Claude Code v2.1.128+. See https://code.claude.com/docs/en/settings"},"enableAllProjectMcpServers":{"type":"boolean","description":"Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp","examples":[true]},"enabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["memory","github"]]},"disabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["filesystem"]]},"allowedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that users are allowed to configure"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"deniedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that is explicitly blocked"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"httpHookAllowedEnvVars":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["MY_TOKEN","HOOK_SECRET"]]},"hooks":{"type":"object","additionalProperties":false,"description":"Custom commands to run before/after tool executions. See https://code.claude.com/docs/en/hooks","examples":[{"PostToolUse":[{"matcher":"Edit|Write","hooks":[{"type":"command","command":"prettier --write","timeout":5}]}]}],"properties":{"PreToolUse":{"type":"array","description":"Hooks that run before tool calls","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUse":{"type":"array","description":"Hooks that run after tool completion","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUseFailure":{"type":"array","description":"Hooks that run after a tool fails","items":{"$ref":"#/$defs/hookMatcher"}},"PermissionRequest":{"type":"array","description":"Hooks that run when a permission dialog appears","items":{"$ref":"#/$defs/hookMatcher"}},"Notification":{"type":"array","description":"Hooks that trigger on notifications","items":{"$ref":"#/$defs/hookMatcher"}},"UserPromptSubmit":{"type":"array","description":"Hooks that run when a user submits a prompt","items":{"$ref":"#/$defs/hookMatcher"}},"Stop":{"type":"array","description":"Hooks that run when agents finish responding. Does not run on user interrupt","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStart":{"type":"array","description":"Hooks that run when a subagent is spawned","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStop":{"type":"array","description":"Hooks that run when subagents finish responding","items":{"$ref":"#/$defs/hookMatcher"}},"PreCompact":{"type":"array","description":"Hooks that run before the context is compacted","items":{"$ref":"#/$defs/hookMatcher"}},"PostCompact":{"type":"array","description":"Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"Elicitation":{"type":"array","description":"Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"ElicitationResult":{"type":"array","description":"Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"TeammateIdle":{"type":"array","description":"Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle","items":{"$ref":"#/$defs/hookMatcher"}},"TaskCompleted":{"type":"array","description":"Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted","items":{"$ref":"#/$defs/hookMatcher"}},"Setup":{"type":"array","description":"UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)","items":{"$ref":"#/$defs/hookMatcher"}},"InstructionsLoaded":{"type":"array","description":"Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded","items":{"$ref":"#/$defs/hookMatcher"}},"ConfigChange":{"type":"array","description":"Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeCreate":{"type":"array","description":"Hooks that run when a worktree is created via --worktree or isolation: \\"worktree\\" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeRemove":{"type":"array","description":"Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove","items":{"$ref":"#/$defs/hookMatcher"}},"SessionStart":{"type":"array","description":"Hooks that run when a new session starts","items":{"$ref":"#/$defs/hookMatcher"}},"SessionEnd":{"type":"array","description":"Hooks that run when a session ends","items":{"$ref":"#/$defs/hookMatcher"}}}},"disableAllHooks":{"type":"boolean","description":"Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks"},"allowedHttpHookUrls":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["https://hooks.example.com/*","http://localhost:*"]]},"allowManagedHooksOnly":{"type":"boolean","description":"(Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration"},"allowManagedPermissionRulesOnly":{"type":"boolean","description":"(Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings"},"statusLine":{"type":"object","properties":{"type":{"type":"string","description":"The type of status line handler; must be set to \\"command\\" to run a custom shell script that receives JSON session data via stdin.","const":"command"},"command":{"type":"string","description":"A shell command or path to a script that displays session information (context usage, costs, git status, etc.) by reading JSON data from stdin and writing output to stdout. See https://code.claude.com/docs/en/statusline"},"padding":{"type":"number","description":"Optional number of extra horizontal spacing characters added to the status line content; defaults to 0."}},"required":["type","command"],"additionalProperties":false,"description":"Custom status line display configuration. See https://code.claude.com/docs/en/statusline","examples":[{"type":"command","command":"~/.claude/statusline.sh"}]},"fileSuggestion":{"type":"object","properties":{"type":{"type":"string","description":"The type of file suggestion handler; must be set to \\"command\\" to execute a custom shell script that generates file suggestions for the @ file picker.","const":"command"},"command":{"type":"string","description":"Shell command to execute for file suggestions"}},"required":["type","command"],"additionalProperties":false,"description":"Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings","examples":[{"type":"command","command":"~/.claude/file-suggestion.sh"}]},"enabledPlugins":{"type":"object","additionalProperties":{"anyOf":[{"type":"array","items":{"type":"string"}},{"type":"boolean"},{"not":{}}]},"description":"Enabled plugins using plugin-id@marketplace-id format. Example: { \\"formatter@anthropic-tools\\": true }. See https://code.claude.com/docs/en/plugins"},"extraKnownMarketplaces":{"type":"object","additionalProperties":{"type":"object","properties":{"source":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","pattern":"\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false}],"description":"Where to fetch the marketplace from"},"installLocation":{"type":"string","description":"Local cache path where marketplace manifest is stored (auto-generated if not provided)"}},"required":["source"],"additionalProperties":false},"description":"Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces"},"strictKnownMarketplaces":{"type":"array","description":"(Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/settings#strictknownmarketplaces","items":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"HTTP headers for authenticated access"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package name (supports scoped packages)"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Absolute path to marketplace.json file"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Absolute path to directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"pathPattern"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"],"additionalProperties":false}]},"examples":[[{"source":"github","repo":"acme-corp/approved-plugins"},{"source":"npm","package":"@acme-corp/compliance-plugins"}]]},"skippedMarketplaces":{"type":"array","items":{"type":"string","minLength":1},"description":"List of marketplace names the user has chosen not to install when prompted"},"skippedPlugins":{"type":"array","items":{"type":"string","minLength":1},"description":"List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted"},"forceLoginMethod":{"type":"string","enum":["claudeai","console"],"description":"Force a specific login method: \\"claudeai\\" for Claude Pro/Max, \\"console\\" for Console billing","examples":["claudeai"]},"forceLoginOrgUUID":{"type":"string","description":"Organization UUID to use for OAuth login","examples":["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"],"minLength":1},"otelHeadersHelper":{"type":"string","description":"Path to a script that outputs OpenTelemetry headers","minLength":1},"outputStyle":{"type":"string","description":"Controls the output style for assistant responses. Built-in styles: default, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles","examples":["default","Explanatory","Learning"],"minLength":1},"skipWebFetchPreflight":{"type":"boolean","description":"Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"},"sandbox":{"type":"object","description":"Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing","properties":{"network":{"type":"object","description":"Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.","properties":{"allowUnixSockets":{"type":"array","items":{"type":"string"},"description":"Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified"},"allowLocalBinding":{"type":"boolean","description":"Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified"},"httpProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"socksProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"allowAllUnixSockets":{"type":"boolean","description":"Allow all Unix domain socket connections. If true, this overrides allowUnixSockets"},"allowedDomains":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com"},"allowManagedDomainsOnly":{"type":"boolean","description":"(Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts."}},"additionalProperties":false},"ignoreViolations":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"},"description":"List of filesystem paths to ignore sandbox violations for when this command pattern matches"},"description":"Map of command patterns to filesystem paths to ignore violations for. Use \\"*\\" to match all commands"},"excludedCommands":{"type":"array","items":{"type":"string"},"description":"Commands that should never run in the sandbox (e.g., [\\"git\\", \\"docker\\"])"},"autoAllowBashIfSandboxed":{"type":"boolean","description":"Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed.","default":true},"enableWeakerNetworkIsolation":{"type":"boolean","description":"macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/settings#sandbox-settings","default":false},"enableWeakerNestedSandbox":{"type":"boolean","description":"Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable.Default: false (secure)."},"allowUnsandboxedCommands":{"type":"boolean","description":"Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."},"enabled":{"type":"boolean","description":"Enable sandboxed bash"},"filesystem":{"type":"object","description":"Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation","properties":{"allowWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path)"},"denyWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite"},"denyRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied read access"},"allowRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths"},"allowManagedReadPathsOnly":{"type":"boolean","description":"When true (managed settings only), only allowRead paths from managed settings are used"}},"additionalProperties":false}},"additionalProperties":false},"spinnerVerbs":{"type":"object","description":"Customize the verbs shown in spinner progress messages","properties":{"mode":{"type":"string","enum":["append","replace"],"description":"How to combine custom verbs with default spinner verbs: 'append' adds custom verbs to the default list, 'replace' uses only custom verbs"},"verbs":{"type":"array","items":{"type":"string","minLength":1},"minItems":1,"description":"Custom verbs used in spinner progress text"}},"required":["verbs"],"additionalProperties":false},"spinnerTipsEnabled":{"type":"boolean","description":"Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)","default":true},"spinnerTipsOverride":{"type":"object","description":"Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings","properties":{"excludeDefault":{"type":"boolean","description":"If true, only show custom tips. If false or absent, custom tips merge with built-in tips","default":false},"tips":{"type":"array","items":{"type":"string","minLength":1},"description":"Custom tip strings to display in the spinner","minItems":1}},"required":["tips"],"additionalProperties":false},"terminalProgressBarEnabled":{"type":"boolean","description":"Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)","default":true},"showTurnDuration":{"type":"boolean","description":"Show turn duration messages after responses (e.g., \\"Cooked for 1m 6s\\"). Set to false to hide these messages (default: true)","default":true},"prefersReducedMotion":{"type":"boolean","description":"Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility","default":false},"alwaysThinkingEnabled":{"type":"boolean","description":"Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode"},"companyAnnouncements":{"type":"array","items":{"type":"string","minLength":1},"description":"Company announcements to display at startup (one will be randomly selected if multiple are provided)"},"teammateMode":{"type":"string","enum":["auto","in-process","tmux"],"description":"How agent team teammates display: \\"auto\\" picks split panes in tmux or iTerm2, in-process otherwise. Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams","default":"auto"},"worktree":{"type":"object","additionalProperties":false,"description":"Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings","properties":{"sparsePaths":{"type":"array","items":{"type":"string","minLength":1},"description":"Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos.","examples":[["packages/my-app","shared/utils"]]}}},"pluginTrustMessage":{"type":"string","description":"(Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings","minLength":1},"pluginConfigs":{"type":"object","additionalProperties":{"type":"object","properties":{"mcpServers":{"type":"object","additionalProperties":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"array","items":{"type":"string"}}]}},"description":"User configuration values for MCP servers keyed by server name"}},"additionalProperties":false},"description":"Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins"},"allowManagedMcpServersOnly":{"type":"boolean","description":"(Managed settings only) Only allowedMcpServers from managed settings are respected. deniedMcpServers still merges from all sources. Users can still add their own MCP servers, but only the admin-defined allowlist applies."},"blockedMarketplaces":{"type":"array","description":"(Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"url","description":"Block marketplace fetched from direct URL"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"Custom HTTP headers (e.g., for authentication)"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"github","description":"Block marketplace from GitHub repository"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","repo"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"git","description":"Block marketplace from git repository URL"},"url":{"type":"string","pattern":".*\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"npm","description":"Block marketplace from NPM package"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"file","description":"Block marketplace from local file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"directory","description":"Block marketplace from local directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"hostPattern","description":"Block marketplace by host pattern matching"},"hostPattern":{"type":"string","description":"Regex pattern to match the host/domain extracted from any marketplace source type"}},"required":["source","hostPattern"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"pathPattern","description":"Block marketplace by file/directory path pattern matching"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"]}]}}}`),nL="Claude Code Settings",rL={$schema:K5,$id:X5,$defs:Y5,description:J5,allowTrailingCommas:Q5,additionalProperties:Z5,type:eL,properties:tL,title:nL};function sL(e){const n=e??{},r={...n.$defs??{},...n.definitions??{}},i=S=>{if(!S)return{};if(!S.$ref)return d(S);const E=/^#\/(\$defs|definitions)\/(.+)$/.exec(S.$ref);if(!E)return d(S);const j=r[E[2]];return j?i({...j,...u(S)}):d(S)},o=new Set(["__proto__","constructor","prototype"]),l=S=>{if(!S)return{};const E={};for(const[j,y]of Object.entries(S))o.has(j)||(E[j]=y);return E},d=S=>{if(!S.allOf||S.allOf.length===0)return S;const E={...S};delete E.allOf;for(const j of S.allOf){const y=i(j);Object.assign(E,{properties:{...l(E.properties),...l(y.properties)},required:iL([...E.required??[],...y.required??[]])}),!E.description&&y.description&&(E.description=y.description),E.default===void 0&&y.default!==void 0&&(E.default=y.default),!E.type&&y.type&&(E.type=y.type)}return E},u=S=>{const{$ref:E,...j}=S;return j},h=(S,E)=>{let j=i(S);for(const y of E){if(!j)return null;if(/^\d+$/.test(y)){const C=Array.isArray(j.items)?j.items[Number(y)]:j.items;j=C?i(C):null;continue}const b=j.properties;if(b&&!o.has(y)&&y in b){j=i(b[y]);continue}const _=j.additionalProperties;if(_&&typeof _=="object"){j=i(_);continue}return null}return j},m=(S,E,j)=>{if(!S)return null;const y={};if(S.description&&(y.description=S.description),S.type&&(y.type=S.type),S.default!==void 0&&(y.default=S.default),S.enum&&(y.enum=S.enum),S.const!==void 0&&(y.const=S.const),S.deprecated&&(y.deprecated=!0),S.examples&&(y.examples=S.examples),S.properties&&(y.knownChildren=Object.keys(S.properties)),j&&(E!=null&&E.includes(j))&&(y.required=!0),S.items&&!Array.isArray(S.items)){const b=i(S.items),_=m(b,void 0,null);_&&(y.itemsInfo=_)}return(S.additionalProperties===!0||typeof S.additionalProperties=="object")&&(y.open=!0),y},x=S=>E=>{if(E.length===0)return m(i(S),void 0,null);const j=h(S,E.slice(0,-1));if(!j)return null;const y=E[E.length-1],b=h(j,[y]);return m(b,j.required,y)},g=S=>{const E=i(S);return Object.keys(E.properties??{})},v=S=>({at:x(S),rootKeys:()=>g(S),rootedAt:E=>{const j=h(S,E);return v(j??{})}});return v(n)}function iL(e){return Array.from(new Set(e))}let db=null;function Ay(){return db||(db=sL(rL)),db}function oL(){const[e,n]=L.useState(null),[r,i]=L.useState(null),[o,l]=L.useState(null),[d,u]=L.useState(null),[h,m]=L.useState(!1),[x,g]=L.useState(null),[v,S]=L.useState(null);if(L.useEffect(()=>{let _=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([C,N,$])=>{_||(n(C),l(C),i(N),u($))}).catch(C=>{console.warn("[telemetry] load failed:",C==null?void 0:C.message)}),()=>{_=!0}},[]),!o||!e)return s.jsx(Vt,{title:"loading…"});const E=JSON.stringify(o)!==JSON.stringify(e),j=(_,C)=>{g(null),l({...o,[_]:C})},y=async()=>{m(!0),g(null);try{const _=await window.api.otel.setConfig(o);!_.ok&&_.error&&g(_.error),n(_.config),l(_.config),i(_.status),S(Date.now())}catch(_){g(_ instanceof Error?_.message:String(_))}finally{m(!1)}},b=()=>{g(null),l(e)};return s.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[s.jsxs("header",{className:"space-y-1",children:[s.jsx("h2",{className:"text-fg text-base font-medium",children:"Telemetry — OpenTelemetry export"}),s.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"When enabled, every classified transcript event (tool_use, todo_write, plan, usage, agent_spawn) is mirrored as a 0-duration OTLP/HTTP span. Point this at a local collector (Jaeger, Grafana Tempo, SigNoz, Honeycomb) for cross-session analysis."}),d&&s.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",s.jsx("span",{className:"font-mono",children:d})]})]}),s.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-fg",children:"Export transcripts to OTEL"}),s.jsx("div",{className:"text-fg-faint text-xs",children:"Toggle off to disable all span emission immediately."})]}),s.jsx(Cy,{checked:o.enabled,onChange:_=>j("enabled",_),label:o.enabled?"on":"off"})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-fg-dim text-xs",children:"OTLP/HTTP traces endpoint"}),s.jsx("input",{type:"text",value:o.endpoint,onChange:_=>j("endpoint",_.target.value),placeholder:"http://localhost:4318/v1/traces",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsxs("span",{className:"text-fg-dim text-xs",children:["Headers (newline-separated ",s.jsx("span",{className:"font-mono",children:"Key: Value"}),")"]}),s.jsx("textarea",{value:o.headers,onChange:_=>j("headers",_.target.value),placeholder:"x-honeycomb-team: YOUR_API_KEY",rows:3,className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-fg-dim text-xs",children:"Service name"}),s.jsx("input",{type:"text",value:o.serviceName,onChange:_=>j("serviceName",_.target.value),placeholder:"session-manager",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),s.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-fg",children:"Include content (PII)"}),s.jsxs("div",{className:"text-fg-faint text-xs leading-relaxed",children:["Adds tool inputs, plan text, and agent prompts to span attributes. Off by default — matches upstream Claude Code's ",s.jsx("span",{className:"font-mono",children:"OTEL_LOG_USER_PROMPTS"})," opt-in."]})]}),s.jsx(Cy,{checked:o.includeContent,onChange:_=>j("includeContent",_),label:o.includeContent?"on":"off"})]})]}),r&&s.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1",children:[s.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-fg-faint",children:"enabled:"})," ",s.jsx("span",{className:r.enabled?"text-accent":"text-fg-dim",children:String(r.enabled)})]}),r.error&&s.jsxs("div",{className:"text-red-400 break-words",children:[s.jsx("span",{className:"text-fg-faint",children:"error:"})," ",r.error]}),!r.error&&r.enabled&&s.jsx("div",{className:"text-fg-faint",children:"spans batched and exported in the background. Verify by enabling and pointing at a local Jaeger."})]}),s.jsxs("footer",{className:"flex items-center gap-3 pt-2 border-t border-line",children:[s.jsx("button",{onClick:y,disabled:!E||h,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:h?"saving…":"Save"}),s.jsx("button",{onClick:b,disabled:!E||h,className:"px-3 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert"}),x&&s.jsx("span",{className:"text-red-400 text-xs",children:x}),!x&&v&&!E&&s.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function aL(){const{model:e,setModel:n}=FN();return s.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[s.jsxs("header",{className:"space-y-1",children:[s.jsx("h2",{className:"text-fg text-base font-medium",children:"Session Manager preferences"}),s.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"Native app preferences, stored locally — not part of Claude Code's own settings."})]}),s.jsx("section",{className:"border border-line rounded p-3 space-y-3",children:s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-fg-dim text-xs",children:"Default model for raw sessions"}),s.jsx("select",{value:e,onChange:r=>n(r.target.value),className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs",children:Yw.map(r=>s.jsx("option",{value:r,children:r.charAt(0).toUpperCase()+r.slice(1)},r))}),s.jsx("span",{className:"text-fg-faint text-[11px]",children:"Used when opening a raw interactive session without an explicit per-launch override."})]})})]})}function lL(){const e=rr(),n=vt($=>$.tabs),r=vt($=>$.activeTabId),i=n.find($=>$.id===r)??null,o=(i==null?void 0:i.cwd)??null,[l,d]=L.useState("user"),[u,h]=L.useState("effective"),m=w0(Sy,e,o),x=m[l]??null,g=tn($=>$.files),v=tn($=>$.setDraft),S=tn($=>$.saveJson),E=tn($=>$.revert),[j,y]=L.useState(null),b=L.useMemo(()=>_0(S0(g,m)),[g,m]),_=($,R,O)=>{var V;const z=m[O??l];if(!z)return;y(null);const U=((V=g[z])==null?void 0:V.draftRaw)??"";let W={};if(U.trim())try{W=JSON.parse(U)}catch{W={}}const Y=iv(W,$,R);v(z,JSON.stringify(Y,null,2)+`
|