claude-code-session-manager 0.57.0 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-B1llI4h-.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-CJDxVF7X.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
2
2
  var b$=Object.defineProperty;var y$=(n,e,i)=>e in n?b$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var qn=(n,e,i)=>y$(n,typeof e!="symbol"?e+"":e,i);import{_ as rv}from"./monaco-editor-BW5C4Iv1.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const d of a.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(s){if(s.ep)return;s.ep=!0;const a=i(s);fetch(s.href,a)}})();function wy(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var nw={exports:{}},Mm={},iw={exports:{}},yn={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -44,7 +44,7 @@ Error generating stack: `+X.message+`
44
44
 
45
45
  ${s}`,c={...a,goalText:l},h={...e().sessions,[i]:c};n({sessions:h}),await ou(a.cwd,h,e().events)},duplicateEpic:(i,r)=>{const s=e().sessions[i];if(!s)throw new Error(`duplicateEpic: no PromptSession with id "${i}"`);const a=r??"unknown",d=e().createPromptSession(s.cwd,s.goalText,s.tag,a),l=e().approveProposed(d.id,a)??d;return bp("epic_duplicate",{cwd:s.cwd,epicId:l.id,source:a}),l},deleteEpic:async(i,r)=>{var h;const s=e().sessions[i];if(!s)throw new Error(`deleteEpic: no PromptSession with id "${i}"`);if((((h=to.getState().snapshot)==null?void 0:h.jobs)??[]).some(m=>(m.status==="running"||m.status==="pending")&&Fj(m).includes(i)))throw new Error("deleteEpic: this Epic has a running or queued scheduler job — cancel it first");const d=Tn.getState().chats[i];if(d&&(d.running||d.queuedPosition>0))throw new Error("deleteEpic: this Epic has a chat run in flight — wait for it to finish first");if(Wl.getState().isAttached(i))throw new Error("deleteEpic: this Epic has a live Terminal session attached — detach it first");const l={...e().sessions},c={...e().events};delete l[i],delete c[i],n({sessions:l,events:c}),await ou(s.cwd,l,c,[i]),bp("epic_delete",{cwd:s.cwd,epicId:i,source:r??"unknown"})},hydrate:async i=>{var r,s,a,d;if(!(typeof window>"u"||!((s=(r=window.api)==null?void 0:r.config)!=null&&s.readJson)))try{const l=X0(i),c=await window.api.config.readJson(l),h=c.exists&&c.data?c.data:{},m=h.sessions??{},f=h.events??{},b=e().sessions,_=Object.keys(m).filter(S=>!b[S]),y=Q$(l)?[]:Object.keys(b).filter(S=>b[S].cwd===i&&(b[S].status==="active"||b[S].status==="proposed")&&!m[S]),k={...b},x={...e().events};let w=!1;for(const S of _)k[S]=m[S],x[S]=f[S]??[],w=!0;for(const S of y)delete k[S],delete x[S],w=!0;for(const S of Object.keys(f)){if(!b[S]||_.includes(S))continue;const C=f[S]??[],T=x[S]??[],N=new Set(T.map(P=>P.id)),A=C.filter(P=>!N.has(P.id));A.length>0&&(x[S]=[...T,...A].sort(IS),w=!0)}if(!w)return;n({sessions:k,events:x})}catch(l){const c=l instanceof Error?l.message:String(l);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("promptSessions","warn",`hydrate failed for ${i}: ${c}`)}},hydrateArchived:async i=>{var r,s,a,d,l,c;if(!(typeof window>"u"||!((s=(r=window.api)==null?void 0:r.config)!=null&&s.listDir)||!((d=(a=window.api)==null?void 0:a.config)!=null&&d.readJson)))try{const h=`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions`,m=await window.api.config.listDir(h,{filesOnly:!0});if(!m.ok)return;const b={...e().sessions},_={...e().events};let y=!1;for(const k of m.entries){if(!k.name.endsWith(".json")||k.name==="active-index.json")continue;const x=k.name.slice(0,-5);if(b[x])continue;const w=await window.api.config.readJson(k.path);if(!w.exists||!w.data)continue;const S=w.data;!S.session||S.session.id!==x||(b[x]={...S.session,status:"completed"},_[x]=S.events??[],y=!0)}if(!y)return;n({sessions:b,events:_})}catch(h){const m=h instanceof Error?h.message:String(h);(c=(l=window.api)==null?void 0:l.logs)==null||c.write("promptSessions","warn",`hydrateArchived failed for ${i}: ${m}`)}},mergeAppendedEvent:(i,r,s)=>{const a=e().sessions[r];if(!a||a.cwd!==i)return;const d=e().events[r]??[];if(d.some(c=>c.id===s.id))return;const l={...e().events,[r]:[...d,s].sort(IS)};if(n({events:l}),s.kind==="response"&&r!==e().focusedEpicId){const{title:c}=q0(a.goalText),h=s.text?/^PRD (\S+) finished/.exec(s.text):null,m=h?`PRD ${h[1]} finished`:"Epic updated";Re.info(`${m} — ${c}`)}}}));var $j;typeof window<"u"&&(($j=window.api)!=null&&$j.promptSessions)&&window.api.promptSessions.onEventAppended(({cwd:n,promptSessionId:e,event:i})=>{Jt.getState().mergeAppendedEvent(n,e,i)});const nd={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},OS=20;function Pb(n,e){const i=[...n,e];return i.length>OS?i.slice(i.length-OS):i}let LS=0;function od(){return LS+=1,`t${Date.now().toString(36)}-${LS}`}const eP="Landed",zS=60;function tP(n){const e=n.trim();if(e.length<=zS)return e;const i=e.slice(0,zS),r=i.lastIndexOf(" ");return(r>0?i.slice(0,r):i).trim()}const Tn=Ti((n,e)=>({chats:{},hydratedTabs:{},get:i=>e().chats[i]??nd,hydrate:async({tabId:i,cwd:r,sessionId:s})=>{var a,d,l;if(!e().hydratedTabs[i]&&(n({hydratedTabs:{...e().hydratedTabs,[i]:!0}}),!(typeof window>"u"||!((a=window.api)!=null&&a.exchanges))))try{const c=await window.api.exchanges.list({cwd:r,sessionId:s});if(!c.length)return;const h=[];for(const f of[...c].reverse()){const b=new Date(f.ts).getTime();h.push({id:od(),role:"user",text:f.prompt,at:b}),h.push({id:od(),role:"assistant",text:f.result,at:b})}const m=e().chats[i]??nd;n({chats:{...e().chats,[i]:{...m,turns:[...h,...m.turns],started:!0}}})}catch(c){const h=c instanceof Error?c.message:String(c);(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`exchange hydration failed for tab ${i}: ${h}`)}},send:({tabId:i,sessionId:r,cwd:s,prompt:a,tag:d,chainRootId:l,external:c})=>{const h=a.trim();if(!h)return;if(Wl.getState().isAttached(i)){Re.error("Terminal mode is active for this Epic — switch back to Chat to send a message.");return}const m=e().chats[i]??nd;if(m.running){const f={id:crypto.randomUUID(),tabId:i,sessionId:r,cwd:s,text:h,status:"queued",createdAt:Date.now(),tag:d,chainRootId:l,external:c};n({chats:{...e().chats,[i]:{...m,queue:[...m.queue,f]}}});return}nP(i),Gj({tabId:i,sessionId:r,cwd:s,text:h,tag:d,chainRootId:l})},resetThread:i=>{n({chats:{...e().chats,[i]:{...nd}}})},pushNotice:(i,r)=>{Rb(i,"",r)},setPendingVoiceText:(i,r)=>{as(i,s=>({...s,pendingVoiceText:r}))},clearPendingVoiceText:i=>{as(i,r=>({...r,pendingVoiceText:void 0}))},dropTab:i=>{if(!(i in e().chats)&&!(i in e().hydratedTabs))return;const r={...e().chats};delete r[i];const s={...e().hydratedTabs};delete s[i],n({chats:r,hydratedTabs:s})}}));function as(n,e){const i=Tn.getState().chats[n]??nd;Tn.setState({chats:{...Tn.getState().chats,[n]:e(i)}})}function db(n,e,i={},r="done",s={}){as(n,a=>{const d=a.activeTicket?Pb(a.ticketHistory??[],{...a.activeTicket,status:r,completedAt:Date.now(),...s}):a.ticketHistory??[];return{...a,turns:[...a.turns,{...e,toolUses:a.liveToolUses}],running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:d,...i}}),__(n)}function nP(n){as(n,e=>{const i=e.ticketHistory??[];return i.some(r=>r.status==="needs-input")?{...e,ticketHistory:i.map(r=>r.status==="needs-input"?{...r,status:"done"}:r)}:e})}function Gj(n){const{tabId:e,sessionId:i,cwd:r,text:s,promptId:a,tag:d,chainRootId:l}=n,c=Tn.getState().chats[e]??nd,h={id:od(),role:"user",text:s,at:Date.now()};S_(e,"user",s);const m=c.activeTicket??{id:a??crypto.randomUUID(),tabId:e,sessionId:i,cwd:r,text:s,status:"running",createdAt:Date.now(),startedAt:Date.now(),tag:d,chainRootId:l};Tn.setState({chats:{...Tn.getState().chats,[e]:{...c,turns:[...c.turns,h],running:!0,queuedPosition:0,stream:"",activeTicket:m}}}),_y(r,i).catch(f=>{var _,y;const b=f instanceof Error?f.message:String(f);return(y=(_=window.api)==null?void 0:_.logs)==null||y.write("chat","warn",`transcript-exists check failed for tab ${e}: ${b}`),c.started}).then(f=>window.api.chat.run({tabId:e,sessionId:i,prompt:s,cwd:r,resume:f,promptId:a})).catch(f=>{const b=f instanceof Error?f.message:String(f);Uj(e,i,b)})}function __(n){const e=Tn.getState().chats[n]??nd;if(e.queue.length===0)return;const[i,...r]=e.queue;if(as(n,s=>({...s,queue:r,running:!0,queuedPosition:0,activeTicket:i})),i.external){gx(n,i);return}if(Jt.getState().sessions[n]){gx(n,i);return}if(W$(i.tag)){gx(n,i);return}U$(i.text).then(s=>{if(s==="develop"){sP(n,i);return}gx(n,i)})}function gx(n,e){const i={...e,status:"running",startedAt:Date.now()};as(n,r=>({...r,activeTicket:i})),Gj({tabId:i.tabId,sessionId:i.sessionId,cwd:i.cwd,text:i.text,promptId:i.id,tag:i.tag,chainRootId:i.chainRootId})}function iP(n,e){var i,r,s,a,d;try{const l=(i=Jt.getState().events[n])==null?void 0:i.slice(-1)[0];if(!l){(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`appendPrdCreatedEvent: PromptSession ${n} has no tail event — skipping prd_created append for ${e}`);return}Jt.getState().appendPromptSessionEvent(n,{kind:"prd_created",causedByEventId:l.id,prdSlug:e})}catch(l){const c=l instanceof Error?l.message:String(l);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("chat","warn",`appendPrdCreatedEvent failed for ${n}: ${c}`)}}const BS=2e3;function S_(n,e,i){var s,a,d,l;const r=Jt.getState().sessions[n];if(r)try{(a=(s=window.api)==null?void 0:s.promptSessionTranscript)==null||a.append(r.cwd,n,{role:e,text:i})}catch(c){const h=c instanceof Error?c.message:String(c);(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`capturePromptSessionTurn failed for ${n}: ${h}`)}}function FS(n,e){var i,r,s;try{const a=(i=Jt.getState().events[n])==null?void 0:i.slice(-1)[0];if(!a)return;const d=e.length>BS?`${e.slice(0,BS)}…`:e;Jt.getState().appendPromptSessionEvent(n,{kind:"response",causedByEventId:a.id,text:d})}catch(a){const d=a instanceof Error?a.message:String(a);(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`appendResponseEvent failed for ${n}: ${d}`)}}async function rP(n,e){var r,s,a,d;const i=l=>{var c;return!!l&&((c=Jt.getState().sessions[l])==null?void 0:c.status)==="active"};if(e.chainRootId){const c=((Tn.getState().chats[n]??nd).ticketHistory??[]).find(m=>m.id===e.chainRootId),h=(c==null?void 0:c.promptSessionId)??null;if(h){const m=Jt.getState().sessions[h];if(!m||m.status==="active")return h}}return i(n)||(await Jt.getState().hydrate(e.cwd),i(n))?n:(e.chainRootId?(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`continuation ticket ${e.id}: no resolvable PromptSession for chainRootId ${e.chainRootId} — refusing dispatch (sessions must never mint an Epic)`):(d=(a=window.api)==null?void 0:a.logs)==null||d.write("chat","warn",`ticket ${e.id}: no resolvable PromptSession for tab ${n} — refusing dispatch (sessions must never mint an Epic)`),null)}function sP(n,e){const i=r=>{as(n,s=>({...s,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:Pb(s.ticketHistory??[],{...e,status:"failed",completedAt:Date.now()})})),Rb(n,e.sessionId,r),Re.error(r),__(n)};rP(n,e).then(r=>{if(!r){i(`→ Ticket ${e.id}: no Epic to dispatch this PRD into. Create one via the New Epic card (or approve a proposed one), then resend.`);return}window.api.chat.createPrd({title:tP(e.text),cwd:e.cwd,estimateMinutes:15,goal:e.text,acceptanceCriteria:["Implement the request described in Goal.","timeout 300 npm run typecheck passes"],implementationNotes:`Target project: ${e.cwd}`,sourcePromptId:r,sourceTabId:e.tabId,tag:e.tag}).then(s=>{if(!(s!=null&&s.ok)){i(`→ PRD authoring failed for ticket ${e.id}: ${(s==null?void 0:s.error)??"unknown error"}`);return}const a=s.filename,d=a.endsWith(".md")?a.slice(0,-3):a;iP(r,d);const l={...e,status:"dispatched-to-prd",completedAt:Date.now(),promptSessionId:r,...e.chainRootId?{}:{prdSlugs:[d]}};Rb(n,l.sessionId,`→ dispatched to PRD ${a} (ticket ${l.id})`),as(n,c=>{let h=Pb(c.ticketHistory??[],l);if(e.chainRootId){const m=e.chainRootId;h=h.map(f=>f.id===m?{...f,prdSlugs:[...f.prdSlugs??[],d]}:f)}return{...c,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:h}}),__(n)}).catch(s=>{const a=s instanceof Error?s.message:String(s);i(`→ PRD authoring failed for ticket ${e.id}: ${a}`)})})}function Uj(n,e,i){as(n,r=>r.activeTicket?{...r,activeTicket:null,ticketHistory:Pb(r.ticketHistory??[],{...r.activeTicket,status:"failed",completedAt:Date.now()})}:r),db(n,{id:od(),role:"error",text:i,at:Date.now()}),Re.error(i)}function Rb(n,e,i){as(n,r=>({...r,turns:[...r.turns,{id:od(),role:"notice",text:i,at:Date.now()}]}))}var Pj;typeof window<"u"&&((Pj=window.api)!=null&&Pj.chat)&&(window.api.chat.onQueued(({tabId:n,position:e})=>{as(n,i=>({...i,running:!0,queuedPosition:e}))}),window.api.chat.onRunStarted(({tabId:n})=>{as(n,e=>({...e,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:n,delta:e})=>{as(n,i=>({...i,stream:i.stream+e}))}),window.api.chat.onToolUse(({tabId:n,id:e,kind:i,label:r,diff:s})=>{as(n,a=>({...a,liveToolUses:[...a.liveToolUses,{id:e,kind:i,label:r,diff:s}]}))}),window.api.chat.onComplete(({tabId:n,finalMessage:e})=>{S_(n,"assistant",e),FS(n,e),db(n,{id:od(),role:"assistant",text:e,at:Date.now(),outcome:eP})}),window.api.chat.onNeedsInput(({tabId:n,questions:e,answerBody:i})=>{const r=od();if(i&&i.trim()){S_(n,"assistant",i),FS(n,i),as(n,s=>({...s,turns:[...s.turns,{id:od(),role:"assistant",text:i,at:Date.now(),toolUses:s.liveToolUses}],liveToolUses:[]})),db(n,{id:r,role:"question",text:e.join(`
46
46
  `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r});return}db(n,{id:r,role:"question",text:e.join(`
47
- `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{Uj(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{Rb(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,d,l;const i=vt.getState().tabs.find(c=>c.id===n);if(i){Tn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=Jt.getState().sessions[n];if(r){if(r.status==="completed"){(a=(s=window.api)==null?void 0:s.logs)==null||a.write("chat","warn",`external send ignored: Epic ${n} is completed/archived — its claudeSessionId is dead`);return}Tn.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function oP(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function Hj(n,e=!1,i=H0()){let r=!e;r&&(r=await _y(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Xa(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${Xa(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const vt=Ti((n,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(i,r)=>{n(s=>({pendingRawCommand:{...s.pendingRawCommand,[i]:r}}))},consumeRawCommand:i=>{const r=e().pendingRawCommand[i];return r===void 0?null:(n(s=>{const a={...s.pendingRawCommand};return delete a[i],{pendingRawCommand:a}}),r)},addTab:({id:i,cwd:r,startupCommand:s,presetId:a=null,label:d,dormant:l=!1})=>{const c=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===c))return n({activeTabId:c}),c;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:c,sessionId:c,label:d??oP(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return n({tabs:[...e().tabs,m],activeTabId:c}),c},setTabRunning:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:r,status:"running"}:s)}),setTabExited:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,status:"exited",exitCode:r}:s)}),closeTab:i=>{var a;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{}),window.api.transcripts.closeTab(i).catch(()=>{}),Tn.getState().dropTab(i);const r=e().tabs.filter(d=>d.id!==i),s=e().activeTabId===i?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;n({tabs:r,activeTabId:s})},setActive:i=>n({activeTabId:i}),restartTab:i=>{const r=e().tabs.find(d=>d.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=d=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:l.generation+1}:l)})};r.presetId?Mj(r.presetId).then(d=>{a(d?Oj(d,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Xa(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Xa(s)}`)},reorderTab:(i,r)=>{const s=[...e().tabs];if(i<0||i>=s.length||r<0||r>=s.length||i===r)return;const[a]=s.splice(i,1);s.splice(r,0,a),n({tabs:s})},restoreTabs:(i,r)=>n({tabs:i,activeTabId:r,hydrated:!0}),wakeTab:async(i,r)=>{var l;const s=e().tabs.find(c=>c.id===i);if(!s||s.status!=="dormant")return;(l=Tn.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Re.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:d}=await Hj({cwd:s.cwd,sessionId:s.sessionId},!1,r??H0());n({tabs:e().tabs.map(c=>c.id===i?{...c,sessionId:a,status:"spawning",startupCommand:d,generation:c.generation+1}:c)})},sleepTab:i=>{const r=e().tabs.find(s=>s.id===i);!r||r.status==="dormant"||(window.api.pty.kill(i),n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:null,status:"dormant"}:s)}))},newSession:i=>{e().tabs.find(s=>s.id===i)&&n({tabs:e().tabs.map(s=>s.id===i?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(i,r)=>e().addTab({cwd:i,startupCommand:null,dormant:!0,...r})}));async function k_(){var i;if(vt.getState().hydrated)return;try{const{tabs:r,activeTabId:s,freshStart:a}=await window.api.sessions.load();if(r.length>0){const l=(await Promise.all(r.map(async h=>{try{const{sessionId:m}=await Hj(h,a);return{id:h.id,sessionId:m,cwd:h.cwd,label:h.label,presetId:h.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",h==null?void 0:h.id,m),null}}))).filter(h=>h!==null),c=s&&l.find(h=>h.id===s)?s:((i=l[0])==null?void 0:i.id)??null;vt.getState().restoreTabs(l,c)}else vt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),vt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=vt.getState(),a=r.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(d=>{console.warn("[sessions] save failed:",d)})};let e=null;vt.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(n,200)))}),n()}const aP=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:k_,useSessions:vt},Symbol.toStringTag,{value:"Module"})),GS=200,lP=/\x1b\[[0-9;]*m/g;function cP(n){return n.replace(lP,"")}const Tg=Ti((n,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(n({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:r,command:s,cwd:a})=>{try{const d=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={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 n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(d){return console.error("[watchers] add failed:",d),Re.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Re.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[i],n({watchers:r})},watchersForTab:i=>Object.values(e().watchers).filter(r=>r.tabId===i),ingestLine:i=>{const r=e().watchers[i.watcherId];if(!r)return;const s=cP(i.line),a=r.lines.length>=GS?[...r.lines.slice(r.lines.length-GS+1),{line:s,ts:i.ts}]:[...r.lines,{line:s,ts:i.ts}];n({watchers:{...e().watchers,[i.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const r={...e().watchers};delete r[i],n({watchers:r})}})),dP="~/.claude/session-manager/browser/history.json",US="~/.claude/session-manager/browser/bookmarks.json",uP=.25,hP=3,HS=.1,WS=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let VS=0;function pP(){const n=WS[VS%WS.length];return VS+=1,n}const Ib=new Map;function fP(n){if(Ib.has(n))return;const e=window.api.browser.onNavState(n,i=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===n?{...s,url:i.url,title:i.title||s.title,canGoBack:i.canGoBack,canGoForward:i.canGoForward,loading:i.loading,isSecure:i.isSecure}:s)}))});Ib.set(n,e)}function mP(n){const e=Ib.get(n);e&&(e(),Ib.delete(n))}const C_=new Map;let ub=null;function qS(n){const e=C_.get(n);e&&(e(),C_.delete(n))}function KS(){ub&&(clearInterval(ub),ub=null)}const E_=new Map;function cw(n){const e=E_.get(n);e&&(e(),E_.delete(n))}const Pt=Ti((n,e)=>({tabs:[],activeTabId:null,openTab:i=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(i==null?void 0:i.url)??"about:blank",color:(i==null?void 0:i.color)??pP(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(d=>({tabs:[...d.tabs,a],activeTabId:r})),fP(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{i!=null&&i.url&&window.api.browser.navigate({viewId:s,url:i.url}).catch(()=>{})}).catch(d=>{var c,h;const l=d instanceof Error?d.message:String(d);(h=(c=window.api)==null?void 0:c.logs)==null||h.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(mP(r.viewId),cw(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),d=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:d}}))},setActive:i=>{n({activeTabId:i})},navigate:(i,r)=>{const s=e().tabs.find(a=>a.id===i);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:i=>n(r=>({mode:i,captured:i==="capture"?r.captured:null})),setCaptureMode:i=>n({captureMode:i,captured:null}),onVerb:i=>{const{mode:r}=e();if(i==="shot"){n({mode:"capture",captureMode:"shot",captured:null});return}if(r===i){n({mode:"browse",captured:i==="capture"?null:e().captured});return}n({mode:i,captureMode:i==="capture"?"agent":e().captureMode,captured:i==="capture"?e().captured:null})},captured:null,capture:async i=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),d=s.find(c=>c.id===r);if(!d)throw new Error("No active browser tab");if(a==="shot"){const c=await window.api.browser.captureShot(d.viewId);if(!c.ok)throw new Error(c.error);n({captured:{mode:a,url:c.url,title:c.title,dataUrl:c.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:d.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:d.url,title:d.title,text:l.text,meta:l.meta,selectors:i,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:i=>{if(e().recorderActive)return;n({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(i).catch(()=>{}),qS(i);const r=window.api.browser.onRecordStep(i,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});C_.set(i,r),KS(),ub=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),qS(i),KS(),n({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&n(i=>({recording:!i.recording}))},toggleStepVariable:i=>{n(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===i?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const i=await window.api.config.readJson(US),r=i.exists&&Array.isArray(i.data)?i.data:[];n({bookmarks:r,bookmarksHydrated:!0})}catch{n({bookmarksHydrated:!0})}},toggleBookmark:i=>{const r=e().tabs.find(l=>l.id===i);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,d=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];n({bookmarks:d}),window.api.config.writeJson(US,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(dP),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(d=>d.id===i);if(!s)return;const a=Math.min(hP,Math.max(uP,r));n(d=>({tabs:d.tabs.map(l=>l.id===i?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor+HS)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-HS)},zoomReset:i=>e().setZoom(i,1),findOpen:!1,findText:"",findMatches:null,openFind:i=>{const r=e().tabs.find(a=>a.id===i);if(!r)return;n({findOpen:!0,findText:"",findMatches:null}),cw(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});E_.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(cw(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(i,r)=>{const s=e().tabs.find(a=>a.id===i);if(n({findText:r}),!!s){if(!r){window.api.browser.find({viewId:s.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:s.viewId,text:r,forward:!0}).catch(()=>{})}},findNext:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),Mc=["home"],yp=["project"],Tl=["home","project"],J0=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:Mc},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:yp},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics for this project",faces:yp},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:Mc},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit — starts at your home folder from Home, the active project from a Tab",faces:Tl},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Global policy + this project's live PRD queue",faces:Tl},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Tl},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:Tl},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:Tl},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:Mc},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:Tl},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:Tl},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override",faces:Mc},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:yp},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:Tl},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window",faces:Tl},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:Mc},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:Mc},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Epic intent tags and their /develop behavior",faces:Mc},{key:"bilko-host",group:"Configure",label:"Host on Bilko.run",icon:"link",hint:"Publish this project's Marketing page to bilko.run",faces:yp},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:Mc},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map",faces:yp},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content",faces:yp}];function gP(n){return J0.filter(e=>e.faces.includes(n)).map(e=>{var i,r;return{...e,label:((i=e.labelByFace)==null?void 0:i[n])??e.label,hint:((r=e.hintByFace)==null?void 0:r[n])??e.hint}})}const vP=Object.fromEntries(J0.map(n=>[n.key,n.group])),dw={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."},Wj=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","keybindings","memory","projects","system-prompt","permissions","settings","remote","agent-library","tag-library","bilko-host","voice","repoviz","search","editor"],xP={editor:"Editor"},bP=Object.fromEntries(J0.map(n=>[n.key,n.label])),yP=Object.fromEntries(Wj.map(n=>[n,xP[n]??bP[n]??n])),Vj="~/.claude/session-manager/app-prefs.json";async function Z0(){var n,e;if(typeof window>"u"||!((e=(n=window.api)==null?void 0:n.config)!=null&&e.readJson))return{};try{const i=await window.api.config.readJson(Vj);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function wP(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await Z0();await window.api.config.writeJson(Vj,{...e,...n})}const xu=Wj.map(n=>({id:n,title:yP[n],component:"screen"})),mn=Ti((n,e)=>{var i;return{panels:[...xu],focusedPanelId:((i=xu[0])==null?void 0:i.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:r=>n({epicsWorkspaceOpen:r}),navFace:"home",setNavFace:r=>n({navFace:r}),openPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,...r==="overview"?{navFace:"home"}:null}))},openProjectPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,navFace:"project"}))},focusPanel:r=>{e().panels.some(a=>a.id===r)&&n({focusedPanelId:r,...r==="overview"?{navFace:"home"}:null})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=xu[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var s;(await Z0()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=xu[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview",navFace:"home"})}}});function _P(n){return mn.getState().panels.find(e=>e.id===n)}function SP(n,e,i="project"){return n==="projects"&&e===null&&i==="project"}function sn({name:n,size:e=17,stroke:i=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(n){case"home":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 11l8-7 8 7"}),o.jsx("path",{d:"M6 10v9h12v-9"}),o.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M7 10l3 2-3 2"}),o.jsx("path",{d:"M13 14h4"})]});case"skills":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"}),o.jsx("path",{d:"M4 6l2 2"})]});case"usage":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),o.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),o.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),o.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),o.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"8",cy:"12",r:"4"}),o.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return o.jsxs("svg",{...s,children:[o.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"}),o.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"11",cy:"11",r:"6"}),o.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M7 3h7l4 4v14H7z"}),o.jsx("path",{d:"M14 3v4h4"})]});case"play":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),o.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),o.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),o.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),o.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"repoviz":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"6",cy:"12",r:"3"}),o.jsx("circle",{cx:"18",cy:"6",r:"3"}),o.jsx("circle",{cx:"18",cy:"18",r:"3"}),o.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),o.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),o.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),o.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 12h6"}),o.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),o.jsx("path",{d:"M4 12h16"})]});case"target":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),o.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),o.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),o.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return o.jsx("svg",{...s,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return o.jsx("svg",{...s,children:o.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 o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14"})});case"paperclip":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});case"expand":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M8 3H3v5"}),o.jsx("path",{d:"M16 3h5v5"}),o.jsx("path",{d:"M8 21H3v-5"}),o.jsx("path",{d:"M16 21h5v-5"})]});case"collapse":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M3 8h5V3"}),o.jsx("path",{d:"M21 8h-5V3"}),o.jsx("path",{d:"M3 16h5v5"}),o.jsx("path",{d:"M21 16h-5v5"})]});default:return null}}const kP=4,YS=40,XS=6;function CP(n){const{onReorder:e,onActivate:i}=n,r=R.useRef(null),s=R.useRef(null),a=R.useRef(0),d=R.useRef(0),[l,c]=R.useState(!1),[,h]=R.useState(0),m=R.useRef(i);m.current=i;const f=R.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=R.useCallback((x,w,S)=>{for(let C=0;C<w.length;C++){const T=w[C].left+w[C].width/2;if(x<T)return C<=S?C:C-1}return w.length-1},[]),_=R.useCallback(()=>{const x=s.current,w=r.current;if(!(x!=null&&x.active)||!w)return;const S=w.getBoundingClientRect(),C=x.startX+x.deltaX,T=C-S.left,N=S.right-C;T<YS?w.scrollLeft-=XS:N<YS&&(w.scrollLeft+=XS),a.current=requestAnimationFrame(_)},[]);R.useEffect(()=>{const x=r.current;if(!x)return;let w=!1;const S=()=>{w||(w=!0,d.current=requestAnimationFrame(()=>{w=!1,h(N=>N+1)}))},C=N=>{var H;const A=s.current;if(!A)return;const P=N.clientX-A.startX;if(!A.active&&Math.abs(P)<kP)return;if(!A.active){A.active=!0,A.tabRects=f().map(B=>B.getBoundingClientRect()),c(!0);try{(H=r.current)==null||H.setPointerCapture(A.pointerId)}catch{}a.current=requestAnimationFrame(_)}A.deltaX=P;const I=A.tabRects[A.fromIndex],O=I.left+I.width/2+P;A.currentIndex=b(O,A.tabRects,A.fromIndex),S()},T=N=>{const A=s.current;if(A&&A.pointerId===N.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(d.current);try{x.releasePointerCapture(A.pointerId)}catch{}A.active&&A.fromIndex!==A.currentIndex?e(A.fromIndex,A.currentIndex):m.current(A.fromIndex),s.current=null,c(!1),h(P=>P+1)}};return x.addEventListener("pointermove",C),x.addEventListener("pointerup",T),x.addEventListener("pointercancel",T),()=>{x.removeEventListener("pointermove",C),x.removeEventListener("pointerup",T),x.removeEventListener("pointercancel",T),cancelAnimationFrame(a.current),cancelAnimationFrame(d.current)}},[e,f,b,_]);const y=R.useCallback((x,w)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:w,currentIndex:w,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:R.useCallback(x=>{var C;const w=s.current,S={};if(w!=null&&w.active)if(x===w.fromIndex)S.transform=`translateX(${w.deltaX}px) scale(1.03)`,S.zIndex=10,S.opacity=.85,S.boxShadow="0 2px 8px rgba(0,0,0,0.4)",S.position="relative",S.pointerEvents="none";else{const T=w.fromIndex,N=w.currentIndex,P=(((C=w.tabRects[T])==null?void 0:C.width)??0)+4;S.transition="transform 0.15s ease",T<N&&x>T&&x<=N?S.transform=`translateX(-${P}px)`:T>N&&x>=N&&x<T?S.transform=`translateX(${P}px)`:S.transform="translateX(0)"}return{onPointerDown:T=>y(T,x),style:S,"data-drag-index":x}},[y]),isDragging:l,containerRef:r}}const EP=3e4;function jP({onToggleSplitView:n,splitViewActive:e}={}){const i=vt(N=>N.tabs),r=vt(N=>N.activeTabId),s=vt(N=>N.closeTab),a=vt(N=>N.setActive),d=vt(N=>N.reorderTab),l=Tg(N=>N.watchers),c=Pt(N=>N.tabs.length>0),h=r!=null&&c,m=mn(N=>N.openPanel),f=mn(N=>N.openProjectPanel),b=mn(N=>N.setEpicsWorkspaceOpen),_=mn(N=>N.navFace==="home"),[y,k]=R.useState(()=>Date.now());R.useEffect(()=>{const N=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(N)},[]);const x=N=>{for(const A of Object.values(l))if(A.tabId===N&&A.lastLineAt&&y-A.lastLineAt<EP)return!0;return!1},{getTabDragProps:w,isDragging:S,containerRef:C}=CP({tabCount:i.length,onReorder:d,onActivate:N=>{const A=i[N];A&&(a(A.id),b(!1),f("terminal"))}}),T=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return o.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:[o.jsxs("button",{onClick:()=>m("overview"),title:"This machine — home","aria-current":_?"true":void 0,"data-testid":"tabbar-machine-home",className:`flex items-center gap-2 px-3.5 py-1.5 mb-1 rounded-full text-[13px] shrink-0 transition-colors ${_?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(sn,{name:"home",className:"w-[15px] h-[15px]"}),o.jsx("span",{children:"Home"})]}),o.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),o.jsx("div",{ref:C,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((N,A)=>{const P=N.id===r,I=w(A),O=T[A%T.length];return o.jsxs("div",{...I,style:I.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 ${S?"":"cursor-grab"} ${P?"bg-bg text-fg font-medium relative z-10 -mb-px border border-accent shadow-[inset_0_2px_0_theme(colors.accent.DEFAULT)]":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:N.cwd,"aria-current":P?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:O,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:N.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:N.label}),N.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),x(N.id)&&o.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"}),o.jsx("button",{onClick:H=>{H.stopPropagation(),s(N.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${N.label}`,children:"×"})]},N.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[h&&n&&o.jsxs("button",{onClick:n,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${e?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":e??!1,children:[o.jsx("span",{"aria-hidden":"true",children:"⇄"}),o.jsx("span",{children:"Split view"})]}),o.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.57.0"]})]})]})}var uw={},Lm={},JS;function qj(){if(JS)return Lm;JS=1,Object.defineProperty(Lm,"__esModule",{value:!0}),Lm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Lm.baseAssetPath=i,Lm}var zm={},ZS;function Q0(){if(ZS)return zm;ZS=1,Object.defineProperty(zm,"__esModule",{value:!0}),zm.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return zm.defaultModelFetcher=n,zm}var Nl={},Bm={},QS;function sv(){if(QS)return Bm;QS=1,Object.defineProperty(Bm,"__esModule",{value:!0}),Bm.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Bm.log={error:n("error"),debug:n("debug"),warn:n("warn")},Bm}var Fm={},ek;function ky(){if(ek)return Fm;ek=1,Object.defineProperty(Fm,"__esModule",{value:!0}),Fm.Message=void 0;var n;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(n||(Fm.Message=n={})),Fm}var tk;function e1(){if(tk)return Nl;tk=1,Object.defineProperty(Nl,"__esModule",{value:!0}),Nl.FrameProcessor=Nl.validateOptions=Nl.defaultFrameProcessorOptions=void 0;const n=sv(),e=ky();Nl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&n.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}Nl.validateOptions=i;const r=d=>{const l=d.reduce((h,m)=>(h.push(h.at(-1)+m.length),h),[0]),c=new Float32Array(l.at(-1));return d.forEach((h,m)=>{const f=l[m];c.set(h,f)}),c};function s(d,l){const c=Math.floor(d.redemptionMs/l),h=Math.floor(d.preSpeechPadMs/l),m=Math.floor(d.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:h,minSpeechFrames:m}}class a{constructor(l,c,h,m){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=h,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=y=>{this.options={...this.options,...y};const{redemptionFrames:k,preSpeechPadFrames:x,minSpeechFrames:w}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=x,this.minSpeechFrames=w},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=y=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(y):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=y=>{const k=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(k.reduce((S,C)=>C.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(C=>C.frame));y({msg:e.Message.SpeechEnd,audio:S})}else y({msg:e.Message.VADMisfire});return{}},this.process=async(y,k)=>{if(!this.active)return;const x=await this.modelProcessFunc(y),w=x.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:x,msg:e.Message.FrameProcessed,frame:y}),this.audioBuffer.push({frame:y,isSpeech:w}),w&&(this.speechFrameCount++,this.redemptionCounter=0),w&&!this.speaking&&(this.speaking=!0,k({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,k({msg:e.Message.SpeechRealStart})),x.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const S=this.audioBuffer;if(this.audioBuffer=[],S.reduce((T,N)=>N.isSpeech?T+1:T,0)>=this.minSpeechFrames){const T=r(S.map(N=>N.frame));k({msg:e.Message.SpeechEnd,audio:T})}else k({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:f,preSpeechPadFrames:b,minSpeechFrames:_}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=_,this.reset()}}return Nl.FrameProcessor=a,Nl}var Dl={};function Eo(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var hw={exports:{}};/*!
47
+ `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{Uj(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{Rb(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,d,l;const i=vt.getState().tabs.find(c=>c.id===n);if(i){Tn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=Jt.getState().sessions[n];if(r){if(r.status==="completed"){(a=(s=window.api)==null?void 0:s.logs)==null||a.write("chat","warn",`external send ignored: Epic ${n} is completed/archived — its claudeSessionId is dead`);return}Tn.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function oP(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function Hj(n,e=!1,i=H0()){let r=!e;r&&(r=await _y(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Xa(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${Xa(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const vt=Ti((n,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(i,r)=>{n(s=>({pendingRawCommand:{...s.pendingRawCommand,[i]:r}}))},consumeRawCommand:i=>{const r=e().pendingRawCommand[i];return r===void 0?null:(n(s=>{const a={...s.pendingRawCommand};return delete a[i],{pendingRawCommand:a}}),r)},addTab:({id:i,cwd:r,startupCommand:s,presetId:a=null,label:d,dormant:l=!1})=>{const c=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===c))return n({activeTabId:c}),c;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:c,sessionId:c,label:d??oP(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return n({tabs:[...e().tabs,m],activeTabId:c}),c},setTabRunning:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:r,status:"running"}:s)}),setTabExited:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,status:"exited",exitCode:r}:s)}),closeTab:i=>{var a;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{}),window.api.transcripts.closeTab(i).catch(()=>{}),Tn.getState().dropTab(i);const r=e().tabs.filter(d=>d.id!==i),s=e().activeTabId===i?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;n({tabs:r,activeTabId:s})},setActive:i=>n({activeTabId:i}),restartTab:i=>{const r=e().tabs.find(d=>d.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=d=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:l.generation+1}:l)})};r.presetId?Mj(r.presetId).then(d=>{a(d?Oj(d,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Xa(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Xa(s)}`)},reorderTab:(i,r)=>{const s=[...e().tabs];if(i<0||i>=s.length||r<0||r>=s.length||i===r)return;const[a]=s.splice(i,1);s.splice(r,0,a),n({tabs:s})},restoreTabs:(i,r)=>n({tabs:i,activeTabId:r,hydrated:!0}),wakeTab:async(i,r)=>{var l;const s=e().tabs.find(c=>c.id===i);if(!s||s.status!=="dormant")return;(l=Tn.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Re.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:d}=await Hj({cwd:s.cwd,sessionId:s.sessionId},!1,r??H0());n({tabs:e().tabs.map(c=>c.id===i?{...c,sessionId:a,status:"spawning",startupCommand:d,generation:c.generation+1}:c)})},sleepTab:i=>{const r=e().tabs.find(s=>s.id===i);!r||r.status==="dormant"||(window.api.pty.kill(i),n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:null,status:"dormant"}:s)}))},newSession:i=>{e().tabs.find(s=>s.id===i)&&n({tabs:e().tabs.map(s=>s.id===i?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(i,r)=>e().addTab({cwd:i,startupCommand:null,dormant:!0,...r})}));async function k_(){var i;if(vt.getState().hydrated)return;try{const{tabs:r,activeTabId:s,freshStart:a}=await window.api.sessions.load();if(r.length>0){const l=(await Promise.all(r.map(async h=>{try{const{sessionId:m}=await Hj(h,a);return{id:h.id,sessionId:m,cwd:h.cwd,label:h.label,presetId:h.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",h==null?void 0:h.id,m),null}}))).filter(h=>h!==null),c=s&&l.find(h=>h.id===s)?s:((i=l[0])==null?void 0:i.id)??null;vt.getState().restoreTabs(l,c)}else vt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),vt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=vt.getState(),a=r.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(d=>{console.warn("[sessions] save failed:",d)})};let e=null;vt.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(n,200)))}),n()}const aP=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:k_,useSessions:vt},Symbol.toStringTag,{value:"Module"})),GS=200,lP=/\x1b\[[0-9;]*m/g;function cP(n){return n.replace(lP,"")}const Tg=Ti((n,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(n({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:r,command:s,cwd:a})=>{try{const d=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={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 n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(d){return console.error("[watchers] add failed:",d),Re.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Re.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[i],n({watchers:r})},watchersForTab:i=>Object.values(e().watchers).filter(r=>r.tabId===i),ingestLine:i=>{const r=e().watchers[i.watcherId];if(!r)return;const s=cP(i.line),a=r.lines.length>=GS?[...r.lines.slice(r.lines.length-GS+1),{line:s,ts:i.ts}]:[...r.lines,{line:s,ts:i.ts}];n({watchers:{...e().watchers,[i.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const r={...e().watchers};delete r[i],n({watchers:r})}})),dP="~/.claude/session-manager/browser/history.json",US="~/.claude/session-manager/browser/bookmarks.json",uP=.25,hP=3,HS=.1,WS=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let VS=0;function pP(){const n=WS[VS%WS.length];return VS+=1,n}const Ib=new Map;function fP(n){if(Ib.has(n))return;const e=window.api.browser.onNavState(n,i=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===n?{...s,url:i.url,title:i.title||s.title,canGoBack:i.canGoBack,canGoForward:i.canGoForward,loading:i.loading,isSecure:i.isSecure}:s)}))});Ib.set(n,e)}function mP(n){const e=Ib.get(n);e&&(e(),Ib.delete(n))}const C_=new Map;let ub=null;function qS(n){const e=C_.get(n);e&&(e(),C_.delete(n))}function KS(){ub&&(clearInterval(ub),ub=null)}const E_=new Map;function cw(n){const e=E_.get(n);e&&(e(),E_.delete(n))}const Pt=Ti((n,e)=>({tabs:[],activeTabId:null,openTab:i=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(i==null?void 0:i.url)??"about:blank",color:(i==null?void 0:i.color)??pP(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(d=>({tabs:[...d.tabs,a],activeTabId:r})),fP(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{i!=null&&i.url&&window.api.browser.navigate({viewId:s,url:i.url}).catch(()=>{})}).catch(d=>{var c,h;const l=d instanceof Error?d.message:String(d);(h=(c=window.api)==null?void 0:c.logs)==null||h.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(mP(r.viewId),cw(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),d=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:d}}))},setActive:i=>{n({activeTabId:i})},navigate:(i,r)=>{const s=e().tabs.find(a=>a.id===i);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:i=>n(r=>({mode:i,captured:i==="capture"?r.captured:null})),setCaptureMode:i=>n({captureMode:i,captured:null}),onVerb:i=>{const{mode:r}=e();if(i==="shot"){n({mode:"capture",captureMode:"shot",captured:null});return}if(r===i){n({mode:"browse",captured:i==="capture"?null:e().captured});return}n({mode:i,captureMode:i==="capture"?"agent":e().captureMode,captured:i==="capture"?e().captured:null})},captured:null,capture:async i=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),d=s.find(c=>c.id===r);if(!d)throw new Error("No active browser tab");if(a==="shot"){const c=await window.api.browser.captureShot(d.viewId);if(!c.ok)throw new Error(c.error);n({captured:{mode:a,url:c.url,title:c.title,dataUrl:c.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:d.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:d.url,title:d.title,text:l.text,meta:l.meta,selectors:i,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:i=>{if(e().recorderActive)return;n({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(i).catch(()=>{}),qS(i);const r=window.api.browser.onRecordStep(i,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});C_.set(i,r),KS(),ub=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),qS(i),KS(),n({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&n(i=>({recording:!i.recording}))},toggleStepVariable:i=>{n(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===i?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const i=await window.api.config.readJson(US),r=i.exists&&Array.isArray(i.data)?i.data:[];n({bookmarks:r,bookmarksHydrated:!0})}catch{n({bookmarksHydrated:!0})}},toggleBookmark:i=>{const r=e().tabs.find(l=>l.id===i);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,d=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];n({bookmarks:d}),window.api.config.writeJson(US,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(dP),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(d=>d.id===i);if(!s)return;const a=Math.min(hP,Math.max(uP,r));n(d=>({tabs:d.tabs.map(l=>l.id===i?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor+HS)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-HS)},zoomReset:i=>e().setZoom(i,1),findOpen:!1,findText:"",findMatches:null,openFind:i=>{const r=e().tabs.find(a=>a.id===i);if(!r)return;n({findOpen:!0,findText:"",findMatches:null}),cw(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});E_.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(cw(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(i,r)=>{const s=e().tabs.find(a=>a.id===i);if(n({findText:r}),!!s){if(!r){window.api.browser.find({viewId:s.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:s.viewId,text:r,forward:!0}).catch(()=>{})}},findNext:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),Mc=["home"],yp=["project"],Tl=["home","project"],J0=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:Mc},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:yp},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics for this project",faces:yp},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:Mc},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit — starts at your home folder from Home, the active project from a Tab",faces:Tl},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Global policy + this project's live PRD queue",faces:Tl},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Tl},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:Tl},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:Tl},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:Mc},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:Tl},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:Tl},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override",faces:Mc},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:yp},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:Tl},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window",faces:Tl},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:Mc},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:Mc},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Epic intent tags and their /develop behavior",faces:Mc},{key:"bilko-host",group:"Configure",label:"Host on Bilko.run",icon:"link",hint:"Publish this project's Marketing page to bilko.run",faces:yp},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:Mc},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map",faces:yp},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content",faces:yp}];function gP(n){return J0.filter(e=>e.faces.includes(n)).map(e=>{var i,r;return{...e,label:((i=e.labelByFace)==null?void 0:i[n])??e.label,hint:((r=e.hintByFace)==null?void 0:r[n])??e.hint}})}const vP=Object.fromEntries(J0.map(n=>[n.key,n.group])),dw={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."},Wj=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","keybindings","memory","projects","system-prompt","permissions","settings","remote","agent-library","tag-library","bilko-host","voice","repoviz","search","editor"],xP={editor:"Editor"},bP=Object.fromEntries(J0.map(n=>[n.key,n.label])),yP=Object.fromEntries(Wj.map(n=>[n,xP[n]??bP[n]??n])),Vj="~/.claude/session-manager/app-prefs.json";async function Z0(){var n,e;if(typeof window>"u"||!((e=(n=window.api)==null?void 0:n.config)!=null&&e.readJson))return{};try{const i=await window.api.config.readJson(Vj);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function wP(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await Z0();await window.api.config.writeJson(Vj,{...e,...n})}const xu=Wj.map(n=>({id:n,title:yP[n],component:"screen"})),mn=Ti((n,e)=>{var i;return{panels:[...xu],focusedPanelId:((i=xu[0])==null?void 0:i.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:r=>n({epicsWorkspaceOpen:r}),navFace:"home",setNavFace:r=>n({navFace:r}),openPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,...r==="overview"?{navFace:"home"}:null}))},openProjectPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,navFace:"project"}))},focusPanel:r=>{e().panels.some(a=>a.id===r)&&n({focusedPanelId:r,...r==="overview"?{navFace:"home"}:null})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=xu[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var s;(await Z0()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=xu[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview",navFace:"home"})}}});function _P(n){return mn.getState().panels.find(e=>e.id===n)}function SP(n,e,i="project"){return n==="projects"&&e===null&&i==="project"}function sn({name:n,size:e=17,stroke:i=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(n){case"home":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 11l8-7 8 7"}),o.jsx("path",{d:"M6 10v9h12v-9"}),o.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M7 10l3 2-3 2"}),o.jsx("path",{d:"M13 14h4"})]});case"skills":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"}),o.jsx("path",{d:"M4 6l2 2"})]});case"usage":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),o.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),o.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),o.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),o.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"8",cy:"12",r:"4"}),o.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return o.jsxs("svg",{...s,children:[o.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"}),o.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"11",cy:"11",r:"6"}),o.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M7 3h7l4 4v14H7z"}),o.jsx("path",{d:"M14 3v4h4"})]});case"play":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),o.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),o.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),o.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),o.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"repoviz":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"6",cy:"12",r:"3"}),o.jsx("circle",{cx:"18",cy:"6",r:"3"}),o.jsx("circle",{cx:"18",cy:"18",r:"3"}),o.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),o.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),o.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),o.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 12h6"}),o.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),o.jsx("path",{d:"M4 12h16"})]});case"target":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),o.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),o.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),o.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return o.jsx("svg",{...s,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return o.jsx("svg",{...s,children:o.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 o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14"})});case"paperclip":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});case"expand":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M8 3H3v5"}),o.jsx("path",{d:"M16 3h5v5"}),o.jsx("path",{d:"M8 21H3v-5"}),o.jsx("path",{d:"M16 21h5v-5"})]});case"collapse":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M3 8h5V3"}),o.jsx("path",{d:"M21 8h-5V3"}),o.jsx("path",{d:"M3 16h5v5"}),o.jsx("path",{d:"M21 16h-5v5"})]});default:return null}}const kP=4,YS=40,XS=6;function CP(n){const{onReorder:e,onActivate:i}=n,r=R.useRef(null),s=R.useRef(null),a=R.useRef(0),d=R.useRef(0),[l,c]=R.useState(!1),[,h]=R.useState(0),m=R.useRef(i);m.current=i;const f=R.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=R.useCallback((x,w,S)=>{for(let C=0;C<w.length;C++){const T=w[C].left+w[C].width/2;if(x<T)return C<=S?C:C-1}return w.length-1},[]),_=R.useCallback(()=>{const x=s.current,w=r.current;if(!(x!=null&&x.active)||!w)return;const S=w.getBoundingClientRect(),C=x.startX+x.deltaX,T=C-S.left,N=S.right-C;T<YS?w.scrollLeft-=XS:N<YS&&(w.scrollLeft+=XS),a.current=requestAnimationFrame(_)},[]);R.useEffect(()=>{const x=r.current;if(!x)return;let w=!1;const S=()=>{w||(w=!0,d.current=requestAnimationFrame(()=>{w=!1,h(N=>N+1)}))},C=N=>{var H;const A=s.current;if(!A)return;const P=N.clientX-A.startX;if(!A.active&&Math.abs(P)<kP)return;if(!A.active){A.active=!0,A.tabRects=f().map(B=>B.getBoundingClientRect()),c(!0);try{(H=r.current)==null||H.setPointerCapture(A.pointerId)}catch{}a.current=requestAnimationFrame(_)}A.deltaX=P;const I=A.tabRects[A.fromIndex],O=I.left+I.width/2+P;A.currentIndex=b(O,A.tabRects,A.fromIndex),S()},T=N=>{const A=s.current;if(A&&A.pointerId===N.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(d.current);try{x.releasePointerCapture(A.pointerId)}catch{}A.active&&A.fromIndex!==A.currentIndex?e(A.fromIndex,A.currentIndex):m.current(A.fromIndex),s.current=null,c(!1),h(P=>P+1)}};return x.addEventListener("pointermove",C),x.addEventListener("pointerup",T),x.addEventListener("pointercancel",T),()=>{x.removeEventListener("pointermove",C),x.removeEventListener("pointerup",T),x.removeEventListener("pointercancel",T),cancelAnimationFrame(a.current),cancelAnimationFrame(d.current)}},[e,f,b,_]);const y=R.useCallback((x,w)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:w,currentIndex:w,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:R.useCallback(x=>{var C;const w=s.current,S={};if(w!=null&&w.active)if(x===w.fromIndex)S.transform=`translateX(${w.deltaX}px) scale(1.03)`,S.zIndex=10,S.opacity=.85,S.boxShadow="0 2px 8px rgba(0,0,0,0.4)",S.position="relative",S.pointerEvents="none";else{const T=w.fromIndex,N=w.currentIndex,P=(((C=w.tabRects[T])==null?void 0:C.width)??0)+4;S.transition="transform 0.15s ease",T<N&&x>T&&x<=N?S.transform=`translateX(-${P}px)`:T>N&&x>=N&&x<T?S.transform=`translateX(${P}px)`:S.transform="translateX(0)"}return{onPointerDown:T=>y(T,x),style:S,"data-drag-index":x}},[y]),isDragging:l,containerRef:r}}const EP=3e4;function jP({onToggleSplitView:n,splitViewActive:e}={}){const i=vt(N=>N.tabs),r=vt(N=>N.activeTabId),s=vt(N=>N.closeTab),a=vt(N=>N.setActive),d=vt(N=>N.reorderTab),l=Tg(N=>N.watchers),c=Pt(N=>N.tabs.length>0),h=r!=null&&c,m=mn(N=>N.openPanel),f=mn(N=>N.openProjectPanel),b=mn(N=>N.setEpicsWorkspaceOpen),_=mn(N=>N.navFace==="home"),[y,k]=R.useState(()=>Date.now());R.useEffect(()=>{const N=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(N)},[]);const x=N=>{for(const A of Object.values(l))if(A.tabId===N&&A.lastLineAt&&y-A.lastLineAt<EP)return!0;return!1},{getTabDragProps:w,isDragging:S,containerRef:C}=CP({tabCount:i.length,onReorder:d,onActivate:N=>{const A=i[N];A&&(a(A.id),b(!1),f("terminal"))}}),T=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return o.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:[o.jsxs("button",{onClick:()=>m("overview"),title:"This machine — home","aria-current":_?"true":void 0,"data-testid":"tabbar-machine-home",className:`flex items-center gap-2 px-3.5 py-1.5 mb-1 rounded-full text-[13px] shrink-0 transition-colors ${_?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(sn,{name:"home",className:"w-[15px] h-[15px]"}),o.jsx("span",{children:"Home"})]}),o.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),o.jsx("div",{ref:C,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((N,A)=>{const P=N.id===r,I=w(A),O=T[A%T.length];return o.jsxs("div",{...I,style:I.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 ${S?"":"cursor-grab"} ${P?"bg-bg text-fg font-medium relative z-10 -mb-px border border-accent shadow-[inset_0_2px_0_theme(colors.accent.DEFAULT)]":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:N.cwd,"aria-current":P?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:O,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:N.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:N.label}),N.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),x(N.id)&&o.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"}),o.jsx("button",{onClick:H=>{H.stopPropagation(),s(N.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${N.label}`,children:"×"})]},N.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[h&&n&&o.jsxs("button",{onClick:n,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${e?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":e??!1,children:[o.jsx("span",{"aria-hidden":"true",children:"⇄"}),o.jsx("span",{children:"Split view"})]}),o.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.57.1"]})]})]})}var uw={},Lm={},JS;function qj(){if(JS)return Lm;JS=1,Object.defineProperty(Lm,"__esModule",{value:!0}),Lm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Lm.baseAssetPath=i,Lm}var zm={},ZS;function Q0(){if(ZS)return zm;ZS=1,Object.defineProperty(zm,"__esModule",{value:!0}),zm.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return zm.defaultModelFetcher=n,zm}var Nl={},Bm={},QS;function sv(){if(QS)return Bm;QS=1,Object.defineProperty(Bm,"__esModule",{value:!0}),Bm.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Bm.log={error:n("error"),debug:n("debug"),warn:n("warn")},Bm}var Fm={},ek;function ky(){if(ek)return Fm;ek=1,Object.defineProperty(Fm,"__esModule",{value:!0}),Fm.Message=void 0;var n;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(n||(Fm.Message=n={})),Fm}var tk;function e1(){if(tk)return Nl;tk=1,Object.defineProperty(Nl,"__esModule",{value:!0}),Nl.FrameProcessor=Nl.validateOptions=Nl.defaultFrameProcessorOptions=void 0;const n=sv(),e=ky();Nl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&n.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}Nl.validateOptions=i;const r=d=>{const l=d.reduce((h,m)=>(h.push(h.at(-1)+m.length),h),[0]),c=new Float32Array(l.at(-1));return d.forEach((h,m)=>{const f=l[m];c.set(h,f)}),c};function s(d,l){const c=Math.floor(d.redemptionMs/l),h=Math.floor(d.preSpeechPadMs/l),m=Math.floor(d.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:h,minSpeechFrames:m}}class a{constructor(l,c,h,m){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=h,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=y=>{this.options={...this.options,...y};const{redemptionFrames:k,preSpeechPadFrames:x,minSpeechFrames:w}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=x,this.minSpeechFrames=w},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=y=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(y):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=y=>{const k=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(k.reduce((S,C)=>C.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(C=>C.frame));y({msg:e.Message.SpeechEnd,audio:S})}else y({msg:e.Message.VADMisfire});return{}},this.process=async(y,k)=>{if(!this.active)return;const x=await this.modelProcessFunc(y),w=x.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:x,msg:e.Message.FrameProcessed,frame:y}),this.audioBuffer.push({frame:y,isSpeech:w}),w&&(this.speechFrameCount++,this.redemptionCounter=0),w&&!this.speaking&&(this.speaking=!0,k({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,k({msg:e.Message.SpeechRealStart})),x.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const S=this.audioBuffer;if(this.audioBuffer=[],S.reduce((T,N)=>N.isSpeech?T+1:T,0)>=this.minSpeechFrames){const T=r(S.map(N=>N.frame));k({msg:e.Message.SpeechEnd,audio:T})}else k({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:f,preSpeechPadFrames:b,minSpeechFrames:_}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=_,this.reset()}}return Nl.FrameProcessor=a,Nl}var Dl={};function Eo(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var hw={exports:{}};/*!
48
48
  * ONNX Runtime Web v1.26.0
49
49
  * Copyright (c) Microsoft Corporation. All rights reserved.
50
50
  * Licensed under the MIT License.
@@ -2898,7 +2898,7 @@ ${L}`,G=E.createShaderModule({code:z,label:u.name});dn("verbose",()=>`[WebGPU] $
2898
2898
  * ONNX Runtime Web v1.26.0
2899
2899
  * Copyright (c) Microsoft Corporation. All rights reserved.
2900
2900
  * Licensed under the MIT License.
2901
- */var dk;function RP(){return dk||(dk=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,l=(oe=>typeof Eo<"u"?Eo:typeof Proxy<"u"?new Proxy(oe,{get:(fe,we)=>(typeof Eo<"u"?Eo:fe)[we]}):oe)(function(oe){if(typeof Eo<"u")return Eo.apply(this,arguments);throw Error('Dynamic require of "'+oe+'" is not supported')}),c=(oe,fe)=>()=>(oe&&(fe=oe(oe=0)),fe),h=(oe,fe)=>{for(var we in fe)r(oe,we,{get:fe[we],enumerable:!0})},m=(oe,fe,we,De)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ee of a(fe))!d.call(oe,Ee)&&Ee!==we&&r(oe,Ee,{get:()=>fe[Ee],enumerable:!(De=s(fe,Ee))||De.enumerable});return oe},f=oe=>m(r({},"__esModule",{value:!0}),oe),b,_,y,k,x,w=c(()=>{b=new Map,_=[],y=(oe,fe,we)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let De=b.get(oe);if(De===void 0)b.set(oe,{backend:fe,priority:we});else{if(De.priority>we)return;if(De.priority===we&&De.backend!==fe)throw new Error(`cannot register backend "${oe}" using priority ${we}`)}if(we>=0){let Ee=_.indexOf(oe);Ee!==-1&&_.splice(Ee,1);for(let Be=0;Be<_.length;Be++)if(b.get(_[Be]).priority<=we){_.splice(Be,0,oe);return}_.push(oe)}return}throw new TypeError("not a valid backend")},k=async oe=>{let fe=b.get(oe);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let we=!!fe.initPromise;try{return we||(fe.initPromise=fe.backend.init(oe)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(De){return we||(fe.error=`${De}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},x=async oe=>{let fe=oe.executionProviders||[],we=fe.map(Ge=>typeof Ge=="string"?Ge:Ge.name),De=we.length===0?_:we,Ee,Be=[],$e=new Set;for(let Ge of De){let tt=await k(Ge);typeof tt=="string"?Be.push({name:Ge,err:tt}):(Ee||(Ee=tt),Ee===tt&&$e.add(Ge))}if(!Ee)throw new Error(`no available backend found. ERR: ${Be.map(Ge=>`[${Ge.name}] ${Ge.err}`).join(", ")}`);for(let{name:Ge,err:tt}of Be)we.includes(Ge)&&console.warn(`removing requested execution provider "${Ge}" from session options because it is not available: ${tt}`);let Pe=fe.filter(Ge=>$e.has(typeof Ge=="string"?Ge:Ge.name));return[Ee,new Proxy(oe,{get:(Ge,tt)=>tt==="executionProviders"?Pe:Reflect.get(Ge,tt)})]}}),S=c(()=>{w()}),C,T=c(()=>{C="1.26.0"}),N,A,P=c(()=>{T(),N="warning",A={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(oe){if(oe!==void 0){if(typeof oe!="string"||["verbose","info","warning","error","fatal"].indexOf(oe)===-1)throw new Error(`Unsupported logging level: ${oe}`);N=oe}},get logLevel(){return N}},Object.defineProperty(A,"logLevel",{enumerable:!0})}),I,O=c(()=>{P(),I=A}),H,B,Z=c(()=>{H=(oe,fe)=>{let we=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);we.width=oe.dims[3],we.height=oe.dims[2];let De=we.getContext("2d");if(De!=null){let Ee,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Be=oe.dims[3]):(Ee=oe.dims[3],Be=oe.dims[2]);let $e=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Pe=fe==null?void 0:fe.norm,Ge,tt;Pe===void 0||Pe.mean===void 0?Ge=[255,255,255,255]:typeof Pe.mean=="number"?Ge=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(Ge=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(Ge[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?tt=[0,0,0,0]:typeof Pe.bias=="number"?tt=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(tt=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(tt[3]=Pe.bias[3]));let st=Be*Ee,nt=0,Xe=st,$t=st*2,ze=-1;$e==="RGBA"?(nt=0,Xe=st,$t=st*2,ze=st*3):$e==="RGB"?(nt=0,Xe=st,$t=st*2):$e==="RBG"&&(nt=0,$t=st,Xe=st*2);for(let ut=0;ut<Be;ut++)for(let Rn=0;Rn<Ee;Rn++){let tn=(oe.data[nt++]-tt[0])*Ge[0],nn=(oe.data[Xe++]-tt[1])*Ge[1],In=(oe.data[$t++]-tt[2])*Ge[2],Bt=ze===-1?255:(oe.data[ze++]-tt[3])*Ge[3];De.fillStyle="rgba("+tn+","+nn+","+In+","+Bt+")",De.fillRect(Rn,ut,1,1)}if("toDataURL"in we)return we.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},B=(oe,fe)=>{let we=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(we!=null){let Ee,Be,$e;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Be=oe.dims[1],$e=oe.dims[3]):(Ee=oe.dims[3],Be=oe.dims[2],$e=oe.dims[1]);let Pe=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Ge=fe==null?void 0:fe.norm,tt,st;Ge===void 0||Ge.mean===void 0?tt=[255,255,255,255]:typeof Ge.mean=="number"?tt=[Ge.mean,Ge.mean,Ge.mean,Ge.mean]:(tt=[Ge.mean[0],Ge.mean[1],Ge.mean[2],255],Ge.mean[3]!==void 0&&(tt[3]=Ge.mean[3])),Ge===void 0||Ge.bias===void 0?st=[0,0,0,0]:typeof Ge.bias=="number"?st=[Ge.bias,Ge.bias,Ge.bias,Ge.bias]:(st=[Ge.bias[0],Ge.bias[1],Ge.bias[2],0],Ge.bias[3]!==void 0&&(st[3]=Ge.bias[3]));let nt=Be*Ee;if(fe!==void 0&&(fe.format!==void 0&&$e===4&&fe.format!=="RGBA"||$e===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,$t=0,ze=1,ut=2,Rn=3,tn=0,nn=nt,In=nt*2,Bt=-1;Pe==="RGBA"?(tn=0,nn=nt,In=nt*2,Bt=nt*3):Pe==="RGB"?(tn=0,nn=nt,In=nt*2):Pe==="RBG"&&(tn=0,In=nt,nn=nt*2),De=we.createImageData(Ee,Be);for(let Bn=0;Bn<Be*Ee;$t+=Xe,ze+=Xe,ut+=Xe,Rn+=Xe,Bn++)De.data[$t]=(oe.data[tn++]-st[0])*tt[0],De.data[ze]=(oe.data[nn++]-st[1])*tt[1],De.data[ut]=(oe.data[In++]-st[2])*tt[2],De.data[Rn]=Bt===-1?255:(oe.data[Bt++]-st[3])*tt[3]}else throw new Error("Can not access image data");return De}}),Q,W,Y,ee,re,se,F=c(()=>{me(),Q=(oe,fe)=>{if(oe===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:we,width:De}=fe,Ee=fe.norm??{mean:255,bias:0},Be,$e;typeof Ee.mean=="number"?Be=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:Be=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?$e=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:$e=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let Pe=fe.format!==void 0?fe.format:"RGBA",Ge=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",tt=we*De,st=Ge==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),nt=4,Xe=0,$t=1,ze=2,ut=3,Rn=0,tn=tt,nn=tt*2,In=-1;Pe==="RGB"&&(nt=3,Xe=0,$t=1,ze=2,ut=-1),Ge==="RGBA"?In=tt*3:Ge==="RBG"?(Rn=0,nn=tt,tn=tt*2):Ge==="BGR"&&(nn=0,tn=tt,Rn=tt*2);for(let Bt=0;Bt<tt;Bt++,Xe+=nt,ze+=nt,$t+=nt,ut+=nt)st[Rn++]=(oe[Xe]+$e[0])/Be[0],st[tn++]=(oe[$t]+$e[1])/Be[1],st[nn++]=(oe[ze]+$e[2])/Be[2],In!==-1&&ut!==-1&&(st[In++]=(oe[ut]+$e[3])/Be[3]);return Ge==="RGBA"?new J("float32",st,[1,4,we,De]):new J("float32",st,[1,3,we,De])},W=async(oe,fe)=>{let we=typeof HTMLImageElement<"u"&&oe instanceof HTMLImageElement,De=typeof ImageData<"u"&&oe instanceof ImageData,Ee=typeof ImageBitmap<"u"&&oe instanceof ImageBitmap,Be=typeof oe=="string",$e,Pe=fe??{},Ge=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=st=>typeof HTMLCanvasElement<"u"&&st instanceof HTMLCanvasElement||st instanceof OffscreenCanvas?st.getContext("2d"):null;if(we){let st=Ge();st.width=oe.width,st.height=oe.height;let nt=tt(st);if(nt!=null){let Xe=oe.height,$t=oe.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,$t=fe.resizedWidth),fe!==void 0){if(Pe=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t}else Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t;nt.drawImage(oe,0,0),$e=nt.getImageData(0,0,$t,Xe).data}else throw new Error("Can not access image data")}else if(De){let st,nt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(st=fe.resizedHeight,nt=fe.resizedWidth):(st=oe.height,nt=oe.width),fe!==void 0&&(Pe=fe),Pe.format="RGBA",Pe.height=st,Pe.width=nt,fe!==void 0){let Xe=Ge();Xe.width=nt,Xe.height=st;let $t=tt(Xe);if($t!=null)$t.putImageData(oe,0,0),$e=$t.getImageData(0,0,nt,st).data;else throw new Error("Can not access image data")}else $e=oe.data}else if(Ee){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let st=Ge();st.width=oe.width,st.height=oe.height;let nt=tt(st);if(nt!=null){let Xe=oe.height,$t=oe.width;return nt.drawImage(oe,0,0,$t,Xe),$e=nt.getImageData(0,0,$t,Xe).data,Pe.height=Xe,Pe.width=$t,Q($e,Pe)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((st,nt)=>{let Xe=Ge(),$t=tt(Xe);if(!oe||!$t)return nt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=oe,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,$t.drawImage(ze,0,0,Xe.width,Xe.height);let ut=$t.getImageData(0,0,Xe.width,Xe.height);Pe.height=Xe.height,Pe.width=Xe.width,st(Q(ut.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Q($e,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},Y=(oe,fe)=>{let{width:we,height:De,download:Ee,dispose:Be}=fe,$e=[1,De,we,4];return new J({location:"texture",type:"float32",texture:oe,dims:$e,download:Ee,dispose:Be})},ee=(oe,fe)=>{let{dataType:we,dims:De,download:Ee,dispose:Be}=fe;return new J({location:"gpu-buffer",type:we??"float32",gpuBuffer:oe,dims:De,download:Ee,dispose:Be})},re=(oe,fe)=>{let{dataType:we,dims:De,download:Ee,dispose:Be}=fe;return new J({location:"ml-tensor",type:we??"float32",mlTensor:oe,dims:De,download:Ee,dispose:Be})},se=(oe,fe,we)=>new J({location:"cpu-pinned",type:oe,data:fe,dims:we??[fe.length]})}),te,q,le,ae,be=c(()=>{te=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ae=()=>{if(!le){le=!0;let oe=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,we=globalThis.Float16Array,De=typeof we<"u"&&we.from;oe&&(te.set("int64",BigInt64Array),q.set(BigInt64Array,"int64")),fe&&(te.set("uint64",BigUint64Array),q.set(BigUint64Array,"uint64")),De?(te.set("float16",we),q.set(we,"float16")):te.set("float16",Uint16Array)}}}),Ne,Se,ce=c(()=>{me(),Ne=oe=>{let fe=1;for(let we=0;we<oe.length;we++){let De=oe[we];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${we}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${we}] must be a non-negative integer, got: ${De}`);fe*=De}return fe},Se=(oe,fe)=>{switch(oe.location){case"cpu":return new J(oe.type,oe.data,fe);case"cpu-pinned":return new J({location:"cpu-pinned",data:oe.data,type:oe.type,dims:fe});case"texture":return new J({location:"texture",texture:oe.texture,type:oe.type,dims:fe});case"gpu-buffer":return new J({location:"gpu-buffer",gpuBuffer:oe.gpuBuffer,type:oe.type,dims:fe});case"ml-tensor":return new J({location:"ml-tensor",mlTensor:oe.mlTensor,type:oe.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${oe.location} is not supported`)}}}),J,me=c(()=>{Z(),F(),be(),ce(),J=class{constructor(oe,fe,we){ae();let De,Ee;if(typeof oe=="object"&&"location"in oe)switch(this.dataLocation=oe.location,De=oe.type,Ee=oe.dims,oe.location){case"cpu-pinned":{let $e=te.get(De);if(!$e)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(oe.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=oe.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=oe.texture,this.downloader=oe.download,this.disposer=oe.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=oe.gpuBuffer,this.downloader=oe.download,this.disposer=oe.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=oe.mlTensor,this.downloader=oe.download,this.disposer=oe.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $e,Pe;if(typeof oe=="string")if(De=oe,Pe=we,oe==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");$e=fe}else{let Ge=te.get(oe);if(Ge===void 0)throw new TypeError(`Unsupported tensor type: ${oe}.`);if(Array.isArray(fe)){if(oe==="float16"&&Ge===Uint16Array||oe==="uint4"||oe==="int4")throw new TypeError(`Creating a ${oe} tensor from number array is not supported. Please use ${Ge.name} as data.`);oe==="uint64"||oe==="int64"?$e=Ge.from(fe,BigInt):$e=Ge.from(fe)}else if(fe instanceof Ge)$e=fe;else if(fe instanceof Uint8ClampedArray)if(oe==="uint8")$e=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(oe==="float16"&&fe instanceof Uint16Array&&Ge!==Uint16Array)$e=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Ge}`)}else if(Pe=fe,Array.isArray(oe)){if(oe.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Ge=typeof oe[0];if(Ge==="string")De="string",$e=oe;else if(Ge==="boolean")De="bool",$e=Uint8Array.from(oe);else throw new TypeError(`Invalid element type of data array: ${Ge}.`)}else if(oe instanceof Uint8ClampedArray)De="uint8",$e=Uint8Array.from(oe);else{let Ge=q.get(oe.constructor);if(Ge===void 0)throw new TypeError(`Unsupported type for tensor data: ${oe.constructor}.`);De=Ge,$e=oe}if(Pe===void 0)Pe=[$e.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");Ee=Pe,this.cpuData=$e,this.dataLocation="cpu"}let Be=Ne(Ee);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="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=De,this.dims=Ee,this.size=Be}static async fromImage(oe,fe){return W(oe,fe)}static fromTexture(oe,fe){return Y(oe,fe)}static fromGpuBuffer(oe,fe){return ee(oe,fe)}static fromMLTensor(oe,fe){return re(oe,fe)}static fromPinnedBuffer(oe,fe,we){return se(oe,fe,we)}toDataURL(oe){return H(this,oe)}toImageData(oe){return B(this,oe)}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(oe){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,oe&&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(oe){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,oe)}}}),ge,Fe=c(()=>{me(),ge=J}),Je,dt,zt,pt,it,ot,Dt=c(()=>{P(),Je=(oe,fe)=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeStamp(`${oe}::ORT::${fe}`)},dt=(oe,fe)=>{var Ee;let we=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<we.length;Be++){if(De&&!we[Be].includes("TRACE_FUNC")){let $e=`FUNC_${oe}::${we[Be].trim().split(" ")[1]}`;fe&&($e+=`::${fe}`),Je("CPU",$e);return}we[Be].includes("TRACE_FUNC")&&(De=!0)}},zt=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||dt("BEGIN",oe)},pt=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||dt("END",oe)},it=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.time(`ORT::${oe}`)},ot=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeEnd(`ORT::${oe}`)}}),on,gn=c(()=>{w(),Fe(),Dt(),on=class Zj{constructor(fe){this.handler=fe}async run(fe,we,De){zt(),it("InferenceSession.run");let Ee={},Be={};if(typeof fe!="object"||fe===null||fe instanceof ge||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof we=="object"){if(we===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(we instanceof ge)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(we)){if(we.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let tt of we){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);Ee[tt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,st=Object.getOwnPropertyNames(we);for(let nt of this.outputNames)if(st.indexOf(nt)!==-1){let Xe=we[nt];(Xe===null||Xe instanceof ge)&&(tt=!0,$e=!1,Ee[nt]=Xe)}if(tt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=we}}else if(typeof we<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof fe[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)Ee[tt]=null;let Pe=await this.handler.run(fe,Ee,Be),Ge={};for(let tt in Pe)if(Object.hasOwnProperty.call(Pe,tt)){let st=Pe[tt];st instanceof ge?Ge[tt]=st:Ge[tt]=new ge(st.type,st.data,st.dims)}return ot("InferenceSession.run"),pt(),Ge}async release(){return this.handler.dispose()}static async create(fe,we,De,Ee){zt(),it("InferenceSession.create");let Be,$e={};if(typeof fe=="string"){if(Be=fe,typeof we=="object"&&we!==null)$e=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof we=="object"&&we!==null)$e=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let st=fe,nt=0,Xe=fe.byteLength;if(typeof we=="object"&&we!==null)$e=we;else if(typeof we=="number"){if(nt=we,!Number.isSafeInteger(nt))throw new RangeError("'byteOffset' must be an integer.");if(nt<0||nt>=st.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${st.byteLength}).`);if(Xe=fe.byteLength-nt,typeof De=="number"){if(Xe=De,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||nt+Xe>st.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${st.byteLength-nt}].`);if(typeof Ee=="object"&&Ee!==null)$e=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof we<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(st,nt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,Ge]=await x($e),tt=await Pe.createInferenceSessionHandler(Be,Ge);return ot("InferenceSession.create"),pt(),new Zj(tt)}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}}}),Ze,Ct=c(()=>{gn(),Ze=on}),xt=c(()=>{}),pn=c(()=>{}),$n=c(()=>{}),er=c(()=>{}),yr={};h(yr,{InferenceSession:()=>Ze,TRACE:()=>Je,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>ge,env:()=>I,registerBackend:()=>y});var vn=c(()=>{S(),O(),Ct(),Fe(),xt(),pn(),Dt(),$n(),er()}),Hi=c(()=>{}),Xn={};h(Xn,{default:()=>Rs});var di,xn,Rs,nl=c(()=>{var oe;_e(),ir(),nr(),di="ort-wasm-proxy-worker",xn=((oe=globalThis.self)==null?void 0:oe.name)===di,xn&&(self.onmessage=fe=>{let{type:we,in:De}=fe.data;try{switch(we){case"init-wasm":gs(De.wasm).then(()=>{va(De).then(()=>{postMessage({type:we})},Ee=>{postMessage({type:we,err:Ee})})},Ee=>{postMessage({type:we,err:Ee})});break;case"init-ep":{let{epName:Ee,env:Be}=De;Fs(Be,Ee).then(()=>{postMessage({type:we})},$e=>{postMessage({type:we,err:$e})});break}case"copy-from":{let{buffer:Ee}=De,Be=dn(Ee);postMessage({type:we,out:Be});break}case"create":{let{model:Ee,options:Be}=De;Cr(Ee,Be).then($e=>{postMessage({type:we,out:$e})},$e=>{postMessage({type:we,err:$e})});break}case"release":ao(De),postMessage({type:we});break;case"run":{let{sessionId:Ee,inputIndices:Be,inputs:$e,outputIndices:Pe,options:Ge}=De;Ye(Ee,Be,$e,Pe,new Array(Pe.length).fill(null),Ge).then(tt=>{tt.some(st=>st[3]!=="cpu")?postMessage({type:we,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:we,out:tt},mt([...$e,...tt]))},tt=>{postMessage({type:we,err:tt})});break}case"end-profiling":sr(De),postMessage({type:we});break;default:}}catch(Ee){postMessage({type:we,err:Ee})}}),Rs=xn?null:fe=>new Worker(fe??kn,{type:"classic",name:di})}),ma,Is,kn,tr,ui,Ms,qr,wr,ro,Os,Ls,Kr,Wi,nr=c(()=>{Hi(),ma=typeof location>"u"?void 0:location.origin,Is=()=>{var oe,fe;return typeof document<"u"?(oe=document.currentScript)==null?void 0:oe.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},kn=Is(),tr=()=>{if(kn&&!kn.startsWith("blob:"))return kn.substring(0,kn.lastIndexOf("/")+1)},ui=(oe,fe)=>{try{let we=fe??kn;return(we?new URL(oe,we):new URL(oe)).origin===ma}catch{return!1}},Ms=(oe,fe)=>{let we=fe??kn;try{return(we?new URL(oe,we):new URL(oe)).href}catch{return}},qr=(oe,fe)=>`${fe??"./"}${oe}`,wr=async oe=>{let fe=await(await fetch(oe,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},ro=async oe=>(await import(oe)).default,Os=(nl(),f(Xn)).default,Ls=async()=>{if(!kn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ui(kn))return[void 0,Os()];let oe=await wr(kn);return[oe,Os(oe)]},Kr=void 0,Wi=async(oe,fe,we,De)=>{let Ee=Kr&&!(oe||fe);if(Ee)if(kn)Ee=ui(kn)||De&&!we;else if(De&&!we)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Kr];{let Be="ort-wasm-simd-threaded.mjs",$e=oe??Ms(Be,fe),Pe=we&&$e&&!ui($e,fe),Ge=Pe?await wr($e):$e??qr(Be,fe);return[Pe?Ge:void 0,await ro(Ge)]}}}),ps,Vi,_r,Br,$o,fs,ms,gs,Gt,ir=c(()=>{nr(),Vi=!1,_r=!1,Br=!1,$o=()=>{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}},fs=()=>{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}},ms=()=>{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}},gs=async oe=>{if(Vi)return Promise.resolve();if(_r)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");_r=!0;let fe=oe.initTimeout,we=oe.numThreads;if(oe.simd!==!1){if(oe.simd==="relaxed"){if(!ms())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!fs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=$o();we>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+we+", 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."),oe.numThreads=we=1);let Ee=oe.wasmPaths,Be=typeof Ee=="string"?Ee:void 0,$e=Ee==null?void 0:Ee.mjs,Pe=($e==null?void 0:$e.href)??$e,Ge=Ee==null?void 0:Ee.wasm,tt=(Ge==null?void 0:Ge.href)??Ge,st=oe.wasmBinary,[nt,Xe]=await Wi(Pe,Be,we>1,!!st||!!tt),$t=!1,ze=[];if(fe>0&&ze.push(new Promise(ut=>{setTimeout(()=>{$t=!0,ut()},fe)})),ze.push(new Promise((ut,Rn)=>{let tn={numThreads:we};if(st)tn.wasmBinary=st,tn.locateFile=nn=>nn;else if(tt||Be)tn.locateFile=nn=>tt??Be+nn;else if(Pe&&Pe.indexOf("blob:")!==0)tn.locateFile=nn=>new URL(nn,Pe).href;else if(nt){let nn=tr();nn&&(tn.locateFile=In=>nn+In)}Xe(tn).then(nn=>{_r=!1,Vi=!0,ps=nn,ut(),nt&&URL.revokeObjectURL(nt)},nn=>{_r=!1,Br=!0,Rn(nn)})})),await Promise.race(ze),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},Gt=()=>{if(Vi&&ps)return ps;throw new Error("WebAssembly is not initialized yet.")}}),Jn,Nn,Et,so=c(()=>{ir(),Jn=(oe,fe)=>{let we=Gt(),De=we.lengthBytesUTF8(oe)+1,Ee=we._malloc(De);return we.stringToUTF8(oe,Ee,De),fe.push(Ee),Ee},Nn=(oe,fe,we,De)=>{if(typeof oe=="object"&&oe!==null){if(we.has(oe))throw new Error("Circular reference in options");we.add(oe)}Object.entries(oe).forEach(([Ee,Be])=>{let $e=fe?fe+Ee:Ee;if(typeof Be=="object")Nn(Be,$e+".",we,De);else if(typeof Be=="string"||typeof Be=="number")De($e,Be.toString());else if(typeof Be=="boolean")De($e,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Et=oe=>{let fe=Gt(),we=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetLastError(Ee,Ee+De);let Be=Number(fe.getValue(Ee,De===4?"i32":"i64")),$e=fe.getValue(Ee+De,"*"),Pe=$e?fe.UTF8ToString($e):"";throw new Error(`${oe} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Pe}`)}finally{fe.stackRestore(we)}}}),Po,il=c(()=>{ir(),so(),Po=oe=>{let fe=Gt(),we=0,De=[],Ee=oe||{};try{if((oe==null?void 0:oe.logSeverityLevel)===void 0)Ee.logSeverityLevel=2;else if(typeof oe.logSeverityLevel!="number"||!Number.isInteger(oe.logSeverityLevel)||oe.logSeverityLevel<0||oe.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${oe.logSeverityLevel}`);if((oe==null?void 0:oe.logVerbosityLevel)===void 0)Ee.logVerbosityLevel=0;else if(typeof oe.logVerbosityLevel!="number"||!Number.isInteger(oe.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${oe.logVerbosityLevel}`);(oe==null?void 0:oe.terminate)===void 0&&(Ee.terminate=!1);let Be=0;return(oe==null?void 0:oe.tag)!==void 0&&(Be=Jn(oe.tag,De)),we=fe._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,Be),we===0&&Et("Can't create run options."),(oe==null?void 0:oe.extra)!==void 0&&Nn(oe.extra,"",new WeakSet,($e,Pe)=>{let Ge=Jn($e,De),tt=Jn(Pe,De);fe._OrtAddRunConfigEntry(we,Ge,tt)!==0&&Et(`Can't set a run config entry: ${$e} - ${Pe}.`)}),[we,De]}catch(Be){throw we!==0&&fe._OrtReleaseRunOptions(we),De.forEach($e=>fe._free($e)),Be}}}),Ro,Io,ga,Li,rl,sl,Dn=c(()=>{ir(),so(),Ro=oe=>{switch(oe){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: ${oe}`)}},Io=oe=>{switch(oe){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${oe}`)}},ga=oe=>{oe.extra||(oe.extra={}),oe.extra.session||(oe.extra.session={});let fe=oe.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),oe.executionProviders&&oe.executionProviders.some(we=>(typeof we=="string"?we:we.name)==="webgpu")&&(oe.enableMemPattern=!1)},Li=(oe,fe,we,De)=>{let Ee=Jn(fe,De),Be=Jn(we,De);Gt()._OrtAddSessionConfigEntry(oe,Ee,Be)!==0&&Et(`Can't set a session config entry: ${fe} - ${we}.`)},rl=async(oe,fe,we)=>{let De=fe.executionProviders;for(let Ee of De){let Be=typeof Ee=="string"?Ee:Ee.name,$e=[];switch(Be){case"webnn":if(Be="WEBNN",Li(oe,"session.disable_quant_qdq","1",we),Li(oe,"session.disable_qdq_constant_folding","1",we),typeof Ee!="string"){let nt=Ee==null?void 0:Ee.deviceType;nt&&Li(oe,"deviceType",nt,we)}break;case"webgpu":if(Be="JS",typeof Ee!="string"){let nt=Ee;if(nt!=null&&nt.preferredLayout){if(nt.preferredLayout!=="NCHW"&&nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${nt.preferredLayout}`);Li(oe,"preferredLayout",nt.preferredLayout,we)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Pe=Jn(Be,we),Ge=$e.length,tt=0,st=0;if(Ge>0){tt=Gt()._malloc(Ge*Gt().PTR_SIZE),we.push(tt),st=Gt()._malloc(Ge*Gt().PTR_SIZE),we.push(st);for(let nt=0;nt<Ge;nt++)Gt().setValue(tt+nt*Gt().PTR_SIZE,$e[nt][0],"*"),Gt().setValue(st+nt*Gt().PTR_SIZE,$e[nt][1],"*")}await Gt()._OrtAppendExecutionProvider(oe,Pe,tt,st,Ge)!==0&&Et(`Can't append execution provider: ${Be}.`)}},sl=async oe=>{let fe=Gt(),we=0,De=[],Ee=oe||{};ga(Ee);try{let Be=Ro(Ee.graphOptimizationLevel??"all"),$e=Io(Ee.executionMode??"sequential"),Pe=typeof Ee.logId=="string"?Jn(Ee.logId,De):0,Ge=Ee.logSeverityLevel??2;if(!Number.isInteger(Ge)||Ge<0||Ge>4)throw new Error(`log severity level is not valid: ${Ge}`);let tt=Ee.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let st=typeof Ee.optimizedModelFilePath=="string"?Jn(Ee.optimizedModelFilePath,De):0;if(we=fe._OrtCreateSessionOptions(Be,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,$e,!!Ee.enableProfiling,0,Pe,Ge,tt,st),we===0&&Et("Can't create session options."),Ee.executionProviders&&await rl(we,Ee,De),Ee.enableGraphCapture!==void 0){if(typeof Ee.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ee.enableGraphCapture}`);Li(we,"enableGraphCapture",Ee.enableGraphCapture.toString(),De)}if(Ee.freeDimensionOverrides)for(let[nt,Xe]of Object.entries(Ee.freeDimensionOverrides)){if(typeof nt!="string")throw new Error(`free dimension override name must be a string: ${nt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let $t=Jn(nt,De);fe._OrtAddFreeDimensionOverride(we,$t,Xe)!==0&&Et(`Can't set a free dimension override: ${nt} - ${Xe}.`)}return Ee.extra!==void 0&&Nn(Ee.extra,"",new WeakSet,(nt,Xe)=>{Li(we,nt,Xe,De)}),[we,De]}catch(Be){throw we!==0&&fe._OrtReleaseSessionOptions(we)!==0&&Et("Can't release session options."),De.forEach($e=>fe._free($e)),Be}}}),qi,ei,Ki,vs,oo,zs,Sr,Ni,Ut=c(()=>{qi=oe=>{switch(oe){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: ${oe}`)}},ei=oe=>{switch(oe){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: ${oe}`)}},Ki=(oe,fe)=>{let we=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][oe],De=typeof fe=="number"?fe:fe.reduce((Ee,Be)=>Ee*Be,1);return we>0?Math.ceil(De*we):void 0},vs=oe=>{switch(oe){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: ${oe}`)}},oo=oe=>{switch(oe){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: ${oe}`)}},zs=oe=>oe==="float32"||oe==="float16"||oe==="int32"||oe==="int64"||oe==="uint32"||oe==="uint8"||oe==="bool"||oe==="uint4"||oe==="int4",Sr=oe=>oe==="float32"||oe==="float16"||oe==="int32"||oe==="int64"||oe==="uint32"||oe==="uint64"||oe==="int8"||oe==="uint8"||oe==="bool"||oe==="uint4"||oe==="int4",Ni=oe=>{switch(oe){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: ${oe}`)}}}),ti,Bs=c(()=>{Hi(),ti=async oe=>{if(typeof oe=="string"){let fe=await fetch(oe);if(!fe.ok)throw new Error(`failed to load external data file: ${oe}`);let we=fe.headers.get("Content-Length"),De=we?parseInt(we,10):0;if(De<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${oe}, no response body.`);let Ee=fe.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch(Pe){if(Pe instanceof RangeError){let Ge=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Ge,maximum:Ge}).buffer}else throw Pe}let $e=0;for(;;){let{done:Pe,value:Ge}=await Ee.read();if(Pe)break;let tt=Ge.byteLength;new Uint8Array(Be,$e,tt).set(Ge),$e+=tt}return new Uint8Array(Be,0,De)}}else return oe instanceof Blob?new Uint8Array(await oe.arrayBuffer()):oe instanceof Uint8Array?oe:new Uint8Array(oe)}}),kr,va,Fs,rr,Yr,Gs,dn,Cr,ao,Fr,Ye,sr,mt,_e=c(()=>{vn(),il(),Dn(),Ut(),ir(),so(),Bs(),kr=(oe,fe)=>{Gt()._OrtInit(oe,fe)!==0&&Et("Can't initialize onnxruntime.")},va=async oe=>{kr(oe.wasm.numThreads,oo(oe.logLevel))},Fs=async(oe,fe)=>{var De,Ee;(Ee=(De=Gt()).asyncInit)==null||Ee.call(De);let we=oe.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(we){if(typeof we.limits!="object"||typeof we.features!="object"||typeof we.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=oe.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let $e=oe.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(we=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:$e}),!we)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")},rr=new Map,Yr=oe=>{let fe=Gt(),we=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetInputOutputCount(oe,Ee,Ee+De)!==0&&Et("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(fe.getValue(Ee,Be)),Number(fe.getValue(Ee+De,Be))]}finally{fe.stackRestore(we)}},Gs=(oe,fe)=>{let we=Gt(),De=we.stackSave(),Ee=0;try{let Be=we.PTR_SIZE,$e=we.stackAlloc(2*Be);we._OrtGetInputOutputMetadata(oe,fe,$e,$e+Be)!==0&&Et("Can't get session input/output metadata.");let Pe=Number(we.getValue($e,"*"));Ee=Number(we.getValue($e+Be,"*"));let Ge=we.HEAP32[Ee/4];if(Ge===0)return[Pe,0];let tt=we.HEAPU32[Ee/4+1],st=[];for(let nt=0;nt<tt;nt++){let Xe=Number(we.getValue(Ee+8+nt*Be,"*"));st.push(Xe!==0?we.UTF8ToString(Xe):Number(we.getValue(Ee+8+(nt+tt)*Be,"*")))}return[Pe,Ge,st]}finally{we.stackRestore(De),Ee!==0&&we._OrtFree(Ee)}},dn=oe=>{let fe=Gt(),we=fe._malloc(oe.byteLength);if(we===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${oe.byteLength}.`);return fe.HEAPU8.set(oe,we),[we,oe.byteLength]},Cr=async(oe,fe)=>{var st,nt,Xe;let we,De,Ee=Gt();Array.isArray(oe)?[we,De]=oe:oe.buffer===Ee.HEAPU8.buffer?[we,De]=[oe.byteOffset,oe.byteLength]:[we,De]=dn(oe);let Be=0,$e=0,Pe=[],Ge=[],tt=[];try{if([$e,Pe]=await sl(fe),(fe==null?void 0:fe.externalData)&&Ee.mountExternalData){let Bn=[];for(let fn of fe.externalData){let Di=typeof fn=="string"?fn:fn.path;Bn.push(ti(typeof fn=="string"?fn:fn.data).then(Yi=>{Ee.mountExternalData(Di,Yi)}))}await Promise.all(Bn)}for(let Bn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Bn=="string"?Bn:Bn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Bn!="string"){let fn=Bn,Di=fn==null?void 0:fn.context,Yi=fn==null?void 0:fn.gpuDevice,or=fn==null?void 0:fn.deviceType,al=fn==null?void 0:fn.powerPreference;Di?Ee.currentContext=Di:Yi?Ee.currentContext=await Ee.webnnCreateMLContext(Yi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:or,powerPreference:al})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}Be=await Ee._OrtCreateSession(we,De,$e),(st=Ee.webgpuOnCreateSession)==null||st.call(Ee,Be),Be===0&&Et("Can't create a session."),(nt=Ee.jsepOnCreateSession)==null||nt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(Be,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[$t,ze]=Yr(Be),ut=!!(fe!=null&&fe.enableGraphCapture),Rn=[],tn=[],nn=[],In=[],Bt=[];for(let Bn=0;Bn<$t;Bn++){let[fn,Di,Yi]=Gs(Be,Bn);fn===0&&Et("Can't get an input name."),Ge.push(fn);let or=Ee.UTF8ToString(fn);Rn.push(or),nn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}for(let Bn=0;Bn<ze;Bn++){let[fn,Di,Yi]=Gs(Be,Bn+$t);fn===0&&Et("Can't get an output name."),tt.push(fn);let or=Ee.UTF8ToString(fn);tn.push(or),In.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}return rr.set(Be,[Be,Ge,tt,null,ut,!1]),[Be,Rn,tn,nn,In]}catch($t){throw Ge.forEach(ze=>Ee._OrtFree(ze)),tt.forEach(ze=>Ee._OrtFree(ze)),Be!==0&&Ee._OrtReleaseSession(Be)!==0&&Et("Can't release session."),$t}finally{Ee._free(we),$e!==0&&Ee._OrtReleaseSessionOptions($e)!==0&&Et("Can't release session options."),Pe.forEach($t=>Ee._free($t)),(Xe=Ee.unmountExternalData)==null||Xe.call(Ee)}},ao=oe=>{var Ge,tt,st;let fe=Gt(),we=rr.get(oe);if(!we)throw new Error(`cannot release session. invalid session id: ${oe}`);let[De,Ee,Be,$e,Pe]=we;$e&&(Pe&&fe._OrtClearBoundOutputs($e.handle)!==0&&Et("Can't clear bound outputs."),fe._OrtReleaseBinding($e.handle)!==0&&Et("Can't release IO binding.")),(Ge=fe.jsepOnReleaseSession)==null||Ge.call(fe,oe),(tt=fe.webnnOnReleaseSession)==null||tt.call(fe,oe),(st=fe.webgpuOnReleaseSession)==null||st.call(fe,oe),Ee.forEach(nt=>fe._OrtFree(nt)),Be.forEach(nt=>fe._OrtFree(nt)),fe._OrtReleaseSession(De)!==0&&Et("Can't release session."),rr.delete(oe)},Fr=async(oe,fe,we,De,Ee,Be,$e=!1)=>{if(!oe){fe.push(0);return}let Pe=Gt(),Ge=Pe.PTR_SIZE,tt=oe[0],st=oe[1],nt=oe[3],Xe=nt,$t,ze;if(tt==="string"&&(nt==="gpu-buffer"||nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(nt==="gpu-buffer"){let tn=oe[2].gpuBuffer;ze=Ki(qi(tt),st);{let nn=Pe.jsepRegisterBuffer;if(!nn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=nn(De,Be,tn,ze)}}else if(nt==="ml-tensor"){let tn=oe[2].mlTensor;ze=Ki(qi(tt),st);let nn=Pe.webnnRegisterMLTensor;if(!nn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=nn(De,tn,qi(tt),st)}else{let tn=oe[2];if(Array.isArray(tn)){ze=Ge*tn.length,$t=Pe._malloc(ze),we.push($t);for(let nn=0;nn<tn.length;nn++){if(typeof tn[nn]!="string")throw new TypeError(`tensor data at index ${nn} is not a string`);Pe.setValue($t+nn*Ge,Jn(tn[nn],we),"*")}}else{let nn=Pe.webnnIsGraphInput,In=Pe.webnnIsGraphOutput;if(tt!=="string"&&nn&&In){let Bt=Pe.UTF8ToString(Ee);if(nn(De,Bt)||In(De,Bt)){let Bn=qi(tt);ze=Ki(Bn,st),Xe="ml-tensor";let fn=Pe.webnnCreateTemporaryTensor,Di=Pe.webnnUploadTensor;if(!fn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Yi=await fn(De,Bn,st);Di(Yi,new Uint8Array(tn.buffer,tn.byteOffset,tn.byteLength)),$t=Yi}else ze=tn.byteLength,$t=Pe._malloc(ze),we.push($t),Pe.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,ze),$t)}else ze=tn.byteLength,$t=Pe._malloc(ze),we.push($t),Pe.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,ze),$t)}}let ut=Pe.stackSave(),Rn=Pe.stackAlloc(4*st.length);try{st.forEach((nn,In)=>Pe.setValue(Rn+In*Ge,nn,Ge===4?"i32":"i64"));let tn=Pe._OrtCreateTensor(qi(tt),$t,ze,Rn,st.length,Ni(Xe));tn===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Be}.`),fe.push(tn)}finally{Pe.stackRestore(ut)}},Ye=async(oe,fe,we,De,Ee,Be)=>{var ar,ac,fd;let $e=Gt(),Pe=$e.PTR_SIZE,Ge=rr.get(oe);if(!Ge)throw new Error(`cannot run inference. invalid session id: ${oe}`);let tt=Ge[0],st=Ge[1],nt=Ge[2],Xe=Ge[3],$t=Ge[4];Ge[5];let ze=fe.length,ut=De.length,Rn=0,tn=[],nn=[],In=[],Bt=[],Bn=[],fn=$e.stackSave(),Di=$e.stackAlloc(ze*Pe),Yi=$e.stackAlloc(ze*Pe),or=$e.stackAlloc(ut*Pe),al=$e.stackAlloc(ut*Pe);try{[Rn,tn]=Po(Be),it("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)await Fr(we[hn],nn,Bt,oe,st[fe[hn]],fe[hn],$t);for(let hn=0;hn<ut;hn++)await Fr(Ee[hn],In,Bt,oe,nt[De[hn]],ze+De[hn],$t);ot("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)$e.setValue(Di+hn*Pe,nn[hn],"*"),$e.setValue(Yi+hn*Pe,st[fe[hn]],"*");for(let hn=0;hn<ut;hn++)$e.setValue(or+hn*Pe,In[hn],"*"),$e.setValue(al+hn*Pe,nt[De[hn]],"*");(ar=$e.jsepOnRunStart)==null||ar.call($e,tt),(ac=$e.webnnOnRunStart)==null||ac.call($e,tt);let Ai;Ai=await $e._OrtRun(tt,Yi,Di,ze,al,ut,or,Rn),Ai!==0&&Et("failed to call OrtRun().");let bs=[],md=[];it("wasm ProcessOutputTensor");for(let hn=0;hn<ut;hn++){let Jr=Number($e.getValue(or+hn*Pe,"*"));if(Jr===In[hn]||Bn.includes(In[hn])){bs.push(Ee[hn]),Jr!==In[hn]&&$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.");continue}let Fu=$e.stackSave(),Ws=$e.stackAlloc(4*Pe),xa=!1,vi,lr=0;try{$e._OrtGetTensorData(Jr,Ws,Ws+Pe,Ws+2*Pe,Ws+3*Pe)!==0&&Et(`Can't access output tensor data on index ${hn}.`);let lc=Pe===4?"i32":"i64",cr=Number($e.getValue(Ws,lc));lr=$e.getValue(Ws+Pe,"*");let gd=$e.getValue(Ws+Pe*2,"*"),Gu=Number($e.getValue(Ws+Pe*3,lc)),Vs=[];for(let xi=0;xi<Gu;xi++)Vs.push(Number($e.getValue(gd+xi*Pe,lc)));$e._OrtFree(gd)!==0&&Et("Can't free memory for tensor dims.");let Zr=Vs.reduce((xi,Zn)=>xi*Zn,1);vi=ei(cr);let ys=Xe==null?void 0:Xe.outputPreferredLocations[De[hn]];if(vi==="string"){if(ys==="gpu-buffer"||ys==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let xi=[];for(let Zn=0;Zn<Zr;Zn++){let Qr=$e.getValue(lr+Zn*Pe,"*"),vd=$e.getValue(lr+(Zn+1)*Pe,"*"),xd=Zn===Zr-1?void 0:vd-Qr;xi.push($e.UTF8ToString(Qr,xd))}bs.push([vi,Vs,xi,"cpu"])}else if(ys==="gpu-buffer"&&Zr>0){let xi=$e.jsepGetBuffer;if(!xi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Zn=xi(lr),Qr=Ki(cr,Zr);if(Qr===void 0||!zs(vi))throw new Error(`Unsupported data type: ${vi}`);xa=!0,bs.push([vi,Vs,{gpuBuffer:Zn,download:$e.jsepCreateDownloader(Zn,Qr,vi),dispose:()=>{$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(ys==="ml-tensor"&&Zr>0){let xi=$e.webnnEnsureTensor,Zn=$e.webnnIsGraphInputOutputTypeSupported;if(!xi||!Zn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ki(cr,Zr)===void 0||!Sr(vi))throw new Error(`Unsupported data type: ${vi}`);if(!Zn(oe,vi,!1))throw new Error(`preferredLocation "ml-tensor" for ${vi} output is not supported by current WebNN Context.`);let Qr=await xi(oe,lr,cr,Vs,!1);xa=!0,bs.push([vi,Vs,{mlTensor:Qr,download:$e.webnnCreateMLTensorDownloader(lr,vi),dispose:()=>{$e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr)}},"ml-tensor"])}else if(ys==="ml-tensor-cpu-output"&&Zr>0){let xi=$e.webnnCreateMLTensorDownloader(lr,vi)(),Zn=bs.length;xa=!0,md.push((async()=>{let Qr=[Zn,await xi];return $e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr),Qr})()),bs.push([vi,Vs,[],"cpu"])}else{let xi=vs(vi),Zn=new xi(Zr);new Uint8Array(Zn.buffer,Zn.byteOffset,Zn.byteLength).set($e.HEAPU8.subarray(lr,lr+Zn.byteLength)),bs.push([vi,Vs,Zn,"cpu"])}}finally{$e.stackRestore(Fu),vi==="string"&&lr&&$e._free(lr),xa||$e._OrtReleaseTensor(Jr)}}Xe&&!$t&&($e._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),rr.set(oe,[tt,st,nt,Xe,$t,!1]));for(let[hn,Jr]of await Promise.all(md))bs[hn][2]=Jr;return ot("wasm ProcessOutputTensor"),bs}finally{(fd=$e.webnnOnRunEnd)==null||fd.call($e,tt),$e.stackRestore(fn),nn.forEach(Ai=>$e._OrtReleaseTensor(Ai)),In.forEach(Ai=>$e._OrtReleaseTensor(Ai)),Bt.forEach(Ai=>$e._free(Ai)),Rn!==0&&$e._OrtReleaseRunOptions(Rn),tn.forEach(Ai=>$e._free(Ai))}},sr=oe=>{let fe=Gt(),we=rr.get(oe);if(!we)throw new Error("invalid session id");let De=we[0],Ee=fe._OrtEndProfiling(De);Ee===0&&Et("Can't get an profile file name."),fe._OrtFree(Ee)},mt=oe=>{let fe=[];for(let we of oe){let De=we[2];!Array.isArray(De)&&"buffer"in De&&fe.push(De.buffer)}return fe}}),Me,Qe,Tt,an,un,Ln,Mn,hi,Hn,gi,On,Xr,lo,Mo,xs,Bu,Oo,Lo,ud=c(()=>{vn(),_e(),ir(),nr(),Me=()=>!!I.wasm.proxy&&typeof document<"u",Tt=!1,an=!1,un=!1,hi=new Map,Hn=(oe,fe)=>{let we=hi.get(oe);we?we.push(fe):hi.set(oe,[fe])},gi=()=>{if(Tt||!an||un||!Qe)throw new Error("worker not ready")},On=oe=>{switch(oe.data.type){case"init-wasm":Tt=!1,oe.data.err?(un=!0,Mn[1](oe.data.err)):(an=!0,Mn[0]()),Ln&&(URL.revokeObjectURL(Ln),Ln=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=hi.get(oe.data.type);oe.data.err?fe.shift()[1](oe.data.err):fe.shift()[0](oe.data.out);break}}},Xr=async()=>{if(!an){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(un)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Me())return new Promise((oe,fe)=>{Qe==null||Qe.terminate(),Ls().then(([we,De])=>{try{Qe=De,Qe.onerror=Be=>fe(Be),Qe.onmessage=On,Mn=[oe,fe];let Ee={type:"init-wasm",in:I};if(!Ee.in.wasm.wasmPaths&&we){let Be=tr();Be&&(Ee.in.wasm.wasmPaths=Be)}Qe.postMessage(Ee),Ln=we}catch(Ee){fe(Ee)}},fe)});try{await gs(I.wasm),await va(I),an=!0}catch(oe){throw un=!0,oe}finally{Tt=!1}}},lo=async oe=>{if(Me())return gi(),new Promise((fe,we)=>{Hn("init-ep",[fe,we]);let De={type:"init-ep",in:{epName:oe,env:I}};Qe.postMessage(De)});await Fs(I,oe)},Mo=async oe=>Me()?(gi(),new Promise((fe,we)=>{Hn("copy-from",[fe,we]);let De={type:"copy-from",in:{buffer:oe}};Qe.postMessage(De,[oe.buffer])})):dn(oe),xs=async(oe,fe)=>{if(Me()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((we,De)=>{Hn("create",[we,De]);let Ee={type:"create",in:{model:oe,options:{...fe}}},Be=[];oe instanceof Uint8Array&&Be.push(oe.buffer),Qe.postMessage(Ee,Be)})}else return Cr(oe,fe)},Bu=async oe=>{if(Me())return gi(),new Promise((fe,we)=>{Hn("release",[fe,we]);let De={type:"release",in:oe};Qe.postMessage(De)});ao(oe)},Oo=async(oe,fe,we,De,Ee,Be)=>{if(Me()){if(we.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise(($e,Pe)=>{Hn("run",[$e,Pe]);let Ge=we,tt={type:"run",in:{sessionId:oe,inputIndices:fe,inputs:Ge,outputIndices:De,options:Be}};Qe.postMessage(tt,mt(Ge))})}else return Ye(oe,fe,we,De,Ee,Be)},Lo=async oe=>{if(Me())return gi(),new Promise((fe,we)=>{Hn("end-profiling",[fe,we]);let De={type:"end-profiling",in:oe};Qe.postMessage(De)});sr(oe)}}),ic,zo,ol,rc=c(()=>{vn(),ud(),Ut(),Hi(),Bs(),ic=(oe,fe)=>{switch(oe.location){case"cpu":return[oe.type,oe.dims,oe.data,"cpu"];case"gpu-buffer":return[oe.type,oe.dims,{gpuBuffer:oe.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[oe.type,oe.dims,{mlTensor:oe.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${oe.location} for ${fe()}`)}},zo=oe=>{switch(oe[3]){case"cpu":return new ge(oe[0],oe[2],oe[1]);case"gpu-buffer":{let fe=oe[0];if(!zs(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:we,download:De,dispose:Ee}=oe[2];return ge.fromGpuBuffer(we,{dataType:fe,dims:oe[1],download:De,dispose:Ee})}case"ml-tensor":{let fe=oe[0];if(!Sr(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:we,download:De,dispose:Ee}=oe[2];return ge.fromMLTensor(we,{dataType:fe,dims:oe[1],download:De,dispose:Ee})}default:throw new Error(`invalid data location: ${oe[3]}`)}},ol=class{async fetchModelAndCopyToWasmMemory(oe){return Mo(await ti(oe))}async loadModel(oe,fe){zt();let we;typeof oe=="string"?we=await this.fetchModelAndCopyToWasmMemory(oe):we=oe,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xs(we,fe),pt()}async dispose(){return Bu(this.sessionId)}async run(oe,fe,we){zt();let De=[],Ee=[];Object.entries(oe).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);De.push($t),Ee.push(ze)});let Be=[],$e=[];Object.entries(fe).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push($t),$e.push(ze)});let Pe=De.map((nt,Xe)=>ic(nt,()=>`input "${this.inputNames[Ee[Xe]]}"`)),Ge=Be.map((nt,Xe)=>nt?ic(nt,()=>`output "${this.outputNames[$e[Xe]]}"`):null),tt=await Oo(this.sessionId,Ee,Pe,$e,Ge,we),st={};for(let nt=0;nt<tt.length;nt++)st[this.outputNames[$e[nt]]]=Be[nt]??zo(tt[nt]);return pt(),st}startProfiling(){}endProfiling(){Lo(this.sessionId)}}}),Us={};h(Us,{OnnxruntimeWebAssemblyBackend:()=>Hs,initializeFlags:()=>co,wasmBackend:()=>Bo});var co,Hs,Bo,hd=c(()=>{vn(),ud(),rc(),co=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let oe=I.wasm.simd;if(typeof oe!="boolean"&&oe!==void 0&&oe!=="fixed"&&oe!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${oe}". 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"?l("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Hs=class{async init(oe){co(),await Xr(),await lo(oe)}async createInferenceSessionHandler(oe,fe){let we=new ol;return await we.loadModel(oe,fe),we}},Bo=new Hs}),pd={};h(pd,{InferenceSession:()=>Ze,TRACE:()=>Je,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>ge,default:()=>oc,env:()=>I,registerBackend:()=>y}),vn(),vn(),vn();var sc="1.26.0",oc=yr;{let oe=(hd(),f(Us)).wasmBackend;y("cpu",oe,10),y("wasm",oe,10)}return Object.defineProperty(I.versions,"web",{value:sc,enumerable:!0}),f(pd)})();n.exports=i})(fw)),fw.exports}var uk;function IP(){return uk||(uk=1,(function(n){var e=Al&&Al.__createBinding||(Object.create?(function(C,T,N,A){A===void 0&&(A=N);var P=Object.getOwnPropertyDescriptor(T,N);(!P||("get"in P?!T.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return T[N]}}),Object.defineProperty(C,A,P)}):(function(C,T,N,A){A===void 0&&(A=N),C[A]=T[N]})),i=Al&&Al.__setModuleDefault||(Object.create?(function(C,T){Object.defineProperty(C,"default",{enumerable:!0,value:T})}):function(C,T){C.default=T}),r=Al&&Al.__importStar||function(C){if(C&&C.__esModule)return C;var T={};if(C!=null)for(var N in C)N!=="default"&&Object.prototype.hasOwnProperty.call(C,N)&&e(T,C,N);return i(T,C),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(RP()),a=Q0(),d=e1(),l=sv(),c=ky(),h=Xj(),m=Jj();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",_="silero_vad_legacy.onnx",y=C=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.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 T=>{T.getTracks().forEach(N=>{N.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:T=>{T.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});n.getDefaultRealTimeVADOptions=y;const k=C=>"audioWorklet"in C&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(C,T,N,A,P){await N.audioWorklet.addModule(C),T.processorOptions={...T.processorOptions??{},frameSamples:A};const I=new AudioWorkletNode(N,"vad-helper-worklet",T);return I.port.onmessage=async O=>{const H=O.data;if(!(typeof H=="object"&&H&&"message"in H)){console.error("Invalid message event",H);return}switch(H.message){case c.Message.AudioFrame:{if(!("data"in H&&H.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const B=new Float32Array(H.data);await P(B);break}}},I}async function w(C,T,N){const A=new m.Resampler({nativeSampleRate:C.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const I=C.createScriptProcessor(4096,1,1);let O=!1;return I.onaudioprocess=async H=>{if(!O){O=!0;try{const B=H.inputBuffer.getChannelData(0);H.outputBuffer.getChannelData(0).fill(0);const Q=A.process(B);for(const W of Q)await N(W)}catch(B){console.error("Error processing audio:",B)}finally{O=!1}}},I.connect(C.destination),I}class S{constructor(T,N,A,P,I=!1,O=null,H=null,B=null,Z=null,Q=null,W=null,Y="uninitialized",ee=!1){this.options=T,this.frameProcessor=N,this.model=A,this.frameSamples=P,this.listening=I,this.errored=O,this._stream=H,this._audioContext=B,this._vadNode=Z,this._mediaStreamAudioSourceNode=Q,this._audioProcessorAdapterType=W,this.initializationState=Y,this.ownsAudioContext=ee,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=re=>{this.initializationState="errored",this.errored=re},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(re){throw re instanceof Error?this.setErrored(re.message):this.setErrored(String(re)),re}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"?k(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await w(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),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:re,audioContext:se,vadNode:F}=this.getAudioInstances();this._stream=await this.options.resumeStream(re);const te=new MediaStreamAudioSourceNode(se,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=te,te.connect(F);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:re,mediaStreamAudioSourceNode:se}=this.getAudioInstances();await this.options.pauseStream(re),se.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var se;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:re}=this.getAudioInstances();re instanceof AudioWorkletNode&&re.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((se=this._audioContext)==null?void 0:se.close())},this.setOptions=re=>{this.frameProcessor.setOptions(re)},this.processFrame=async re=>{await this.frameProcessor.process(re,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=re=>{switch(re.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(re.probs,re.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(re.audio);break}}}static async new(T={}){const N={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,d.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const A=N.model==="v5"?b:_,P=N.baseAssetPath+A,I=N.model==="v5"?h.SileroV5.new:h.SileroLegacy.new;let O;try{O=await I(n.ort,()=>(0,a.defaultModelFetcher)(P))}catch(W){throw console.error(`Encountered an error while loading model file ${P}`),W}const H=N.model==="v5"?512:1536,B=H/16,Z=new d.FrameProcessor(O.process,O.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},B),Q=new S(N,Z,O,H);if(N.startOnLoad)try{await Q.start()}catch(W){throw console.error("Error starting micVad",W),W}return Q}}n.MicVAD=S})(Al)),Al}var hk;function MP(){return hk||(hk=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=qj();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=Q0();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=e1();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=ky();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=$P();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const d=PP();n.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var l=IP();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(uw)),uw}var OP=MP();function vx(n,e,i,r,s){var d,l;try{(l=(d=window.api)==null?void 0:d.logs)==null||l.write(n,e,i,r,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?a(`[${n}]`,i,r):a(`[${n}]`,i)}const ht={debug:(n,e,i)=>vx(n,"debug",e,i),info:(n,e,i)=>vx(n,"info",e,i),warn:(n,e,i)=>vx(n,"warn",e,i),error:(n,e,i,r)=>vx(n,"error",e,i,r)},Qj=16e3,LP=6,wp=Qj*LP,zP=400,BP=Qj*zP/1e3,pk=300,fk=2e3,mk=1500,gk=3e3,FP=600,eT=.5,tT=.35,vk=.85,xk=.7;let As=null,Ka=!1,cs=!1;const j_=new Set;function xx(n){for(const e of Array.from(j_))try{e(n)}catch(i){ht.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let mw=0;const bk=2;let Mp=!1,nT=!1;function iT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";ht[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{ht.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),GP(`error:${e.message||"unknown"}`)})}function Mb(){return As||(As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),iT(As),ht.info("speech","worker spawned"),As)}let bx=!1;function GP(n){if(!Mp){if(bx){ht.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(bx=!0,mw+=1,nT=!0,ht.warn("speech","respawnWorker: starting",{reason:n,attempt:mw}),xx({reason:n,respawned:!1,finalOnly:!0}),mw>bk){if(Mp=!0,ht.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:bk}),As)try{As.terminate()}catch{}As=null,Ka=!1,cs=!1,xx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),bx=!1;return}if(As)try{As.terminate()}catch{}As=null,Ka=!1,cs=!1;try{As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),iT(As),cs=!0,As.postMessage({type:"load"}),ht.info("speech","respawnWorker: new worker spawned, load posted"),xx({reason:n,respawned:!0,finalOnly:!0})}catch(e){Mp=!0,ht.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),xx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{bx=!1}}}function UP(n,e){if(Ka||cs)return;cs=!0;const i=Mb();ht.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(Ka=!0,cs=!1,ht.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(cs=!1,ht.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),i.removeEventListener("message",r))};i.addEventListener("message",r),i.postMessage({type:"load"})}function HP(){ht.info("speech","resetModel: clearing load flags"),Ka=!1,cs=!1}function Cy(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function WP(n){const e=Mb();return!Ka&&!cs&&(cs=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var d,l,c;((d=a.data)==null?void 0:d.type)==="result"?(e.removeEventListener("message",s),i((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),r(new Error(String(a.data.error??"Transcription failed")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(Ka=!0,cs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function rT(n){let e=Mb(),i=!1,r=null,s=null,a=null,d=null,l=null;const c=[],h=new Set;let m=null,f=0,b=!1,_=0,y=!1,k=!1,x=0,w=0,S=0,C=-1,T=pk,N=0,A=null,P="",I="",O=!1,H=0;function B(ae,be){const Ne=Math.min(ae.length,be.length);let Se=0;for(;Se<Ne&&ae.charCodeAt(Se)===be.charCodeAt(Se);)Se++;return Se}function Z(ae){const be=B(P,ae);return P=ae,be>I.length&&(I=ae.slice(0,be)),I.length>ae.length&&(I=ae),I}const Q=()=>(m||(m=new Float32Array(wp)),m),W=()=>{f=0},Y=ae=>{const be=Q(),Ne=ae.length;if(Ne>=wp){be.set(ae.subarray(Ne-wp)),f=wp;return}if(f+Ne<=wp){be.set(ae,f),f+=Ne;return}const Se=f+Ne-wp;be.copyWithin(0,Se,f),f-=Se,be.set(ae,f),f+=Ne},ee=()=>{A&&(clearTimeout(A),A=null)},re=()=>{ee(),b=!1,y=!1,k=!1,T=pk,P="",I="",O=!1,H=0,W()},se=()=>{if(i||!b||k||y||A)return;if(f<BP){A=setTimeout(()=>{A=null,se()},T);return}const ae=performance.now()-x;if(ae<T&&x!==0){A=setTimeout(()=>{A=null,se()},T-ae);return}if(nT||Mp||n.partialsEnabled&&!n.partialsEnabled())return;const be=Q(),Ne=new Float32Array(f);Ne.set(be.subarray(0,f)),w+=1,S=w,y=!0,N=performance.now(),x=N,e.postMessage({type:"transcribe-partial",audio:Ne,seq:w},[Ne.buffer])},F=ae=>ae.length===0?Promise.resolve():Mp?(ht.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(be=>{c.push(be),w+=1;const Ne=w;C=Ne,e.postMessage({type:"transcribe",audio:ae,seq:Ne},[ae.buffer])}),te=ae=>{const be=F(ae);return h.add(be),be.finally(()=>{h.delete(be)}),be},q=ae=>{var be,Ne,Se,ce,J;if(ae.data.type==="result"){const me=ae.data.text,ge=ae.data.seq??0;ge&&ge<C&&ht.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ge,latestFinalSeq:C}),!i&&me&&n.onFinal(me),(be=c.shift())==null||be()}else if(ae.data.type==="partial"){const me=ae.data.seq??0,ge=ae.data.text??"",Fe=performance.now()-N;y=!1,Fe>=gk?(k=!0,ht.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Fe),seq:me})):Fe>=mk&&(T=Math.min(T*2,fk),ht.warn("speech","partials.slowdown",{elapsedMs:Math.round(Fe),newIntervalMs:T,seq:me})),O||(O=!0,Fe>FP&&T<500&&(T=500,ht.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Fe),newIntervalMs:500})));const Je=me!==S||me<=C;if(!i&&!Je&&ge){const dt=Z(ge);dt&&((Ne=n.onPartial)==null||Ne.call(n,dt),H===0&&(H=performance.now(),ht.info("speech","partial.first",{msSinceSpeechStart:Math.round(H-_)})))}se()}else if(ae.data.type==="partial-error"){const me=performance.now()-N;y=!1,me>=gk?(k=!0,ht.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(me),seq:ae.data.seq})):me>=mk&&(T=Math.min(T*2,fk),ht.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(me),newIntervalMs:T,seq:ae.data.seq})),ht.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),se()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(Se=c.shift())==null||Se()):ae.data.type==="status"?(i||(ce=n.onModelStatus)==null||ce.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(Ka=!0,cs=!1)):ae.data.type==="progress"&&(i||(J=n.onProgress)==null||J.call(n,ae.data.pct))};e.addEventListener("message",q);const le=ae=>{var be,Ne;if(!i){for(ht.warn("speech","createRecognition: worker death event",ae),(be=n.onStatusChange)==null||be.call(n,"restarting");c.length;)(Ne=c.shift())==null||Ne();if(h.clear(),ee(),y=!1,ae.respawned){try{e.removeEventListener("message",q)}catch{}e=Mb(),e.addEventListener("message",q)}}};return j_.add(le),{start:async()=>{if(!i){if(Mp){n.onError("Speech recognition disabled — please reload the app.");return}!Ka&&!cs&&(cs=!0,ht.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ht.info("speech","createRecognition.start: initializing VAD",{modelReady:Ka,modelLoading:cs});try{const ae=new URL("vad/",document.baseURI).href,be=n.inputDeviceId||null,Ne={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};be&&(Ne.deviceId={exact:be}),ht.info("speech","getUserMedia",{hasDeviceId:!!be,deviceIdPrefix:be?be.slice(0,8):null});const Se=await navigator.mediaDevices.getUserMedia({audio:Ne});s=Se,a=new AudioContext;for(const ce of Se.getAudioTracks())ce.addEventListener("ended",()=>{i||(ht.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),d=a.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,l.connect(d)}catch(ce){ht.warn("speech","analyser init failed",{error:ce instanceof Error?ce.message:String(ce)}),l=null,d=null}r=await OP.MicVAD.new({audioContext:a,getStream:async()=>Se,resumeStream:async()=>Se,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:eT,negativeSpeechThreshold:tT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ce,J)=>{var me;i||((me=n.onFrame)==null||me.call(n,ce),b&&(Y(J),se()))},onSpeechStart:()=>{var ce;i||(re(),b=!0,_=performance.now(),(ce=n.onSpeechStart)==null||ce.call(n))},onSpeechEnd:ce=>{var J;i||((J=n.onStatusChange)==null||J.call(n,"transcribing"),re(),te(ce))},onVADMisfire:()=>{var ce,J;i||((ce=n.onStatusChange)==null||ce.call(n,"idle"),re(),(J=n.onMisfire)==null||J.call(n))}}),r.start()}catch(ae){const be=ae instanceof Error?ae.message:"Microphone access denied",Ne=ae instanceof Error?ae.stack:"";if(ht.error("speech","createRecognition.start: VAD init failed",{error:be,stack:Ne}),d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Se=>Se.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(be)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(re();h.size>0;)await Promise.all(Array.from(h));if(r){try{await r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ae,be)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:be})}catch(Ne){ht.warn("speech","setVadThresholds failed",{error:Ne instanceof Error?Ne.message:String(Ne)})}},getAnalyser:()=>d,destroy:()=>{if(i=!0,re(),r){try{r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}j_.delete(le),e.removeEventListener("message",q)}}}let Ng=null;const T_=new Set,N_=new Set;function VP(){for(const n of T_)try{n()}catch{}}function D_(){for(const n of N_)try{n()}catch{}}function qP(n){return n.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 KP(n){if(!window.speechSynthesis)return;const e=qP(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{Ng=performance.now(),VP()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Ng=null,D_())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Ng=null,D_())},window.speechSynthesis.speak(i)}function sT(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Ng=null,D_())}function oT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function YP(){return Ng}function XP(n){return T_.add(n),()=>{T_.delete(n)}}function JP(n){return N_.add(n),()=>{N_.delete(n)}}function ZP(n){oT()&&(n.setVadThresholds(vk,xk),ht.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=XP(()=>{n.setVadThresholds(vk,xk),ht.info("voice","tts.duck.on")}),i=JP(()=>{n.setVadThresholds(eT,tT),ht.info("voice","tts.duck.off")});return()=>{e(),i()}}const QP=[{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 eR(n){const e=n.trim();return QP.find(i=>i.match.test(e))??null}const tR=4e4;let bu=null;function Op(){bu&&clearTimeout(bu),bu=setTimeout(()=>{bu=null,kt.getState().stopRecording()},tR)}function yx(){bu&&(clearTimeout(bu),bu=null)}let id=null,Qc=null;const nR=.04,iR=.3;let Ob=0,A_=0;function rR(n){Qc!==null&&cancelAnimationFrame(Qc);const e=()=>{if(id===null||kt.getState().submitCountdownStartAt===null){Qc=null;return}const i=performance.now();if(i-A_<200&&Ob>iR){const s=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Ob.toFixed(2),msIntoCountdown:Math.round(s)}),Kc(),Op();return}const r=aT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const d=Math.sqrt(a/s.length);if(d>nR){const l=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(l)}),Kc(),Op();return}}Qc=requestAnimationFrame(e)};Qc=requestAnimationFrame(e)}function yk(n){id&&clearTimeout(id);const e=kt.getState().submitDelayMs,i=performance.now();kt.setState({submitCountdownStartAt:i}),id=setTimeout(()=>{var s;id=null,kt.setState({submitCountdownStartAt:null});const r=vt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=Tn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(Tn.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),Tn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){ht.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Op()},e),rR(i)}function Kc(){Qc!==null&&(cancelAnimationFrame(Qc),Qc=null),id&&(clearTimeout(id),id=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let xr=null,Wr=null,Wm=null;function aT(){var n;return((n=xr==null?void 0:xr.getAnalyser)==null?void 0:n.call(xr))??null}const wx=1e4;let Dg=null;function _x(){Dg&&(clearTimeout(Dg),Dg=null)}let pb=null,fb=null;function Sx(){pb=null,fb&&(fb(),fb=null)}const sR=1500,oR=9e4;let kx=0,mb=null,$_=-1;function Cx(){mb&&(clearTimeout(mb),mb=null,$_=-1)}const aR=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=Ti((n,e)=>({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(e().modelStatus!=="idle")return;ht.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++kx,r=()=>{i===kx&&(Cx(),$_=i,mb=setTimeout(()=>{$_===i&&e().modelStatus==="loading"&&(ht.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},oR))};r(),UP((s,a)=>{i===kx&&(s==="ready"?(Cx(),ht.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Cx(),ht.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===kx&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{ht.info("voice","mic.gate.retry"),Cx(),HP(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(xr){ht.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Cy()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const d=rT({inputDeviceId:a,onStatusChange:l=>{n(l==="transcribing"?{statusPill:"transcribing"}:l==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:l=>{e().partialsEnabled&&n({lastPartial:l})},partialsEnabled:()=>e().partialsEnabled,onFrame:l=>{Ob=l.isSpeech,A_=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),yx(),Kc(),oT()){const c=YP(),h=c!==null?performance.now()-c:null;sT(),n({lastBargeInAt:performance.now()}),ht.info("voice","barge-in",{tabId:i,utteranceOffsetMs:h})}else ht.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Op();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&ht.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var b;Op();const c=l.trim();if(!c||aR.has(c)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Wm){Wm(c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=vt.getState().tabs.find(_=>_.id===i))==null?void 0:b.status)==="dormant"){Tn.getState().setPendingVoiceText(i,c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&yk(i);const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}const m=eR(c);if(m){ht.info("voice","voice-command",{tabId:i,label:m.label,transcript:c}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Kc();const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}window.api.pty.write({tabId:i,data:c}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&yk(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:c}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{ht.error("voice","recognition error",{err:l}),Kc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Wr==null||Wr(),Wr=null,yx(),xr==null||xr.destroy(),xr=null,Wm=null,Re.error(`Microphone error: ${l}`)},onModelStatus:l=>{l==="ready"?n({modelStatus:"ready",loadingProgress:100}):l==="loading"&&n({modelStatus:"loading"})},onProgress:l=>n({loadingProgress:Math.round(l)})});xr=d,Wm=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Op(),d.start().then(()=>{xr===d&&(Wr==null||Wr(),Wr=ZP(d))}).catch(l=>{const c=l instanceof Error?l.message:String(l);ht.error("voice","handle.start() failed",{error:c}),Re.error(`Could not start mic: ${c}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,d,l;return((l=(d=(a=window.api)==null?void 0:a.voice)==null?void 0:d.getDevicePref)==null?void 0:l.call(d))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ht.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=xr;i&&(yx(),Kc(),Ob=0,A_=0,Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),xr===i&&(xr=null,Wm=null),e().hotkeyState==="stopping"&&(_x(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=xr;if(!i)return;yx(),Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){ht.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),xr===i&&(xr=null);const{useSessions:r}=await rv(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>aP);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:i=>n({externalRecording:i}),toggleTTS:()=>n(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>n({autoSubmit:i}),setSubmitDelayMs:i=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Kc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ht.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),n({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&n({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(n({turnDetectorState:i}),i==="load_failed"?ht.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ht.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ht.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&n({wizardArmed:i})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:i,source:r,mode:s,tabId:a})=>{const d=e(),{canRecord:l,reason:c}=Lb(d);if(i==="down"){if(c==="error"||c==="load-timeout"){d.resetAndRetryModel(),ht.info("voice-hotkey","down.retry",{source:r,reason:c});return}if(!l&&c!=="loading"){ht.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:c});return}if(d.hotkeyState==="recording"||d.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),_x(),Dg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:wx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},wx),d.stopRecording());return}if(c==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),ht.info("voice-hotkey","armed",{source:r,modelStatus:d.modelStatus})),Sx(),pb={tabId:a,source:r,mode:s},fb=kt.subscribe((h,m)=>{if(pb&&h.modelStatus==="ready"&&m.modelStatus!=="ready"&&h.hotkeyState==="armed"){const f=pb;if(Sx(),!f.tabId){ht.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}ht.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),kt.getState().startRecording(f.tabId)}});return}if(!a){ht.warn("voice-hotkey","no-active-tab",{source:r});return}ht.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),d.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(ht.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(d.hotkeyState==="armed"){Sx(),ht.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),_x(),Dg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:wx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},wx),d.stopRecording())}},destroyHotkey:()=>{const i=e();if(Sx(),Kc(),i.hotkeyState==="recording"){ht.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(_x(),n({hotkeyState:"destroyed"}))}})),lR=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),Lb=n=>Cy()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const n=window;n.__voice=kt,n.__transcripts=[]}const cR=6e4,dR=5e3,Ag=Ti(()=>({data:null,refreshing:!1}));let wk=!1,gb=null,_k=null,Sk=!1;async function t1(){Ag.setState({refreshing:!0});let n=cR;try{const e=await W0(window.api.billing.fetch(),dR,"billing.fetch");Ag.setState({data:e,refreshing:!1}),e.kind==="transient"?n=_k==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),_k=e.kind}catch(e){if(Ag.setState({refreshing:!1}),!Sk){Sk=!0;const i=e instanceof Error?e.message:String(e);Re.warn(`Billing usage fetch failed: ${i}`)}}gb=setTimeout(t1,n)}function uR(){wk||(wk=!0,t1())}function lT(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function hR(){gb!==null&&(clearTimeout(gb),gb=null),t1()}function ov(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),i=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!i)return n;const r=i[1].charAt(0).toUpperCase()+i[1].slice(1).toLowerCase(),s=i[3]?`${i[2]}.${i[3]}`:i[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const Ex=new Map,pR=3e4;function n1(n){const[e,i]=R.useState(()=>{var r;return n?((r=Ex.get(n))==null?void 0:r.value)??null:null});return R.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=Ex.get(n);if(a&&Date.now()-a.ts<pR){r||i(a.value);return}try{const d=await window.api.app.gitBranch(n);if(r)return;Ex.set(n,{value:d,ts:Date.now()}),i(d)}catch{if(r)return;Ex.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function fR(n){return n.filter(e=>e.group==="Tools").map(({key:e,label:i,icon:r,hint:s})=>({key:e,label:i,icon:r,hint:s}))}const P_="sm.almanac.sidebarWidth",cT=180,dT=480,R_=252;function mR(){try{const n=parseInt(localStorage.getItem(P_)??"",10);if(Number.isFinite(n))return Math.min(dT,Math.max(cT,n))}catch{}return R_}const gR=52,uT="sm.almanac.sidebarCollapsed";function vR(){try{return localStorage.getItem(uT)==="1"}catch{}return!1}const hT="sm.almanac.collapsedGroups";function xR(){try{const n=localStorage.getItem(hT);if(!n)return new Set;const e=JSON.parse(n);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function bR(){const n=vt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:to(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function yR({active:n,onNavigate:e,onNewSession:i}){const[r,s]=R.useState(()=>xR()),a=R.useCallback(P=>{s(I=>{const O=new Set(I);O.has(P)?O.delete(P):O.add(P);try{localStorage.setItem(hT,JSON.stringify(Array.from(O)))}catch{}return O})},[]),[d,l]=R.useState(()=>vR()),c=R.useCallback(()=>{l(P=>{const I=!P;try{localStorage.setItem(uT,I?"1":"0")}catch{}return I})},[]),h=vt(P=>P.tabs),m=vt(P=>P.activeTabId),f=h.find(P=>P.id===m)??null,b=bR(),_=mn(P=>P.navFace),y=gP(_),k=y.filter(P=>P.group==="Workspace"),x=y.filter(P=>P.group==="Configure"),w=fR(y),[S,C]=R.useState(()=>mR()),T=R.useRef(S);T.current=S;const N=R.useCallback(P=>{P.preventDefault();const I=P.clientX,O=T.current;let H=O;const B=Q=>{H=Math.min(dT,Math.max(cT,O+(Q.clientX-I))),C(H)},Z=()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(P_,String(H))}catch{}};window.addEventListener("pointermove",B),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),A=R.useCallback(()=>{C(R_);try{localStorage.setItem(P_,String(R_))}catch{}},[]);return o.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?gR:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(wR,{tab:f,navFace:_,onNewSession:i,rail:d,onToggleRail:c}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!d&&o.jsx(gw,{label:"Workspace",desc:dw.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(d||!r.has("Workspace"))&&k.map(P=>o.jsx(kk,{item:P,active:n===P.key,live:P.liveKind?b[P.liveKind]:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(gw,{label:"Configure",desc:dw.Configure,collapsed:r.has("Configure"),count:x.length,onToggle:()=>a("Configure")}),(d||!r.has("Configure"))&&x.map(P=>o.jsx(kk,{item:P,active:n===P.key,live:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(gw,{label:"Tools",desc:dw.Tools,collapsed:r.has("Tools"),count:w.length,onToggle:()=>a("Tools")}),(d||!r.has("Tools"))&&w.map(P=>o.jsx(_R,{tool:P,active:n===P.key,onClick:()=>e(P.key),rail:d},P.key))]})}),o.jsx(SR,{rail:d,navFace:_}),!d&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:A,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 wR({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",d=n1((n==null?void 0:n.cwd)??null);return r?o.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[o.jsx("button",{onClick:i,"data-testid":"tour-new-session",title:"Open / Start Project",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:o.jsx(sn,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:s,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:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:o.jsx(sn,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),o.jsx("button",{onClick:s,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:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(sn,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(sn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),o.jsx("button",{onClick:s,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:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(sn,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[o.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),o.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(n==null?void 0:n.cwd)??"",children:a})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:d?`⌥${d}`:n?n.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(sn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function gw({label:n,desc:e,collapsed:i,count:r,onToggle:s}){return o.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[o.jsxs("button",{onClick:s,"aria-expanded":!i,title:i?`Expand ${n}`:`Collapse ${n}`,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:[o.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:i?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:n}),i&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!i&&o.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:e})]})}function kk({item:n,active:e,live:i,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:n.hint,"data-testid":n.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"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:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(sn,{name:n.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&i&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&i&&o.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 _R({tool:n,active:e,onClick:i,rail:r}){return o.jsxs("button",{onClick:i,title:n.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${e?"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:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(sn,{name:n.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]})]})}function SR({rail:n,navFace:e}){const i=kt(c=>c.isRecording),r=vt(c=>c.tabs),s=vt(c=>c.activeTabId),a=r.find(c=>c.id===s)??null,[d,l]=R.useState(null);return R.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return Mj(a.presetId).then(h=>{c||l((h==null?void 0:h.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?o.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"})}):o.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:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"}),(i||e==="project")&&o.jsx("span",{className:"truncate",title:d??"",children:i?"recording…":d?`Claude · ${ov(d)}`:"Claude Code"})]})}function kR(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function CR(n,e,i){return{tabId:n,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const vb=Ti((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,r,s)=>{const a={...e().refs};if(a[i]=(a[i]??0)+1,n({refs:a}),a[i]>1)return;n({tabs:{...e().tabs,[i]:CR(i,r,s)}});const d=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:d}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:m}=await rv(async()=>{const{toast:f}=await Promise.resolve().then(()=>Bj);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...c,path:null}}});return}n({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const h=await window.api.transcripts.buffer(i);for(const m of h)e().ingest(i,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const r={...e().refs};if(!r[i])return;if(r[i]--,r[i]>0){n({refs:r});return}delete r[i];const s=e().unsubs[i];s==null||s();const a={...e().unsubs};delete a[i];const d={...e().tabs};delete d[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:d})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const d=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:d},c=[],h=(m,f)=>m.length>f?m.slice(0,f-1)+"…":m;switch(r.kind){case"todo_write":{const m=Array.isArray(r.data)?r.data:[];l.todos=m,s!=null&&s.replay||c.push({id:0,kind:"todo-update",at:d,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const _ of["command","file_path","pattern","url","query","subagent_type","description"])f&&_ in f&&(b[_]=f[_]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:d},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const _=m.input,y=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(_==null?void 0:_.file_path)=="string"?_.file_path:void 0,x=typeof(_==null?void 0:_.command)=="string"?_.command:void 0,w=k?k.split("/").pop()??k:x?h(x,28):"";c.push({id:0,kind:"tool-use",at:d,label:w?`${m.name} · ${w}`:m.name,target:k??x,toolName:m.name}),y&&k&&c.push({id:0,kind:"file-edit",at:d,label:`${m.name} · ${h(k.split("/").pop()??k,34)}`,target:k,toolName:m.name})}break}case"plan":{const m=r.data,f=typeof m=="string"?m:(m==null?void 0:m.plan)??JSON.stringify(m);l.plans=[{at:d,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:d,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:d},...a.agents].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"agent-spawn",at:d,label:m!=null&&m.subagent_type?`Agent: ${h(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),b=m.input_tokens??m.inputTokens??0,_=m.output_tokens??m.outputTokens??0,y=f+b+_;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+_,cacheCreationInputTokens:(a.usage.cacheCreationInputTokens||0)+(m.cache_creation_input_tokens??m.cacheCreationInputTokens??0),cacheReadInputTokens:(a.usage.cacheReadInputTokens||0)+(m.cache_read_input_tokens??m.cacheReadInputTokens??0)},!(s!=null&&s.replay)&&Math.floor(y/1e3)>Math.floor(f/1e3)&&c.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(y/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=kR(a.agents,m==null?void 0:m.toolUseId,d);break}}if(c.length>0){let m=a.activitySeq;const f=c.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function ER(n){const e=vb(s=>s.subscribe),i=vb(s=>s.unsubscribe),r=vb(s=>n?s.tabs[n.id]:void 0);return R.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>i(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,i]),r}function jR({onNavigate:n}){const e=vt(C=>C.tabs),i=vt(C=>C.activeTabId),r=e.find(C=>C.id===i)??null,s=ER(r),a=(s==null?void 0:s.lastEventAt)??0,d=Ag(C=>C.data),l=to(C=>{var T;return((T=C.snapshot)==null?void 0:T.paused)??null}),c=n1((r==null?void 0:r.cwd)??null),[,h]=R.useState(0);R.useEffect(()=>{const C=setInterval(()=>h(T=>T+1),6e4);return()=>clearInterval(C)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=R.useState(!1),_=R.useRef(null);R.useEffect(()=>{if(!f)return;const C=T=>{_.current&&!_.current.contains(T.target)&&b(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[f]),R.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const y=lT(d),k=(y==null?void 0:y.usage.five_hour)??null,x=k?Math.round(k.utilization):null,w=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",S=a>0?DR(Date.now()-a):"—";return o.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:[o.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:w?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:w?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>n==null?void 0:n("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 ${l.reason==="auth"||l.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:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),r&&o.jsxs("span",{className:"text-fg-faint",title:r.cwd,children:[r.label,c&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(TR,{ref:_,todos:m,open:f,onToggle:()=>b(C=>!C)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.57.0"]})]})}const TR=R.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(d=>d.status==="completed").length,in_progress:e.filter(d=>d.status==="in_progress").length,pending:e.filter(d=>d.status==="pending").length};return o.jsxs("div",{ref:s,className:"relative",children:[o.jsxs("button",{onClick:r,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[o.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),o.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),o.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),o.jsxs("span",{className:"text-fg-faint",children:["todos ",i?"▾":"▴"]})]}),i&&o.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:o.jsx("ul",{className:"space-y-0.5",children:e.map((d,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(NR,{status:d.status}),o.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})]},l))})})]})});function NR({status:n}){return n==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?o.jsx("span",{className:"w-3 shrink-0",children:o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function DR(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function AR({onClose:n,onSent:e}){const i=vt(P=>P.tabs),[r,s]=R.useState(""),[a,d]=R.useState(()=>Object.fromEntries(i.map(P=>[P.id,!0]))),[l,c]=R.useState(!1),[h,m]=R.useState({}),f=R.useRef(null),b=R.useRef(e);R.useEffect(()=>{b.current=e},[e]),R.useEffect(()=>{d(P=>{const I={};for(const O of i)I[O.id]=P[O.id]??!0;return I})},[i]),R.useEffect(()=>{var P;(P=f.current)==null||P.focus()},[]),R.useEffect(()=>window.api.pty.onWriteError(I=>{m(O=>I.tabId in O?{...O,[I.tabId]:"skipped"}:O)}),[]),R.useEffect(()=>{if(Object.keys(h).length===0)return;const P=Object.values(h).filter(O=>O==="sent").length,I=window.setTimeout(()=>b.current(P),1500);return()=>window.clearTimeout(I)},[h]);const _=i.filter(P=>a[P.id]).map(P=>P.id),y=_.length,k=Object.keys(h).length>0,x=r.length>0&&y>0&&!l&&!k,w=()=>{if(!x)return;c(!0);const P=vt.getState().tabs,I=new Set(P.map(H=>H.id)),O={};for(const H of _)I.has(H)?(window.api.pty.write({tabId:H,data:r+"\r"}),O[H]="sent"):O[H]="skipped";m(O),c(!1)},S=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopPropagation(),n();return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),w())},C=i.length>0&&i.every(P=>a[P.id]),T=()=>{const P=!C;d(Object.fromEntries(i.map(I=>[I.id,P])))},N=Object.values(h).some(P=>P==="skipped"),A=k?N?"Sent (some skipped)":"Sent":`Send to ${y} tab${y===1?"":"s"}`;return o.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:S,"data-testid":"broadcast-bar",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),o.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),o.jsx("textarea",{ref:f,value:r,onChange:P=>s(P.target.value),rows:3,placeholder:"Prompt to broadcast…",className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono resize-y focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:C,onChange:T,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",y,"/",i.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:i.map(P=>o.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:!!a[P.id],onChange:I=>d(O=>({...O,[P.id]:I.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:P.label}),h[P.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[P.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},P.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),o.jsx("button",{onClick:w,disabled:!x,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:A})]})]})}function $R({tabId:n,cwd:e,onClose:i}){const r=Tg(y=>y.watchersForTab(n)),s=Tg(y=>y.add),a=Tg(y=>y.remove),d=R.useRef(null),[l,c]=R.useState(""),[h,m]=R.useState(""),[f,b]=R.useState(!1);R.useEffect(()=>{const y=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),R.useEffect(()=>{const y=k=>{d.current&&!d.current.contains(k.target)&&i()};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[i]);const _=async()=>{const y=h.trim();if(!y||f)return;b(!0);const k=await s({tabId:n,label:l.trim(),command:y,cwd:e});b(!1),k&&(c(""),m(""))};return o.jsxs("div",{ref:d,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[o.jsxs("div",{className:"flex items-center mb-2",children:[o.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),o.jsxs("span",{className:"text-fg-faint ml-2",children:[r.length," active"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:i,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[o.jsx("input",{value:l,onChange:y=>c(y.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{value:h,onChange:y=>m(y.target.value),onKeyDown:y=>{y.key==="Enter"&&_()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),o.jsx("button",{onClick:_,disabled:!h.trim()||f,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),o.jsxs("span",{className:"text-fg-faint",children:["cwd: ",o.jsx("span",{className:"font-mono",children:e})]})]}),r.length===0?o.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):o.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:r.map(y=>{const k=y.lines[y.lines.length-1];return o.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-fg truncate",children:y.label}),o.jsxs("span",{className:"text-fg-faint",children:[y.lineCount," line",y.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(y.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${y.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:y.command,children:y.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},y.watcherId)})})]})}/**
2901
+ */var dk;function RP(){return dk||(dk=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,l=(oe=>typeof Eo<"u"?Eo:typeof Proxy<"u"?new Proxy(oe,{get:(fe,we)=>(typeof Eo<"u"?Eo:fe)[we]}):oe)(function(oe){if(typeof Eo<"u")return Eo.apply(this,arguments);throw Error('Dynamic require of "'+oe+'" is not supported')}),c=(oe,fe)=>()=>(oe&&(fe=oe(oe=0)),fe),h=(oe,fe)=>{for(var we in fe)r(oe,we,{get:fe[we],enumerable:!0})},m=(oe,fe,we,De)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ee of a(fe))!d.call(oe,Ee)&&Ee!==we&&r(oe,Ee,{get:()=>fe[Ee],enumerable:!(De=s(fe,Ee))||De.enumerable});return oe},f=oe=>m(r({},"__esModule",{value:!0}),oe),b,_,y,k,x,w=c(()=>{b=new Map,_=[],y=(oe,fe,we)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let De=b.get(oe);if(De===void 0)b.set(oe,{backend:fe,priority:we});else{if(De.priority>we)return;if(De.priority===we&&De.backend!==fe)throw new Error(`cannot register backend "${oe}" using priority ${we}`)}if(we>=0){let Ee=_.indexOf(oe);Ee!==-1&&_.splice(Ee,1);for(let Be=0;Be<_.length;Be++)if(b.get(_[Be]).priority<=we){_.splice(Be,0,oe);return}_.push(oe)}return}throw new TypeError("not a valid backend")},k=async oe=>{let fe=b.get(oe);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let we=!!fe.initPromise;try{return we||(fe.initPromise=fe.backend.init(oe)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(De){return we||(fe.error=`${De}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},x=async oe=>{let fe=oe.executionProviders||[],we=fe.map(Ge=>typeof Ge=="string"?Ge:Ge.name),De=we.length===0?_:we,Ee,Be=[],$e=new Set;for(let Ge of De){let tt=await k(Ge);typeof tt=="string"?Be.push({name:Ge,err:tt}):(Ee||(Ee=tt),Ee===tt&&$e.add(Ge))}if(!Ee)throw new Error(`no available backend found. ERR: ${Be.map(Ge=>`[${Ge.name}] ${Ge.err}`).join(", ")}`);for(let{name:Ge,err:tt}of Be)we.includes(Ge)&&console.warn(`removing requested execution provider "${Ge}" from session options because it is not available: ${tt}`);let Pe=fe.filter(Ge=>$e.has(typeof Ge=="string"?Ge:Ge.name));return[Ee,new Proxy(oe,{get:(Ge,tt)=>tt==="executionProviders"?Pe:Reflect.get(Ge,tt)})]}}),S=c(()=>{w()}),C,T=c(()=>{C="1.26.0"}),N,A,P=c(()=>{T(),N="warning",A={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(oe){if(oe!==void 0){if(typeof oe!="string"||["verbose","info","warning","error","fatal"].indexOf(oe)===-1)throw new Error(`Unsupported logging level: ${oe}`);N=oe}},get logLevel(){return N}},Object.defineProperty(A,"logLevel",{enumerable:!0})}),I,O=c(()=>{P(),I=A}),H,B,Z=c(()=>{H=(oe,fe)=>{let we=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);we.width=oe.dims[3],we.height=oe.dims[2];let De=we.getContext("2d");if(De!=null){let Ee,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Be=oe.dims[3]):(Ee=oe.dims[3],Be=oe.dims[2]);let $e=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Pe=fe==null?void 0:fe.norm,Ge,tt;Pe===void 0||Pe.mean===void 0?Ge=[255,255,255,255]:typeof Pe.mean=="number"?Ge=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(Ge=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(Ge[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?tt=[0,0,0,0]:typeof Pe.bias=="number"?tt=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(tt=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(tt[3]=Pe.bias[3]));let st=Be*Ee,nt=0,Xe=st,$t=st*2,ze=-1;$e==="RGBA"?(nt=0,Xe=st,$t=st*2,ze=st*3):$e==="RGB"?(nt=0,Xe=st,$t=st*2):$e==="RBG"&&(nt=0,$t=st,Xe=st*2);for(let ut=0;ut<Be;ut++)for(let Rn=0;Rn<Ee;Rn++){let tn=(oe.data[nt++]-tt[0])*Ge[0],nn=(oe.data[Xe++]-tt[1])*Ge[1],In=(oe.data[$t++]-tt[2])*Ge[2],Bt=ze===-1?255:(oe.data[ze++]-tt[3])*Ge[3];De.fillStyle="rgba("+tn+","+nn+","+In+","+Bt+")",De.fillRect(Rn,ut,1,1)}if("toDataURL"in we)return we.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},B=(oe,fe)=>{let we=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(we!=null){let Ee,Be,$e;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Be=oe.dims[1],$e=oe.dims[3]):(Ee=oe.dims[3],Be=oe.dims[2],$e=oe.dims[1]);let Pe=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Ge=fe==null?void 0:fe.norm,tt,st;Ge===void 0||Ge.mean===void 0?tt=[255,255,255,255]:typeof Ge.mean=="number"?tt=[Ge.mean,Ge.mean,Ge.mean,Ge.mean]:(tt=[Ge.mean[0],Ge.mean[1],Ge.mean[2],255],Ge.mean[3]!==void 0&&(tt[3]=Ge.mean[3])),Ge===void 0||Ge.bias===void 0?st=[0,0,0,0]:typeof Ge.bias=="number"?st=[Ge.bias,Ge.bias,Ge.bias,Ge.bias]:(st=[Ge.bias[0],Ge.bias[1],Ge.bias[2],0],Ge.bias[3]!==void 0&&(st[3]=Ge.bias[3]));let nt=Be*Ee;if(fe!==void 0&&(fe.format!==void 0&&$e===4&&fe.format!=="RGBA"||$e===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,$t=0,ze=1,ut=2,Rn=3,tn=0,nn=nt,In=nt*2,Bt=-1;Pe==="RGBA"?(tn=0,nn=nt,In=nt*2,Bt=nt*3):Pe==="RGB"?(tn=0,nn=nt,In=nt*2):Pe==="RBG"&&(tn=0,In=nt,nn=nt*2),De=we.createImageData(Ee,Be);for(let Bn=0;Bn<Be*Ee;$t+=Xe,ze+=Xe,ut+=Xe,Rn+=Xe,Bn++)De.data[$t]=(oe.data[tn++]-st[0])*tt[0],De.data[ze]=(oe.data[nn++]-st[1])*tt[1],De.data[ut]=(oe.data[In++]-st[2])*tt[2],De.data[Rn]=Bt===-1?255:(oe.data[Bt++]-st[3])*tt[3]}else throw new Error("Can not access image data");return De}}),Q,W,Y,ee,re,se,F=c(()=>{me(),Q=(oe,fe)=>{if(oe===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:we,width:De}=fe,Ee=fe.norm??{mean:255,bias:0},Be,$e;typeof Ee.mean=="number"?Be=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:Be=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?$e=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:$e=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let Pe=fe.format!==void 0?fe.format:"RGBA",Ge=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",tt=we*De,st=Ge==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),nt=4,Xe=0,$t=1,ze=2,ut=3,Rn=0,tn=tt,nn=tt*2,In=-1;Pe==="RGB"&&(nt=3,Xe=0,$t=1,ze=2,ut=-1),Ge==="RGBA"?In=tt*3:Ge==="RBG"?(Rn=0,nn=tt,tn=tt*2):Ge==="BGR"&&(nn=0,tn=tt,Rn=tt*2);for(let Bt=0;Bt<tt;Bt++,Xe+=nt,ze+=nt,$t+=nt,ut+=nt)st[Rn++]=(oe[Xe]+$e[0])/Be[0],st[tn++]=(oe[$t]+$e[1])/Be[1],st[nn++]=(oe[ze]+$e[2])/Be[2],In!==-1&&ut!==-1&&(st[In++]=(oe[ut]+$e[3])/Be[3]);return Ge==="RGBA"?new J("float32",st,[1,4,we,De]):new J("float32",st,[1,3,we,De])},W=async(oe,fe)=>{let we=typeof HTMLImageElement<"u"&&oe instanceof HTMLImageElement,De=typeof ImageData<"u"&&oe instanceof ImageData,Ee=typeof ImageBitmap<"u"&&oe instanceof ImageBitmap,Be=typeof oe=="string",$e,Pe=fe??{},Ge=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=st=>typeof HTMLCanvasElement<"u"&&st instanceof HTMLCanvasElement||st instanceof OffscreenCanvas?st.getContext("2d"):null;if(we){let st=Ge();st.width=oe.width,st.height=oe.height;let nt=tt(st);if(nt!=null){let Xe=oe.height,$t=oe.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,$t=fe.resizedWidth),fe!==void 0){if(Pe=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t}else Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t;nt.drawImage(oe,0,0),$e=nt.getImageData(0,0,$t,Xe).data}else throw new Error("Can not access image data")}else if(De){let st,nt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(st=fe.resizedHeight,nt=fe.resizedWidth):(st=oe.height,nt=oe.width),fe!==void 0&&(Pe=fe),Pe.format="RGBA",Pe.height=st,Pe.width=nt,fe!==void 0){let Xe=Ge();Xe.width=nt,Xe.height=st;let $t=tt(Xe);if($t!=null)$t.putImageData(oe,0,0),$e=$t.getImageData(0,0,nt,st).data;else throw new Error("Can not access image data")}else $e=oe.data}else if(Ee){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let st=Ge();st.width=oe.width,st.height=oe.height;let nt=tt(st);if(nt!=null){let Xe=oe.height,$t=oe.width;return nt.drawImage(oe,0,0,$t,Xe),$e=nt.getImageData(0,0,$t,Xe).data,Pe.height=Xe,Pe.width=$t,Q($e,Pe)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((st,nt)=>{let Xe=Ge(),$t=tt(Xe);if(!oe||!$t)return nt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=oe,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,$t.drawImage(ze,0,0,Xe.width,Xe.height);let ut=$t.getImageData(0,0,Xe.width,Xe.height);Pe.height=Xe.height,Pe.width=Xe.width,st(Q(ut.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Q($e,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},Y=(oe,fe)=>{let{width:we,height:De,download:Ee,dispose:Be}=fe,$e=[1,De,we,4];return new J({location:"texture",type:"float32",texture:oe,dims:$e,download:Ee,dispose:Be})},ee=(oe,fe)=>{let{dataType:we,dims:De,download:Ee,dispose:Be}=fe;return new J({location:"gpu-buffer",type:we??"float32",gpuBuffer:oe,dims:De,download:Ee,dispose:Be})},re=(oe,fe)=>{let{dataType:we,dims:De,download:Ee,dispose:Be}=fe;return new J({location:"ml-tensor",type:we??"float32",mlTensor:oe,dims:De,download:Ee,dispose:Be})},se=(oe,fe,we)=>new J({location:"cpu-pinned",type:oe,data:fe,dims:we??[fe.length]})}),te,q,le,ae,be=c(()=>{te=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ae=()=>{if(!le){le=!0;let oe=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,we=globalThis.Float16Array,De=typeof we<"u"&&we.from;oe&&(te.set("int64",BigInt64Array),q.set(BigInt64Array,"int64")),fe&&(te.set("uint64",BigUint64Array),q.set(BigUint64Array,"uint64")),De?(te.set("float16",we),q.set(we,"float16")):te.set("float16",Uint16Array)}}}),Ne,Se,ce=c(()=>{me(),Ne=oe=>{let fe=1;for(let we=0;we<oe.length;we++){let De=oe[we];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${we}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${we}] must be a non-negative integer, got: ${De}`);fe*=De}return fe},Se=(oe,fe)=>{switch(oe.location){case"cpu":return new J(oe.type,oe.data,fe);case"cpu-pinned":return new J({location:"cpu-pinned",data:oe.data,type:oe.type,dims:fe});case"texture":return new J({location:"texture",texture:oe.texture,type:oe.type,dims:fe});case"gpu-buffer":return new J({location:"gpu-buffer",gpuBuffer:oe.gpuBuffer,type:oe.type,dims:fe});case"ml-tensor":return new J({location:"ml-tensor",mlTensor:oe.mlTensor,type:oe.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${oe.location} is not supported`)}}}),J,me=c(()=>{Z(),F(),be(),ce(),J=class{constructor(oe,fe,we){ae();let De,Ee;if(typeof oe=="object"&&"location"in oe)switch(this.dataLocation=oe.location,De=oe.type,Ee=oe.dims,oe.location){case"cpu-pinned":{let $e=te.get(De);if(!$e)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(oe.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=oe.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=oe.texture,this.downloader=oe.download,this.disposer=oe.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=oe.gpuBuffer,this.downloader=oe.download,this.disposer=oe.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=oe.mlTensor,this.downloader=oe.download,this.disposer=oe.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $e,Pe;if(typeof oe=="string")if(De=oe,Pe=we,oe==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");$e=fe}else{let Ge=te.get(oe);if(Ge===void 0)throw new TypeError(`Unsupported tensor type: ${oe}.`);if(Array.isArray(fe)){if(oe==="float16"&&Ge===Uint16Array||oe==="uint4"||oe==="int4")throw new TypeError(`Creating a ${oe} tensor from number array is not supported. Please use ${Ge.name} as data.`);oe==="uint64"||oe==="int64"?$e=Ge.from(fe,BigInt):$e=Ge.from(fe)}else if(fe instanceof Ge)$e=fe;else if(fe instanceof Uint8ClampedArray)if(oe==="uint8")$e=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(oe==="float16"&&fe instanceof Uint16Array&&Ge!==Uint16Array)$e=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Ge}`)}else if(Pe=fe,Array.isArray(oe)){if(oe.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Ge=typeof oe[0];if(Ge==="string")De="string",$e=oe;else if(Ge==="boolean")De="bool",$e=Uint8Array.from(oe);else throw new TypeError(`Invalid element type of data array: ${Ge}.`)}else if(oe instanceof Uint8ClampedArray)De="uint8",$e=Uint8Array.from(oe);else{let Ge=q.get(oe.constructor);if(Ge===void 0)throw new TypeError(`Unsupported type for tensor data: ${oe.constructor}.`);De=Ge,$e=oe}if(Pe===void 0)Pe=[$e.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");Ee=Pe,this.cpuData=$e,this.dataLocation="cpu"}let Be=Ne(Ee);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="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=De,this.dims=Ee,this.size=Be}static async fromImage(oe,fe){return W(oe,fe)}static fromTexture(oe,fe){return Y(oe,fe)}static fromGpuBuffer(oe,fe){return ee(oe,fe)}static fromMLTensor(oe,fe){return re(oe,fe)}static fromPinnedBuffer(oe,fe,we){return se(oe,fe,we)}toDataURL(oe){return H(this,oe)}toImageData(oe){return B(this,oe)}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(oe){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,oe&&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(oe){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,oe)}}}),ge,Fe=c(()=>{me(),ge=J}),Je,dt,zt,pt,it,ot,Dt=c(()=>{P(),Je=(oe,fe)=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeStamp(`${oe}::ORT::${fe}`)},dt=(oe,fe)=>{var Ee;let we=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<we.length;Be++){if(De&&!we[Be].includes("TRACE_FUNC")){let $e=`FUNC_${oe}::${we[Be].trim().split(" ")[1]}`;fe&&($e+=`::${fe}`),Je("CPU",$e);return}we[Be].includes("TRACE_FUNC")&&(De=!0)}},zt=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||dt("BEGIN",oe)},pt=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||dt("END",oe)},it=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.time(`ORT::${oe}`)},ot=oe=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeEnd(`ORT::${oe}`)}}),on,gn=c(()=>{w(),Fe(),Dt(),on=class Zj{constructor(fe){this.handler=fe}async run(fe,we,De){zt(),it("InferenceSession.run");let Ee={},Be={};if(typeof fe!="object"||fe===null||fe instanceof ge||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof we=="object"){if(we===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(we instanceof ge)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(we)){if(we.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let tt of we){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);Ee[tt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,st=Object.getOwnPropertyNames(we);for(let nt of this.outputNames)if(st.indexOf(nt)!==-1){let Xe=we[nt];(Xe===null||Xe instanceof ge)&&(tt=!0,$e=!1,Ee[nt]=Xe)}if(tt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=we}}else if(typeof we<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof fe[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)Ee[tt]=null;let Pe=await this.handler.run(fe,Ee,Be),Ge={};for(let tt in Pe)if(Object.hasOwnProperty.call(Pe,tt)){let st=Pe[tt];st instanceof ge?Ge[tt]=st:Ge[tt]=new ge(st.type,st.data,st.dims)}return ot("InferenceSession.run"),pt(),Ge}async release(){return this.handler.dispose()}static async create(fe,we,De,Ee){zt(),it("InferenceSession.create");let Be,$e={};if(typeof fe=="string"){if(Be=fe,typeof we=="object"&&we!==null)$e=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof we=="object"&&we!==null)$e=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let st=fe,nt=0,Xe=fe.byteLength;if(typeof we=="object"&&we!==null)$e=we;else if(typeof we=="number"){if(nt=we,!Number.isSafeInteger(nt))throw new RangeError("'byteOffset' must be an integer.");if(nt<0||nt>=st.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${st.byteLength}).`);if(Xe=fe.byteLength-nt,typeof De=="number"){if(Xe=De,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||nt+Xe>st.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${st.byteLength-nt}].`);if(typeof Ee=="object"&&Ee!==null)$e=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof we<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(st,nt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,Ge]=await x($e),tt=await Pe.createInferenceSessionHandler(Be,Ge);return ot("InferenceSession.create"),pt(),new Zj(tt)}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}}}),Ze,Ct=c(()=>{gn(),Ze=on}),xt=c(()=>{}),pn=c(()=>{}),$n=c(()=>{}),er=c(()=>{}),yr={};h(yr,{InferenceSession:()=>Ze,TRACE:()=>Je,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>ge,env:()=>I,registerBackend:()=>y});var vn=c(()=>{S(),O(),Ct(),Fe(),xt(),pn(),Dt(),$n(),er()}),Hi=c(()=>{}),Xn={};h(Xn,{default:()=>Rs});var di,xn,Rs,nl=c(()=>{var oe;_e(),ir(),nr(),di="ort-wasm-proxy-worker",xn=((oe=globalThis.self)==null?void 0:oe.name)===di,xn&&(self.onmessage=fe=>{let{type:we,in:De}=fe.data;try{switch(we){case"init-wasm":gs(De.wasm).then(()=>{va(De).then(()=>{postMessage({type:we})},Ee=>{postMessage({type:we,err:Ee})})},Ee=>{postMessage({type:we,err:Ee})});break;case"init-ep":{let{epName:Ee,env:Be}=De;Fs(Be,Ee).then(()=>{postMessage({type:we})},$e=>{postMessage({type:we,err:$e})});break}case"copy-from":{let{buffer:Ee}=De,Be=dn(Ee);postMessage({type:we,out:Be});break}case"create":{let{model:Ee,options:Be}=De;Cr(Ee,Be).then($e=>{postMessage({type:we,out:$e})},$e=>{postMessage({type:we,err:$e})});break}case"release":ao(De),postMessage({type:we});break;case"run":{let{sessionId:Ee,inputIndices:Be,inputs:$e,outputIndices:Pe,options:Ge}=De;Ye(Ee,Be,$e,Pe,new Array(Pe.length).fill(null),Ge).then(tt=>{tt.some(st=>st[3]!=="cpu")?postMessage({type:we,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:we,out:tt},mt([...$e,...tt]))},tt=>{postMessage({type:we,err:tt})});break}case"end-profiling":sr(De),postMessage({type:we});break;default:}}catch(Ee){postMessage({type:we,err:Ee})}}),Rs=xn?null:fe=>new Worker(fe??kn,{type:"classic",name:di})}),ma,Is,kn,tr,ui,Ms,qr,wr,ro,Os,Ls,Kr,Wi,nr=c(()=>{Hi(),ma=typeof location>"u"?void 0:location.origin,Is=()=>{var oe,fe;return typeof document<"u"?(oe=document.currentScript)==null?void 0:oe.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},kn=Is(),tr=()=>{if(kn&&!kn.startsWith("blob:"))return kn.substring(0,kn.lastIndexOf("/")+1)},ui=(oe,fe)=>{try{let we=fe??kn;return(we?new URL(oe,we):new URL(oe)).origin===ma}catch{return!1}},Ms=(oe,fe)=>{let we=fe??kn;try{return(we?new URL(oe,we):new URL(oe)).href}catch{return}},qr=(oe,fe)=>`${fe??"./"}${oe}`,wr=async oe=>{let fe=await(await fetch(oe,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},ro=async oe=>(await import(oe)).default,Os=(nl(),f(Xn)).default,Ls=async()=>{if(!kn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ui(kn))return[void 0,Os()];let oe=await wr(kn);return[oe,Os(oe)]},Kr=void 0,Wi=async(oe,fe,we,De)=>{let Ee=Kr&&!(oe||fe);if(Ee)if(kn)Ee=ui(kn)||De&&!we;else if(De&&!we)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Kr];{let Be="ort-wasm-simd-threaded.mjs",$e=oe??Ms(Be,fe),Pe=we&&$e&&!ui($e,fe),Ge=Pe?await wr($e):$e??qr(Be,fe);return[Pe?Ge:void 0,await ro(Ge)]}}}),ps,Vi,_r,Br,$o,fs,ms,gs,Gt,ir=c(()=>{nr(),Vi=!1,_r=!1,Br=!1,$o=()=>{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}},fs=()=>{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}},ms=()=>{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}},gs=async oe=>{if(Vi)return Promise.resolve();if(_r)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");_r=!0;let fe=oe.initTimeout,we=oe.numThreads;if(oe.simd!==!1){if(oe.simd==="relaxed"){if(!ms())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!fs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=$o();we>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+we+", 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."),oe.numThreads=we=1);let Ee=oe.wasmPaths,Be=typeof Ee=="string"?Ee:void 0,$e=Ee==null?void 0:Ee.mjs,Pe=($e==null?void 0:$e.href)??$e,Ge=Ee==null?void 0:Ee.wasm,tt=(Ge==null?void 0:Ge.href)??Ge,st=oe.wasmBinary,[nt,Xe]=await Wi(Pe,Be,we>1,!!st||!!tt),$t=!1,ze=[];if(fe>0&&ze.push(new Promise(ut=>{setTimeout(()=>{$t=!0,ut()},fe)})),ze.push(new Promise((ut,Rn)=>{let tn={numThreads:we};if(st)tn.wasmBinary=st,tn.locateFile=nn=>nn;else if(tt||Be)tn.locateFile=nn=>tt??Be+nn;else if(Pe&&Pe.indexOf("blob:")!==0)tn.locateFile=nn=>new URL(nn,Pe).href;else if(nt){let nn=tr();nn&&(tn.locateFile=In=>nn+In)}Xe(tn).then(nn=>{_r=!1,Vi=!0,ps=nn,ut(),nt&&URL.revokeObjectURL(nt)},nn=>{_r=!1,Br=!0,Rn(nn)})})),await Promise.race(ze),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},Gt=()=>{if(Vi&&ps)return ps;throw new Error("WebAssembly is not initialized yet.")}}),Jn,Nn,Et,so=c(()=>{ir(),Jn=(oe,fe)=>{let we=Gt(),De=we.lengthBytesUTF8(oe)+1,Ee=we._malloc(De);return we.stringToUTF8(oe,Ee,De),fe.push(Ee),Ee},Nn=(oe,fe,we,De)=>{if(typeof oe=="object"&&oe!==null){if(we.has(oe))throw new Error("Circular reference in options");we.add(oe)}Object.entries(oe).forEach(([Ee,Be])=>{let $e=fe?fe+Ee:Ee;if(typeof Be=="object")Nn(Be,$e+".",we,De);else if(typeof Be=="string"||typeof Be=="number")De($e,Be.toString());else if(typeof Be=="boolean")De($e,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Et=oe=>{let fe=Gt(),we=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetLastError(Ee,Ee+De);let Be=Number(fe.getValue(Ee,De===4?"i32":"i64")),$e=fe.getValue(Ee+De,"*"),Pe=$e?fe.UTF8ToString($e):"";throw new Error(`${oe} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Pe}`)}finally{fe.stackRestore(we)}}}),Po,il=c(()=>{ir(),so(),Po=oe=>{let fe=Gt(),we=0,De=[],Ee=oe||{};try{if((oe==null?void 0:oe.logSeverityLevel)===void 0)Ee.logSeverityLevel=2;else if(typeof oe.logSeverityLevel!="number"||!Number.isInteger(oe.logSeverityLevel)||oe.logSeverityLevel<0||oe.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${oe.logSeverityLevel}`);if((oe==null?void 0:oe.logVerbosityLevel)===void 0)Ee.logVerbosityLevel=0;else if(typeof oe.logVerbosityLevel!="number"||!Number.isInteger(oe.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${oe.logVerbosityLevel}`);(oe==null?void 0:oe.terminate)===void 0&&(Ee.terminate=!1);let Be=0;return(oe==null?void 0:oe.tag)!==void 0&&(Be=Jn(oe.tag,De)),we=fe._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,Be),we===0&&Et("Can't create run options."),(oe==null?void 0:oe.extra)!==void 0&&Nn(oe.extra,"",new WeakSet,($e,Pe)=>{let Ge=Jn($e,De),tt=Jn(Pe,De);fe._OrtAddRunConfigEntry(we,Ge,tt)!==0&&Et(`Can't set a run config entry: ${$e} - ${Pe}.`)}),[we,De]}catch(Be){throw we!==0&&fe._OrtReleaseRunOptions(we),De.forEach($e=>fe._free($e)),Be}}}),Ro,Io,ga,Li,rl,sl,Dn=c(()=>{ir(),so(),Ro=oe=>{switch(oe){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: ${oe}`)}},Io=oe=>{switch(oe){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${oe}`)}},ga=oe=>{oe.extra||(oe.extra={}),oe.extra.session||(oe.extra.session={});let fe=oe.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),oe.executionProviders&&oe.executionProviders.some(we=>(typeof we=="string"?we:we.name)==="webgpu")&&(oe.enableMemPattern=!1)},Li=(oe,fe,we,De)=>{let Ee=Jn(fe,De),Be=Jn(we,De);Gt()._OrtAddSessionConfigEntry(oe,Ee,Be)!==0&&Et(`Can't set a session config entry: ${fe} - ${we}.`)},rl=async(oe,fe,we)=>{let De=fe.executionProviders;for(let Ee of De){let Be=typeof Ee=="string"?Ee:Ee.name,$e=[];switch(Be){case"webnn":if(Be="WEBNN",Li(oe,"session.disable_quant_qdq","1",we),Li(oe,"session.disable_qdq_constant_folding","1",we),typeof Ee!="string"){let nt=Ee==null?void 0:Ee.deviceType;nt&&Li(oe,"deviceType",nt,we)}break;case"webgpu":if(Be="JS",typeof Ee!="string"){let nt=Ee;if(nt!=null&&nt.preferredLayout){if(nt.preferredLayout!=="NCHW"&&nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${nt.preferredLayout}`);Li(oe,"preferredLayout",nt.preferredLayout,we)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Pe=Jn(Be,we),Ge=$e.length,tt=0,st=0;if(Ge>0){tt=Gt()._malloc(Ge*Gt().PTR_SIZE),we.push(tt),st=Gt()._malloc(Ge*Gt().PTR_SIZE),we.push(st);for(let nt=0;nt<Ge;nt++)Gt().setValue(tt+nt*Gt().PTR_SIZE,$e[nt][0],"*"),Gt().setValue(st+nt*Gt().PTR_SIZE,$e[nt][1],"*")}await Gt()._OrtAppendExecutionProvider(oe,Pe,tt,st,Ge)!==0&&Et(`Can't append execution provider: ${Be}.`)}},sl=async oe=>{let fe=Gt(),we=0,De=[],Ee=oe||{};ga(Ee);try{let Be=Ro(Ee.graphOptimizationLevel??"all"),$e=Io(Ee.executionMode??"sequential"),Pe=typeof Ee.logId=="string"?Jn(Ee.logId,De):0,Ge=Ee.logSeverityLevel??2;if(!Number.isInteger(Ge)||Ge<0||Ge>4)throw new Error(`log severity level is not valid: ${Ge}`);let tt=Ee.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let st=typeof Ee.optimizedModelFilePath=="string"?Jn(Ee.optimizedModelFilePath,De):0;if(we=fe._OrtCreateSessionOptions(Be,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,$e,!!Ee.enableProfiling,0,Pe,Ge,tt,st),we===0&&Et("Can't create session options."),Ee.executionProviders&&await rl(we,Ee,De),Ee.enableGraphCapture!==void 0){if(typeof Ee.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ee.enableGraphCapture}`);Li(we,"enableGraphCapture",Ee.enableGraphCapture.toString(),De)}if(Ee.freeDimensionOverrides)for(let[nt,Xe]of Object.entries(Ee.freeDimensionOverrides)){if(typeof nt!="string")throw new Error(`free dimension override name must be a string: ${nt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let $t=Jn(nt,De);fe._OrtAddFreeDimensionOverride(we,$t,Xe)!==0&&Et(`Can't set a free dimension override: ${nt} - ${Xe}.`)}return Ee.extra!==void 0&&Nn(Ee.extra,"",new WeakSet,(nt,Xe)=>{Li(we,nt,Xe,De)}),[we,De]}catch(Be){throw we!==0&&fe._OrtReleaseSessionOptions(we)!==0&&Et("Can't release session options."),De.forEach($e=>fe._free($e)),Be}}}),qi,ei,Ki,vs,oo,zs,Sr,Ni,Ut=c(()=>{qi=oe=>{switch(oe){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: ${oe}`)}},ei=oe=>{switch(oe){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: ${oe}`)}},Ki=(oe,fe)=>{let we=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][oe],De=typeof fe=="number"?fe:fe.reduce((Ee,Be)=>Ee*Be,1);return we>0?Math.ceil(De*we):void 0},vs=oe=>{switch(oe){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: ${oe}`)}},oo=oe=>{switch(oe){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: ${oe}`)}},zs=oe=>oe==="float32"||oe==="float16"||oe==="int32"||oe==="int64"||oe==="uint32"||oe==="uint8"||oe==="bool"||oe==="uint4"||oe==="int4",Sr=oe=>oe==="float32"||oe==="float16"||oe==="int32"||oe==="int64"||oe==="uint32"||oe==="uint64"||oe==="int8"||oe==="uint8"||oe==="bool"||oe==="uint4"||oe==="int4",Ni=oe=>{switch(oe){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: ${oe}`)}}}),ti,Bs=c(()=>{Hi(),ti=async oe=>{if(typeof oe=="string"){let fe=await fetch(oe);if(!fe.ok)throw new Error(`failed to load external data file: ${oe}`);let we=fe.headers.get("Content-Length"),De=we?parseInt(we,10):0;if(De<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${oe}, no response body.`);let Ee=fe.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch(Pe){if(Pe instanceof RangeError){let Ge=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Ge,maximum:Ge}).buffer}else throw Pe}let $e=0;for(;;){let{done:Pe,value:Ge}=await Ee.read();if(Pe)break;let tt=Ge.byteLength;new Uint8Array(Be,$e,tt).set(Ge),$e+=tt}return new Uint8Array(Be,0,De)}}else return oe instanceof Blob?new Uint8Array(await oe.arrayBuffer()):oe instanceof Uint8Array?oe:new Uint8Array(oe)}}),kr,va,Fs,rr,Yr,Gs,dn,Cr,ao,Fr,Ye,sr,mt,_e=c(()=>{vn(),il(),Dn(),Ut(),ir(),so(),Bs(),kr=(oe,fe)=>{Gt()._OrtInit(oe,fe)!==0&&Et("Can't initialize onnxruntime.")},va=async oe=>{kr(oe.wasm.numThreads,oo(oe.logLevel))},Fs=async(oe,fe)=>{var De,Ee;(Ee=(De=Gt()).asyncInit)==null||Ee.call(De);let we=oe.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(we){if(typeof we.limits!="object"||typeof we.features!="object"||typeof we.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=oe.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let $e=oe.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(we=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:$e}),!we)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")},rr=new Map,Yr=oe=>{let fe=Gt(),we=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetInputOutputCount(oe,Ee,Ee+De)!==0&&Et("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(fe.getValue(Ee,Be)),Number(fe.getValue(Ee+De,Be))]}finally{fe.stackRestore(we)}},Gs=(oe,fe)=>{let we=Gt(),De=we.stackSave(),Ee=0;try{let Be=we.PTR_SIZE,$e=we.stackAlloc(2*Be);we._OrtGetInputOutputMetadata(oe,fe,$e,$e+Be)!==0&&Et("Can't get session input/output metadata.");let Pe=Number(we.getValue($e,"*"));Ee=Number(we.getValue($e+Be,"*"));let Ge=we.HEAP32[Ee/4];if(Ge===0)return[Pe,0];let tt=we.HEAPU32[Ee/4+1],st=[];for(let nt=0;nt<tt;nt++){let Xe=Number(we.getValue(Ee+8+nt*Be,"*"));st.push(Xe!==0?we.UTF8ToString(Xe):Number(we.getValue(Ee+8+(nt+tt)*Be,"*")))}return[Pe,Ge,st]}finally{we.stackRestore(De),Ee!==0&&we._OrtFree(Ee)}},dn=oe=>{let fe=Gt(),we=fe._malloc(oe.byteLength);if(we===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${oe.byteLength}.`);return fe.HEAPU8.set(oe,we),[we,oe.byteLength]},Cr=async(oe,fe)=>{var st,nt,Xe;let we,De,Ee=Gt();Array.isArray(oe)?[we,De]=oe:oe.buffer===Ee.HEAPU8.buffer?[we,De]=[oe.byteOffset,oe.byteLength]:[we,De]=dn(oe);let Be=0,$e=0,Pe=[],Ge=[],tt=[];try{if([$e,Pe]=await sl(fe),(fe==null?void 0:fe.externalData)&&Ee.mountExternalData){let Bn=[];for(let fn of fe.externalData){let Di=typeof fn=="string"?fn:fn.path;Bn.push(ti(typeof fn=="string"?fn:fn.data).then(Yi=>{Ee.mountExternalData(Di,Yi)}))}await Promise.all(Bn)}for(let Bn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Bn=="string"?Bn:Bn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Bn!="string"){let fn=Bn,Di=fn==null?void 0:fn.context,Yi=fn==null?void 0:fn.gpuDevice,or=fn==null?void 0:fn.deviceType,al=fn==null?void 0:fn.powerPreference;Di?Ee.currentContext=Di:Yi?Ee.currentContext=await Ee.webnnCreateMLContext(Yi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:or,powerPreference:al})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}Be=await Ee._OrtCreateSession(we,De,$e),(st=Ee.webgpuOnCreateSession)==null||st.call(Ee,Be),Be===0&&Et("Can't create a session."),(nt=Ee.jsepOnCreateSession)==null||nt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(Be,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[$t,ze]=Yr(Be),ut=!!(fe!=null&&fe.enableGraphCapture),Rn=[],tn=[],nn=[],In=[],Bt=[];for(let Bn=0;Bn<$t;Bn++){let[fn,Di,Yi]=Gs(Be,Bn);fn===0&&Et("Can't get an input name."),Ge.push(fn);let or=Ee.UTF8ToString(fn);Rn.push(or),nn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}for(let Bn=0;Bn<ze;Bn++){let[fn,Di,Yi]=Gs(Be,Bn+$t);fn===0&&Et("Can't get an output name."),tt.push(fn);let or=Ee.UTF8ToString(fn);tn.push(or),In.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}return rr.set(Be,[Be,Ge,tt,null,ut,!1]),[Be,Rn,tn,nn,In]}catch($t){throw Ge.forEach(ze=>Ee._OrtFree(ze)),tt.forEach(ze=>Ee._OrtFree(ze)),Be!==0&&Ee._OrtReleaseSession(Be)!==0&&Et("Can't release session."),$t}finally{Ee._free(we),$e!==0&&Ee._OrtReleaseSessionOptions($e)!==0&&Et("Can't release session options."),Pe.forEach($t=>Ee._free($t)),(Xe=Ee.unmountExternalData)==null||Xe.call(Ee)}},ao=oe=>{var Ge,tt,st;let fe=Gt(),we=rr.get(oe);if(!we)throw new Error(`cannot release session. invalid session id: ${oe}`);let[De,Ee,Be,$e,Pe]=we;$e&&(Pe&&fe._OrtClearBoundOutputs($e.handle)!==0&&Et("Can't clear bound outputs."),fe._OrtReleaseBinding($e.handle)!==0&&Et("Can't release IO binding.")),(Ge=fe.jsepOnReleaseSession)==null||Ge.call(fe,oe),(tt=fe.webnnOnReleaseSession)==null||tt.call(fe,oe),(st=fe.webgpuOnReleaseSession)==null||st.call(fe,oe),Ee.forEach(nt=>fe._OrtFree(nt)),Be.forEach(nt=>fe._OrtFree(nt)),fe._OrtReleaseSession(De)!==0&&Et("Can't release session."),rr.delete(oe)},Fr=async(oe,fe,we,De,Ee,Be,$e=!1)=>{if(!oe){fe.push(0);return}let Pe=Gt(),Ge=Pe.PTR_SIZE,tt=oe[0],st=oe[1],nt=oe[3],Xe=nt,$t,ze;if(tt==="string"&&(nt==="gpu-buffer"||nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(nt==="gpu-buffer"){let tn=oe[2].gpuBuffer;ze=Ki(qi(tt),st);{let nn=Pe.jsepRegisterBuffer;if(!nn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=nn(De,Be,tn,ze)}}else if(nt==="ml-tensor"){let tn=oe[2].mlTensor;ze=Ki(qi(tt),st);let nn=Pe.webnnRegisterMLTensor;if(!nn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=nn(De,tn,qi(tt),st)}else{let tn=oe[2];if(Array.isArray(tn)){ze=Ge*tn.length,$t=Pe._malloc(ze),we.push($t);for(let nn=0;nn<tn.length;nn++){if(typeof tn[nn]!="string")throw new TypeError(`tensor data at index ${nn} is not a string`);Pe.setValue($t+nn*Ge,Jn(tn[nn],we),"*")}}else{let nn=Pe.webnnIsGraphInput,In=Pe.webnnIsGraphOutput;if(tt!=="string"&&nn&&In){let Bt=Pe.UTF8ToString(Ee);if(nn(De,Bt)||In(De,Bt)){let Bn=qi(tt);ze=Ki(Bn,st),Xe="ml-tensor";let fn=Pe.webnnCreateTemporaryTensor,Di=Pe.webnnUploadTensor;if(!fn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Yi=await fn(De,Bn,st);Di(Yi,new Uint8Array(tn.buffer,tn.byteOffset,tn.byteLength)),$t=Yi}else ze=tn.byteLength,$t=Pe._malloc(ze),we.push($t),Pe.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,ze),$t)}else ze=tn.byteLength,$t=Pe._malloc(ze),we.push($t),Pe.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,ze),$t)}}let ut=Pe.stackSave(),Rn=Pe.stackAlloc(4*st.length);try{st.forEach((nn,In)=>Pe.setValue(Rn+In*Ge,nn,Ge===4?"i32":"i64"));let tn=Pe._OrtCreateTensor(qi(tt),$t,ze,Rn,st.length,Ni(Xe));tn===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Be}.`),fe.push(tn)}finally{Pe.stackRestore(ut)}},Ye=async(oe,fe,we,De,Ee,Be)=>{var ar,ac,fd;let $e=Gt(),Pe=$e.PTR_SIZE,Ge=rr.get(oe);if(!Ge)throw new Error(`cannot run inference. invalid session id: ${oe}`);let tt=Ge[0],st=Ge[1],nt=Ge[2],Xe=Ge[3],$t=Ge[4];Ge[5];let ze=fe.length,ut=De.length,Rn=0,tn=[],nn=[],In=[],Bt=[],Bn=[],fn=$e.stackSave(),Di=$e.stackAlloc(ze*Pe),Yi=$e.stackAlloc(ze*Pe),or=$e.stackAlloc(ut*Pe),al=$e.stackAlloc(ut*Pe);try{[Rn,tn]=Po(Be),it("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)await Fr(we[hn],nn,Bt,oe,st[fe[hn]],fe[hn],$t);for(let hn=0;hn<ut;hn++)await Fr(Ee[hn],In,Bt,oe,nt[De[hn]],ze+De[hn],$t);ot("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)$e.setValue(Di+hn*Pe,nn[hn],"*"),$e.setValue(Yi+hn*Pe,st[fe[hn]],"*");for(let hn=0;hn<ut;hn++)$e.setValue(or+hn*Pe,In[hn],"*"),$e.setValue(al+hn*Pe,nt[De[hn]],"*");(ar=$e.jsepOnRunStart)==null||ar.call($e,tt),(ac=$e.webnnOnRunStart)==null||ac.call($e,tt);let Ai;Ai=await $e._OrtRun(tt,Yi,Di,ze,al,ut,or,Rn),Ai!==0&&Et("failed to call OrtRun().");let bs=[],md=[];it("wasm ProcessOutputTensor");for(let hn=0;hn<ut;hn++){let Jr=Number($e.getValue(or+hn*Pe,"*"));if(Jr===In[hn]||Bn.includes(In[hn])){bs.push(Ee[hn]),Jr!==In[hn]&&$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.");continue}let Fu=$e.stackSave(),Ws=$e.stackAlloc(4*Pe),xa=!1,vi,lr=0;try{$e._OrtGetTensorData(Jr,Ws,Ws+Pe,Ws+2*Pe,Ws+3*Pe)!==0&&Et(`Can't access output tensor data on index ${hn}.`);let lc=Pe===4?"i32":"i64",cr=Number($e.getValue(Ws,lc));lr=$e.getValue(Ws+Pe,"*");let gd=$e.getValue(Ws+Pe*2,"*"),Gu=Number($e.getValue(Ws+Pe*3,lc)),Vs=[];for(let xi=0;xi<Gu;xi++)Vs.push(Number($e.getValue(gd+xi*Pe,lc)));$e._OrtFree(gd)!==0&&Et("Can't free memory for tensor dims.");let Zr=Vs.reduce((xi,Zn)=>xi*Zn,1);vi=ei(cr);let ys=Xe==null?void 0:Xe.outputPreferredLocations[De[hn]];if(vi==="string"){if(ys==="gpu-buffer"||ys==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let xi=[];for(let Zn=0;Zn<Zr;Zn++){let Qr=$e.getValue(lr+Zn*Pe,"*"),vd=$e.getValue(lr+(Zn+1)*Pe,"*"),xd=Zn===Zr-1?void 0:vd-Qr;xi.push($e.UTF8ToString(Qr,xd))}bs.push([vi,Vs,xi,"cpu"])}else if(ys==="gpu-buffer"&&Zr>0){let xi=$e.jsepGetBuffer;if(!xi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Zn=xi(lr),Qr=Ki(cr,Zr);if(Qr===void 0||!zs(vi))throw new Error(`Unsupported data type: ${vi}`);xa=!0,bs.push([vi,Vs,{gpuBuffer:Zn,download:$e.jsepCreateDownloader(Zn,Qr,vi),dispose:()=>{$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(ys==="ml-tensor"&&Zr>0){let xi=$e.webnnEnsureTensor,Zn=$e.webnnIsGraphInputOutputTypeSupported;if(!xi||!Zn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ki(cr,Zr)===void 0||!Sr(vi))throw new Error(`Unsupported data type: ${vi}`);if(!Zn(oe,vi,!1))throw new Error(`preferredLocation "ml-tensor" for ${vi} output is not supported by current WebNN Context.`);let Qr=await xi(oe,lr,cr,Vs,!1);xa=!0,bs.push([vi,Vs,{mlTensor:Qr,download:$e.webnnCreateMLTensorDownloader(lr,vi),dispose:()=>{$e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr)}},"ml-tensor"])}else if(ys==="ml-tensor-cpu-output"&&Zr>0){let xi=$e.webnnCreateMLTensorDownloader(lr,vi)(),Zn=bs.length;xa=!0,md.push((async()=>{let Qr=[Zn,await xi];return $e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr),Qr})()),bs.push([vi,Vs,[],"cpu"])}else{let xi=vs(vi),Zn=new xi(Zr);new Uint8Array(Zn.buffer,Zn.byteOffset,Zn.byteLength).set($e.HEAPU8.subarray(lr,lr+Zn.byteLength)),bs.push([vi,Vs,Zn,"cpu"])}}finally{$e.stackRestore(Fu),vi==="string"&&lr&&$e._free(lr),xa||$e._OrtReleaseTensor(Jr)}}Xe&&!$t&&($e._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),rr.set(oe,[tt,st,nt,Xe,$t,!1]));for(let[hn,Jr]of await Promise.all(md))bs[hn][2]=Jr;return ot("wasm ProcessOutputTensor"),bs}finally{(fd=$e.webnnOnRunEnd)==null||fd.call($e,tt),$e.stackRestore(fn),nn.forEach(Ai=>$e._OrtReleaseTensor(Ai)),In.forEach(Ai=>$e._OrtReleaseTensor(Ai)),Bt.forEach(Ai=>$e._free(Ai)),Rn!==0&&$e._OrtReleaseRunOptions(Rn),tn.forEach(Ai=>$e._free(Ai))}},sr=oe=>{let fe=Gt(),we=rr.get(oe);if(!we)throw new Error("invalid session id");let De=we[0],Ee=fe._OrtEndProfiling(De);Ee===0&&Et("Can't get an profile file name."),fe._OrtFree(Ee)},mt=oe=>{let fe=[];for(let we of oe){let De=we[2];!Array.isArray(De)&&"buffer"in De&&fe.push(De.buffer)}return fe}}),Me,Qe,Tt,an,un,Ln,Mn,hi,Hn,gi,On,Xr,lo,Mo,xs,Bu,Oo,Lo,ud=c(()=>{vn(),_e(),ir(),nr(),Me=()=>!!I.wasm.proxy&&typeof document<"u",Tt=!1,an=!1,un=!1,hi=new Map,Hn=(oe,fe)=>{let we=hi.get(oe);we?we.push(fe):hi.set(oe,[fe])},gi=()=>{if(Tt||!an||un||!Qe)throw new Error("worker not ready")},On=oe=>{switch(oe.data.type){case"init-wasm":Tt=!1,oe.data.err?(un=!0,Mn[1](oe.data.err)):(an=!0,Mn[0]()),Ln&&(URL.revokeObjectURL(Ln),Ln=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=hi.get(oe.data.type);oe.data.err?fe.shift()[1](oe.data.err):fe.shift()[0](oe.data.out);break}}},Xr=async()=>{if(!an){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(un)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Me())return new Promise((oe,fe)=>{Qe==null||Qe.terminate(),Ls().then(([we,De])=>{try{Qe=De,Qe.onerror=Be=>fe(Be),Qe.onmessage=On,Mn=[oe,fe];let Ee={type:"init-wasm",in:I};if(!Ee.in.wasm.wasmPaths&&we){let Be=tr();Be&&(Ee.in.wasm.wasmPaths=Be)}Qe.postMessage(Ee),Ln=we}catch(Ee){fe(Ee)}},fe)});try{await gs(I.wasm),await va(I),an=!0}catch(oe){throw un=!0,oe}finally{Tt=!1}}},lo=async oe=>{if(Me())return gi(),new Promise((fe,we)=>{Hn("init-ep",[fe,we]);let De={type:"init-ep",in:{epName:oe,env:I}};Qe.postMessage(De)});await Fs(I,oe)},Mo=async oe=>Me()?(gi(),new Promise((fe,we)=>{Hn("copy-from",[fe,we]);let De={type:"copy-from",in:{buffer:oe}};Qe.postMessage(De,[oe.buffer])})):dn(oe),xs=async(oe,fe)=>{if(Me()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((we,De)=>{Hn("create",[we,De]);let Ee={type:"create",in:{model:oe,options:{...fe}}},Be=[];oe instanceof Uint8Array&&Be.push(oe.buffer),Qe.postMessage(Ee,Be)})}else return Cr(oe,fe)},Bu=async oe=>{if(Me())return gi(),new Promise((fe,we)=>{Hn("release",[fe,we]);let De={type:"release",in:oe};Qe.postMessage(De)});ao(oe)},Oo=async(oe,fe,we,De,Ee,Be)=>{if(Me()){if(we.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise(($e,Pe)=>{Hn("run",[$e,Pe]);let Ge=we,tt={type:"run",in:{sessionId:oe,inputIndices:fe,inputs:Ge,outputIndices:De,options:Be}};Qe.postMessage(tt,mt(Ge))})}else return Ye(oe,fe,we,De,Ee,Be)},Lo=async oe=>{if(Me())return gi(),new Promise((fe,we)=>{Hn("end-profiling",[fe,we]);let De={type:"end-profiling",in:oe};Qe.postMessage(De)});sr(oe)}}),ic,zo,ol,rc=c(()=>{vn(),ud(),Ut(),Hi(),Bs(),ic=(oe,fe)=>{switch(oe.location){case"cpu":return[oe.type,oe.dims,oe.data,"cpu"];case"gpu-buffer":return[oe.type,oe.dims,{gpuBuffer:oe.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[oe.type,oe.dims,{mlTensor:oe.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${oe.location} for ${fe()}`)}},zo=oe=>{switch(oe[3]){case"cpu":return new ge(oe[0],oe[2],oe[1]);case"gpu-buffer":{let fe=oe[0];if(!zs(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:we,download:De,dispose:Ee}=oe[2];return ge.fromGpuBuffer(we,{dataType:fe,dims:oe[1],download:De,dispose:Ee})}case"ml-tensor":{let fe=oe[0];if(!Sr(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:we,download:De,dispose:Ee}=oe[2];return ge.fromMLTensor(we,{dataType:fe,dims:oe[1],download:De,dispose:Ee})}default:throw new Error(`invalid data location: ${oe[3]}`)}},ol=class{async fetchModelAndCopyToWasmMemory(oe){return Mo(await ti(oe))}async loadModel(oe,fe){zt();let we;typeof oe=="string"?we=await this.fetchModelAndCopyToWasmMemory(oe):we=oe,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xs(we,fe),pt()}async dispose(){return Bu(this.sessionId)}async run(oe,fe,we){zt();let De=[],Ee=[];Object.entries(oe).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);De.push($t),Ee.push(ze)});let Be=[],$e=[];Object.entries(fe).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push($t),$e.push(ze)});let Pe=De.map((nt,Xe)=>ic(nt,()=>`input "${this.inputNames[Ee[Xe]]}"`)),Ge=Be.map((nt,Xe)=>nt?ic(nt,()=>`output "${this.outputNames[$e[Xe]]}"`):null),tt=await Oo(this.sessionId,Ee,Pe,$e,Ge,we),st={};for(let nt=0;nt<tt.length;nt++)st[this.outputNames[$e[nt]]]=Be[nt]??zo(tt[nt]);return pt(),st}startProfiling(){}endProfiling(){Lo(this.sessionId)}}}),Us={};h(Us,{OnnxruntimeWebAssemblyBackend:()=>Hs,initializeFlags:()=>co,wasmBackend:()=>Bo});var co,Hs,Bo,hd=c(()=>{vn(),ud(),rc(),co=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let oe=I.wasm.simd;if(typeof oe!="boolean"&&oe!==void 0&&oe!=="fixed"&&oe!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${oe}". 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"?l("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Hs=class{async init(oe){co(),await Xr(),await lo(oe)}async createInferenceSessionHandler(oe,fe){let we=new ol;return await we.loadModel(oe,fe),we}},Bo=new Hs}),pd={};h(pd,{InferenceSession:()=>Ze,TRACE:()=>Je,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>ge,default:()=>oc,env:()=>I,registerBackend:()=>y}),vn(),vn(),vn();var sc="1.26.0",oc=yr;{let oe=(hd(),f(Us)).wasmBackend;y("cpu",oe,10),y("wasm",oe,10)}return Object.defineProperty(I.versions,"web",{value:sc,enumerable:!0}),f(pd)})();n.exports=i})(fw)),fw.exports}var uk;function IP(){return uk||(uk=1,(function(n){var e=Al&&Al.__createBinding||(Object.create?(function(C,T,N,A){A===void 0&&(A=N);var P=Object.getOwnPropertyDescriptor(T,N);(!P||("get"in P?!T.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return T[N]}}),Object.defineProperty(C,A,P)}):(function(C,T,N,A){A===void 0&&(A=N),C[A]=T[N]})),i=Al&&Al.__setModuleDefault||(Object.create?(function(C,T){Object.defineProperty(C,"default",{enumerable:!0,value:T})}):function(C,T){C.default=T}),r=Al&&Al.__importStar||function(C){if(C&&C.__esModule)return C;var T={};if(C!=null)for(var N in C)N!=="default"&&Object.prototype.hasOwnProperty.call(C,N)&&e(T,C,N);return i(T,C),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(RP()),a=Q0(),d=e1(),l=sv(),c=ky(),h=Xj(),m=Jj();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",_="silero_vad_legacy.onnx",y=C=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.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 T=>{T.getTracks().forEach(N=>{N.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:T=>{T.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});n.getDefaultRealTimeVADOptions=y;const k=C=>"audioWorklet"in C&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(C,T,N,A,P){await N.audioWorklet.addModule(C),T.processorOptions={...T.processorOptions??{},frameSamples:A};const I=new AudioWorkletNode(N,"vad-helper-worklet",T);return I.port.onmessage=async O=>{const H=O.data;if(!(typeof H=="object"&&H&&"message"in H)){console.error("Invalid message event",H);return}switch(H.message){case c.Message.AudioFrame:{if(!("data"in H&&H.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const B=new Float32Array(H.data);await P(B);break}}},I}async function w(C,T,N){const A=new m.Resampler({nativeSampleRate:C.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const I=C.createScriptProcessor(4096,1,1);let O=!1;return I.onaudioprocess=async H=>{if(!O){O=!0;try{const B=H.inputBuffer.getChannelData(0);H.outputBuffer.getChannelData(0).fill(0);const Q=A.process(B);for(const W of Q)await N(W)}catch(B){console.error("Error processing audio:",B)}finally{O=!1}}},I.connect(C.destination),I}class S{constructor(T,N,A,P,I=!1,O=null,H=null,B=null,Z=null,Q=null,W=null,Y="uninitialized",ee=!1){this.options=T,this.frameProcessor=N,this.model=A,this.frameSamples=P,this.listening=I,this.errored=O,this._stream=H,this._audioContext=B,this._vadNode=Z,this._mediaStreamAudioSourceNode=Q,this._audioProcessorAdapterType=W,this.initializationState=Y,this.ownsAudioContext=ee,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=re=>{this.initializationState="errored",this.errored=re},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(re){throw re instanceof Error?this.setErrored(re.message):this.setErrored(String(re)),re}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"?k(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await w(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),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:re,audioContext:se,vadNode:F}=this.getAudioInstances();this._stream=await this.options.resumeStream(re);const te=new MediaStreamAudioSourceNode(se,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=te,te.connect(F);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:re,mediaStreamAudioSourceNode:se}=this.getAudioInstances();await this.options.pauseStream(re),se.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var se;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:re}=this.getAudioInstances();re instanceof AudioWorkletNode&&re.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((se=this._audioContext)==null?void 0:se.close())},this.setOptions=re=>{this.frameProcessor.setOptions(re)},this.processFrame=async re=>{await this.frameProcessor.process(re,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=re=>{switch(re.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(re.probs,re.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(re.audio);break}}}static async new(T={}){const N={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,d.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const A=N.model==="v5"?b:_,P=N.baseAssetPath+A,I=N.model==="v5"?h.SileroV5.new:h.SileroLegacy.new;let O;try{O=await I(n.ort,()=>(0,a.defaultModelFetcher)(P))}catch(W){throw console.error(`Encountered an error while loading model file ${P}`),W}const H=N.model==="v5"?512:1536,B=H/16,Z=new d.FrameProcessor(O.process,O.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},B),Q=new S(N,Z,O,H);if(N.startOnLoad)try{await Q.start()}catch(W){throw console.error("Error starting micVad",W),W}return Q}}n.MicVAD=S})(Al)),Al}var hk;function MP(){return hk||(hk=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=qj();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=Q0();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=e1();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=ky();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=$P();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const d=PP();n.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var l=IP();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(uw)),uw}var OP=MP();function vx(n,e,i,r,s){var d,l;try{(l=(d=window.api)==null?void 0:d.logs)==null||l.write(n,e,i,r,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?a(`[${n}]`,i,r):a(`[${n}]`,i)}const ht={debug:(n,e,i)=>vx(n,"debug",e,i),info:(n,e,i)=>vx(n,"info",e,i),warn:(n,e,i)=>vx(n,"warn",e,i),error:(n,e,i,r)=>vx(n,"error",e,i,r)},Qj=16e3,LP=6,wp=Qj*LP,zP=400,BP=Qj*zP/1e3,pk=300,fk=2e3,mk=1500,gk=3e3,FP=600,eT=.5,tT=.35,vk=.85,xk=.7;let As=null,Ka=!1,cs=!1;const j_=new Set;function xx(n){for(const e of Array.from(j_))try{e(n)}catch(i){ht.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let mw=0;const bk=2;let Mp=!1,nT=!1;function iT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";ht[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{ht.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),GP(`error:${e.message||"unknown"}`)})}function Mb(){return As||(As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),iT(As),ht.info("speech","worker spawned"),As)}let bx=!1;function GP(n){if(!Mp){if(bx){ht.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(bx=!0,mw+=1,nT=!0,ht.warn("speech","respawnWorker: starting",{reason:n,attempt:mw}),xx({reason:n,respawned:!1,finalOnly:!0}),mw>bk){if(Mp=!0,ht.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:bk}),As)try{As.terminate()}catch{}As=null,Ka=!1,cs=!1,xx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),bx=!1;return}if(As)try{As.terminate()}catch{}As=null,Ka=!1,cs=!1;try{As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),iT(As),cs=!0,As.postMessage({type:"load"}),ht.info("speech","respawnWorker: new worker spawned, load posted"),xx({reason:n,respawned:!0,finalOnly:!0})}catch(e){Mp=!0,ht.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),xx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{bx=!1}}}function UP(n,e){if(Ka||cs)return;cs=!0;const i=Mb();ht.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(Ka=!0,cs=!1,ht.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(cs=!1,ht.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),i.removeEventListener("message",r))};i.addEventListener("message",r),i.postMessage({type:"load"})}function HP(){ht.info("speech","resetModel: clearing load flags"),Ka=!1,cs=!1}function Cy(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function WP(n){const e=Mb();return!Ka&&!cs&&(cs=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var d,l,c;((d=a.data)==null?void 0:d.type)==="result"?(e.removeEventListener("message",s),i((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),r(new Error(String(a.data.error??"Transcription failed")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(Ka=!0,cs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function rT(n){let e=Mb(),i=!1,r=null,s=null,a=null,d=null,l=null;const c=[],h=new Set;let m=null,f=0,b=!1,_=0,y=!1,k=!1,x=0,w=0,S=0,C=-1,T=pk,N=0,A=null,P="",I="",O=!1,H=0;function B(ae,be){const Ne=Math.min(ae.length,be.length);let Se=0;for(;Se<Ne&&ae.charCodeAt(Se)===be.charCodeAt(Se);)Se++;return Se}function Z(ae){const be=B(P,ae);return P=ae,be>I.length&&(I=ae.slice(0,be)),I.length>ae.length&&(I=ae),I}const Q=()=>(m||(m=new Float32Array(wp)),m),W=()=>{f=0},Y=ae=>{const be=Q(),Ne=ae.length;if(Ne>=wp){be.set(ae.subarray(Ne-wp)),f=wp;return}if(f+Ne<=wp){be.set(ae,f),f+=Ne;return}const Se=f+Ne-wp;be.copyWithin(0,Se,f),f-=Se,be.set(ae,f),f+=Ne},ee=()=>{A&&(clearTimeout(A),A=null)},re=()=>{ee(),b=!1,y=!1,k=!1,T=pk,P="",I="",O=!1,H=0,W()},se=()=>{if(i||!b||k||y||A)return;if(f<BP){A=setTimeout(()=>{A=null,se()},T);return}const ae=performance.now()-x;if(ae<T&&x!==0){A=setTimeout(()=>{A=null,se()},T-ae);return}if(nT||Mp||n.partialsEnabled&&!n.partialsEnabled())return;const be=Q(),Ne=new Float32Array(f);Ne.set(be.subarray(0,f)),w+=1,S=w,y=!0,N=performance.now(),x=N,e.postMessage({type:"transcribe-partial",audio:Ne,seq:w},[Ne.buffer])},F=ae=>ae.length===0?Promise.resolve():Mp?(ht.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(be=>{c.push(be),w+=1;const Ne=w;C=Ne,e.postMessage({type:"transcribe",audio:ae,seq:Ne},[ae.buffer])}),te=ae=>{const be=F(ae);return h.add(be),be.finally(()=>{h.delete(be)}),be},q=ae=>{var be,Ne,Se,ce,J;if(ae.data.type==="result"){const me=ae.data.text,ge=ae.data.seq??0;ge&&ge<C&&ht.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ge,latestFinalSeq:C}),!i&&me&&n.onFinal(me),(be=c.shift())==null||be()}else if(ae.data.type==="partial"){const me=ae.data.seq??0,ge=ae.data.text??"",Fe=performance.now()-N;y=!1,Fe>=gk?(k=!0,ht.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Fe),seq:me})):Fe>=mk&&(T=Math.min(T*2,fk),ht.warn("speech","partials.slowdown",{elapsedMs:Math.round(Fe),newIntervalMs:T,seq:me})),O||(O=!0,Fe>FP&&T<500&&(T=500,ht.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Fe),newIntervalMs:500})));const Je=me!==S||me<=C;if(!i&&!Je&&ge){const dt=Z(ge);dt&&((Ne=n.onPartial)==null||Ne.call(n,dt),H===0&&(H=performance.now(),ht.info("speech","partial.first",{msSinceSpeechStart:Math.round(H-_)})))}se()}else if(ae.data.type==="partial-error"){const me=performance.now()-N;y=!1,me>=gk?(k=!0,ht.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(me),seq:ae.data.seq})):me>=mk&&(T=Math.min(T*2,fk),ht.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(me),newIntervalMs:T,seq:ae.data.seq})),ht.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),se()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(Se=c.shift())==null||Se()):ae.data.type==="status"?(i||(ce=n.onModelStatus)==null||ce.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(Ka=!0,cs=!1)):ae.data.type==="progress"&&(i||(J=n.onProgress)==null||J.call(n,ae.data.pct))};e.addEventListener("message",q);const le=ae=>{var be,Ne;if(!i){for(ht.warn("speech","createRecognition: worker death event",ae),(be=n.onStatusChange)==null||be.call(n,"restarting");c.length;)(Ne=c.shift())==null||Ne();if(h.clear(),ee(),y=!1,ae.respawned){try{e.removeEventListener("message",q)}catch{}e=Mb(),e.addEventListener("message",q)}}};return j_.add(le),{start:async()=>{if(!i){if(Mp){n.onError("Speech recognition disabled — please reload the app.");return}!Ka&&!cs&&(cs=!0,ht.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ht.info("speech","createRecognition.start: initializing VAD",{modelReady:Ka,modelLoading:cs});try{const ae=new URL("vad/",document.baseURI).href,be=n.inputDeviceId||null,Ne={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};be&&(Ne.deviceId={exact:be}),ht.info("speech","getUserMedia",{hasDeviceId:!!be,deviceIdPrefix:be?be.slice(0,8):null});const Se=await navigator.mediaDevices.getUserMedia({audio:Ne});s=Se,a=new AudioContext;for(const ce of Se.getAudioTracks())ce.addEventListener("ended",()=>{i||(ht.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),d=a.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,l.connect(d)}catch(ce){ht.warn("speech","analyser init failed",{error:ce instanceof Error?ce.message:String(ce)}),l=null,d=null}r=await OP.MicVAD.new({audioContext:a,getStream:async()=>Se,resumeStream:async()=>Se,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:eT,negativeSpeechThreshold:tT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ce,J)=>{var me;i||((me=n.onFrame)==null||me.call(n,ce),b&&(Y(J),se()))},onSpeechStart:()=>{var ce;i||(re(),b=!0,_=performance.now(),(ce=n.onSpeechStart)==null||ce.call(n))},onSpeechEnd:ce=>{var J;i||((J=n.onStatusChange)==null||J.call(n,"transcribing"),re(),te(ce))},onVADMisfire:()=>{var ce,J;i||((ce=n.onStatusChange)==null||ce.call(n,"idle"),re(),(J=n.onMisfire)==null||J.call(n))}}),r.start()}catch(ae){const be=ae instanceof Error?ae.message:"Microphone access denied",Ne=ae instanceof Error?ae.stack:"";if(ht.error("speech","createRecognition.start: VAD init failed",{error:be,stack:Ne}),d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Se=>Se.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(be)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(re();h.size>0;)await Promise.all(Array.from(h));if(r){try{await r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ae,be)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:be})}catch(Ne){ht.warn("speech","setVadThresholds failed",{error:Ne instanceof Error?Ne.message:String(Ne)})}},getAnalyser:()=>d,destroy:()=>{if(i=!0,re(),r){try{r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}j_.delete(le),e.removeEventListener("message",q)}}}let Ng=null;const T_=new Set,N_=new Set;function VP(){for(const n of T_)try{n()}catch{}}function D_(){for(const n of N_)try{n()}catch{}}function qP(n){return n.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 KP(n){if(!window.speechSynthesis)return;const e=qP(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{Ng=performance.now(),VP()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Ng=null,D_())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Ng=null,D_())},window.speechSynthesis.speak(i)}function sT(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Ng=null,D_())}function oT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function YP(){return Ng}function XP(n){return T_.add(n),()=>{T_.delete(n)}}function JP(n){return N_.add(n),()=>{N_.delete(n)}}function ZP(n){oT()&&(n.setVadThresholds(vk,xk),ht.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=XP(()=>{n.setVadThresholds(vk,xk),ht.info("voice","tts.duck.on")}),i=JP(()=>{n.setVadThresholds(eT,tT),ht.info("voice","tts.duck.off")});return()=>{e(),i()}}const QP=[{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 eR(n){const e=n.trim();return QP.find(i=>i.match.test(e))??null}const tR=4e4;let bu=null;function Op(){bu&&clearTimeout(bu),bu=setTimeout(()=>{bu=null,kt.getState().stopRecording()},tR)}function yx(){bu&&(clearTimeout(bu),bu=null)}let id=null,Qc=null;const nR=.04,iR=.3;let Ob=0,A_=0;function rR(n){Qc!==null&&cancelAnimationFrame(Qc);const e=()=>{if(id===null||kt.getState().submitCountdownStartAt===null){Qc=null;return}const i=performance.now();if(i-A_<200&&Ob>iR){const s=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Ob.toFixed(2),msIntoCountdown:Math.round(s)}),Kc(),Op();return}const r=aT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const d=Math.sqrt(a/s.length);if(d>nR){const l=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(l)}),Kc(),Op();return}}Qc=requestAnimationFrame(e)};Qc=requestAnimationFrame(e)}function yk(n){id&&clearTimeout(id);const e=kt.getState().submitDelayMs,i=performance.now();kt.setState({submitCountdownStartAt:i}),id=setTimeout(()=>{var s;id=null,kt.setState({submitCountdownStartAt:null});const r=vt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=Tn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(Tn.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),Tn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){ht.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Op()},e),rR(i)}function Kc(){Qc!==null&&(cancelAnimationFrame(Qc),Qc=null),id&&(clearTimeout(id),id=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let xr=null,Wr=null,Wm=null;function aT(){var n;return((n=xr==null?void 0:xr.getAnalyser)==null?void 0:n.call(xr))??null}const wx=1e4;let Dg=null;function _x(){Dg&&(clearTimeout(Dg),Dg=null)}let pb=null,fb=null;function Sx(){pb=null,fb&&(fb(),fb=null)}const sR=1500,oR=9e4;let kx=0,mb=null,$_=-1;function Cx(){mb&&(clearTimeout(mb),mb=null,$_=-1)}const aR=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=Ti((n,e)=>({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(e().modelStatus!=="idle")return;ht.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++kx,r=()=>{i===kx&&(Cx(),$_=i,mb=setTimeout(()=>{$_===i&&e().modelStatus==="loading"&&(ht.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},oR))};r(),UP((s,a)=>{i===kx&&(s==="ready"?(Cx(),ht.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Cx(),ht.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===kx&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{ht.info("voice","mic.gate.retry"),Cx(),HP(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(xr){ht.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Cy()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const d=rT({inputDeviceId:a,onStatusChange:l=>{n(l==="transcribing"?{statusPill:"transcribing"}:l==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:l=>{e().partialsEnabled&&n({lastPartial:l})},partialsEnabled:()=>e().partialsEnabled,onFrame:l=>{Ob=l.isSpeech,A_=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),yx(),Kc(),oT()){const c=YP(),h=c!==null?performance.now()-c:null;sT(),n({lastBargeInAt:performance.now()}),ht.info("voice","barge-in",{tabId:i,utteranceOffsetMs:h})}else ht.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Op();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&ht.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var b;Op();const c=l.trim();if(!c||aR.has(c)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Wm){Wm(c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=vt.getState().tabs.find(_=>_.id===i))==null?void 0:b.status)==="dormant"){Tn.getState().setPendingVoiceText(i,c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&yk(i);const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}const m=eR(c);if(m){ht.info("voice","voice-command",{tabId:i,label:m.label,transcript:c}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Kc();const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}window.api.pty.write({tabId:i,data:c}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&yk(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:c}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{ht.error("voice","recognition error",{err:l}),Kc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Wr==null||Wr(),Wr=null,yx(),xr==null||xr.destroy(),xr=null,Wm=null,Re.error(`Microphone error: ${l}`)},onModelStatus:l=>{l==="ready"?n({modelStatus:"ready",loadingProgress:100}):l==="loading"&&n({modelStatus:"loading"})},onProgress:l=>n({loadingProgress:Math.round(l)})});xr=d,Wm=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Op(),d.start().then(()=>{xr===d&&(Wr==null||Wr(),Wr=ZP(d))}).catch(l=>{const c=l instanceof Error?l.message:String(l);ht.error("voice","handle.start() failed",{error:c}),Re.error(`Could not start mic: ${c}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,d,l;return((l=(d=(a=window.api)==null?void 0:a.voice)==null?void 0:d.getDevicePref)==null?void 0:l.call(d))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ht.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=xr;i&&(yx(),Kc(),Ob=0,A_=0,Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),xr===i&&(xr=null,Wm=null),e().hotkeyState==="stopping"&&(_x(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=xr;if(!i)return;yx(),Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){ht.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),xr===i&&(xr=null);const{useSessions:r}=await rv(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>aP);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:i=>n({externalRecording:i}),toggleTTS:()=>n(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>n({autoSubmit:i}),setSubmitDelayMs:i=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Kc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ht.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),n({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&n({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(n({turnDetectorState:i}),i==="load_failed"?ht.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ht.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ht.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&n({wizardArmed:i})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:i,source:r,mode:s,tabId:a})=>{const d=e(),{canRecord:l,reason:c}=Lb(d);if(i==="down"){if(c==="error"||c==="load-timeout"){d.resetAndRetryModel(),ht.info("voice-hotkey","down.retry",{source:r,reason:c});return}if(!l&&c!=="loading"){ht.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:c});return}if(d.hotkeyState==="recording"||d.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),_x(),Dg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:wx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},wx),d.stopRecording());return}if(c==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),ht.info("voice-hotkey","armed",{source:r,modelStatus:d.modelStatus})),Sx(),pb={tabId:a,source:r,mode:s},fb=kt.subscribe((h,m)=>{if(pb&&h.modelStatus==="ready"&&m.modelStatus!=="ready"&&h.hotkeyState==="armed"){const f=pb;if(Sx(),!f.tabId){ht.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}ht.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),kt.getState().startRecording(f.tabId)}});return}if(!a){ht.warn("voice-hotkey","no-active-tab",{source:r});return}ht.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),d.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(ht.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(d.hotkeyState==="armed"){Sx(),ht.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),_x(),Dg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:wx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},wx),d.stopRecording())}},destroyHotkey:()=>{const i=e();if(Sx(),Kc(),i.hotkeyState==="recording"){ht.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(_x(),n({hotkeyState:"destroyed"}))}})),lR=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),Lb=n=>Cy()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const n=window;n.__voice=kt,n.__transcripts=[]}const cR=6e4,dR=5e3,Ag=Ti(()=>({data:null,refreshing:!1}));let wk=!1,gb=null,_k=null,Sk=!1;async function t1(){Ag.setState({refreshing:!0});let n=cR;try{const e=await W0(window.api.billing.fetch(),dR,"billing.fetch");Ag.setState({data:e,refreshing:!1}),e.kind==="transient"?n=_k==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),_k=e.kind}catch(e){if(Ag.setState({refreshing:!1}),!Sk){Sk=!0;const i=e instanceof Error?e.message:String(e);Re.warn(`Billing usage fetch failed: ${i}`)}}gb=setTimeout(t1,n)}function uR(){wk||(wk=!0,t1())}function lT(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function hR(){gb!==null&&(clearTimeout(gb),gb=null),t1()}function ov(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),i=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!i)return n;const r=i[1].charAt(0).toUpperCase()+i[1].slice(1).toLowerCase(),s=i[3]?`${i[2]}.${i[3]}`:i[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const Ex=new Map,pR=3e4;function n1(n){const[e,i]=R.useState(()=>{var r;return n?((r=Ex.get(n))==null?void 0:r.value)??null:null});return R.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=Ex.get(n);if(a&&Date.now()-a.ts<pR){r||i(a.value);return}try{const d=await window.api.app.gitBranch(n);if(r)return;Ex.set(n,{value:d,ts:Date.now()}),i(d)}catch{if(r)return;Ex.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function fR(n){return n.filter(e=>e.group==="Tools").map(({key:e,label:i,icon:r,hint:s})=>({key:e,label:i,icon:r,hint:s}))}const P_="sm.almanac.sidebarWidth",cT=180,dT=480,R_=252;function mR(){try{const n=parseInt(localStorage.getItem(P_)??"",10);if(Number.isFinite(n))return Math.min(dT,Math.max(cT,n))}catch{}return R_}const gR=52,uT="sm.almanac.sidebarCollapsed";function vR(){try{return localStorage.getItem(uT)==="1"}catch{}return!1}const hT="sm.almanac.collapsedGroups";function xR(){try{const n=localStorage.getItem(hT);if(!n)return new Set;const e=JSON.parse(n);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function bR(){const n=vt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:to(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function yR({active:n,onNavigate:e,onNewSession:i}){const[r,s]=R.useState(()=>xR()),a=R.useCallback(P=>{s(I=>{const O=new Set(I);O.has(P)?O.delete(P):O.add(P);try{localStorage.setItem(hT,JSON.stringify(Array.from(O)))}catch{}return O})},[]),[d,l]=R.useState(()=>vR()),c=R.useCallback(()=>{l(P=>{const I=!P;try{localStorage.setItem(uT,I?"1":"0")}catch{}return I})},[]),h=vt(P=>P.tabs),m=vt(P=>P.activeTabId),f=h.find(P=>P.id===m)??null,b=bR(),_=mn(P=>P.navFace),y=gP(_),k=y.filter(P=>P.group==="Workspace"),x=y.filter(P=>P.group==="Configure"),w=fR(y),[S,C]=R.useState(()=>mR()),T=R.useRef(S);T.current=S;const N=R.useCallback(P=>{P.preventDefault();const I=P.clientX,O=T.current;let H=O;const B=Q=>{H=Math.min(dT,Math.max(cT,O+(Q.clientX-I))),C(H)},Z=()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(P_,String(H))}catch{}};window.addEventListener("pointermove",B),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),A=R.useCallback(()=>{C(R_);try{localStorage.setItem(P_,String(R_))}catch{}},[]);return o.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?gR:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(wR,{tab:f,navFace:_,onNewSession:i,rail:d,onToggleRail:c}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!d&&o.jsx(gw,{label:"Workspace",desc:dw.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(d||!r.has("Workspace"))&&k.map(P=>o.jsx(kk,{item:P,active:n===P.key,live:P.liveKind?b[P.liveKind]:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(gw,{label:"Configure",desc:dw.Configure,collapsed:r.has("Configure"),count:x.length,onToggle:()=>a("Configure")}),(d||!r.has("Configure"))&&x.map(P=>o.jsx(kk,{item:P,active:n===P.key,live:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(gw,{label:"Tools",desc:dw.Tools,collapsed:r.has("Tools"),count:w.length,onToggle:()=>a("Tools")}),(d||!r.has("Tools"))&&w.map(P=>o.jsx(_R,{tool:P,active:n===P.key,onClick:()=>e(P.key),rail:d},P.key))]})}),o.jsx(SR,{rail:d,navFace:_}),!d&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:A,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 wR({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",d=n1((n==null?void 0:n.cwd)??null);return r?o.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[o.jsx("button",{onClick:i,"data-testid":"tour-new-session",title:"Open / Start Project",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:o.jsx(sn,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:s,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:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:o.jsx(sn,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),o.jsx("button",{onClick:s,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:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(sn,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(sn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),o.jsx("button",{onClick:s,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:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(sn,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[o.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),o.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(n==null?void 0:n.cwd)??"",children:a})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:d?`⌥${d}`:n?n.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(sn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function gw({label:n,desc:e,collapsed:i,count:r,onToggle:s}){return o.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[o.jsxs("button",{onClick:s,"aria-expanded":!i,title:i?`Expand ${n}`:`Collapse ${n}`,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:[o.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:i?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:n}),i&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!i&&o.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:e})]})}function kk({item:n,active:e,live:i,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:n.hint,"data-testid":n.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"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:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(sn,{name:n.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&i&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&i&&o.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 _R({tool:n,active:e,onClick:i,rail:r}){return o.jsxs("button",{onClick:i,title:n.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${e?"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:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(sn,{name:n.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]})]})}function SR({rail:n,navFace:e}){const i=kt(c=>c.isRecording),r=vt(c=>c.tabs),s=vt(c=>c.activeTabId),a=r.find(c=>c.id===s)??null,[d,l]=R.useState(null);return R.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return Mj(a.presetId).then(h=>{c||l((h==null?void 0:h.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?o.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"})}):o.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:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"}),(i||e==="project")&&o.jsx("span",{className:"truncate",title:d??"",children:i?"recording…":d?`Claude · ${ov(d)}`:"Claude Code"})]})}function kR(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function CR(n,e,i){return{tabId:n,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const vb=Ti((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,r,s)=>{const a={...e().refs};if(a[i]=(a[i]??0)+1,n({refs:a}),a[i]>1)return;n({tabs:{...e().tabs,[i]:CR(i,r,s)}});const d=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:d}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:m}=await rv(async()=>{const{toast:f}=await Promise.resolve().then(()=>Bj);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...c,path:null}}});return}n({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const h=await window.api.transcripts.buffer(i);for(const m of h)e().ingest(i,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const r={...e().refs};if(!r[i])return;if(r[i]--,r[i]>0){n({refs:r});return}delete r[i];const s=e().unsubs[i];s==null||s();const a={...e().unsubs};delete a[i];const d={...e().tabs};delete d[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:d})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const d=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:d},c=[],h=(m,f)=>m.length>f?m.slice(0,f-1)+"…":m;switch(r.kind){case"todo_write":{const m=Array.isArray(r.data)?r.data:[];l.todos=m,s!=null&&s.replay||c.push({id:0,kind:"todo-update",at:d,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const _ of["command","file_path","pattern","url","query","subagent_type","description"])f&&_ in f&&(b[_]=f[_]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:d},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const _=m.input,y=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(_==null?void 0:_.file_path)=="string"?_.file_path:void 0,x=typeof(_==null?void 0:_.command)=="string"?_.command:void 0,w=k?k.split("/").pop()??k:x?h(x,28):"";c.push({id:0,kind:"tool-use",at:d,label:w?`${m.name} · ${w}`:m.name,target:k??x,toolName:m.name}),y&&k&&c.push({id:0,kind:"file-edit",at:d,label:`${m.name} · ${h(k.split("/").pop()??k,34)}`,target:k,toolName:m.name})}break}case"plan":{const m=r.data,f=typeof m=="string"?m:(m==null?void 0:m.plan)??JSON.stringify(m);l.plans=[{at:d,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:d,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:d},...a.agents].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"agent-spawn",at:d,label:m!=null&&m.subagent_type?`Agent: ${h(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),b=m.input_tokens??m.inputTokens??0,_=m.output_tokens??m.outputTokens??0,y=f+b+_;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+_,cacheCreationInputTokens:(a.usage.cacheCreationInputTokens||0)+(m.cache_creation_input_tokens??m.cacheCreationInputTokens??0),cacheReadInputTokens:(a.usage.cacheReadInputTokens||0)+(m.cache_read_input_tokens??m.cacheReadInputTokens??0)},!(s!=null&&s.replay)&&Math.floor(y/1e3)>Math.floor(f/1e3)&&c.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(y/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=kR(a.agents,m==null?void 0:m.toolUseId,d);break}}if(c.length>0){let m=a.activitySeq;const f=c.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function ER(n){const e=vb(s=>s.subscribe),i=vb(s=>s.unsubscribe),r=vb(s=>n?s.tabs[n.id]:void 0);return R.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>i(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,i]),r}function jR({onNavigate:n}){const e=vt(C=>C.tabs),i=vt(C=>C.activeTabId),r=e.find(C=>C.id===i)??null,s=ER(r),a=(s==null?void 0:s.lastEventAt)??0,d=Ag(C=>C.data),l=to(C=>{var T;return((T=C.snapshot)==null?void 0:T.paused)??null}),c=n1((r==null?void 0:r.cwd)??null),[,h]=R.useState(0);R.useEffect(()=>{const C=setInterval(()=>h(T=>T+1),6e4);return()=>clearInterval(C)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=R.useState(!1),_=R.useRef(null);R.useEffect(()=>{if(!f)return;const C=T=>{_.current&&!_.current.contains(T.target)&&b(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[f]),R.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const y=lT(d),k=(y==null?void 0:y.usage.five_hour)??null,x=k?Math.round(k.utilization):null,w=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",S=a>0?DR(Date.now()-a):"—";return o.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:[o.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:w?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:w?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>n==null?void 0:n("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 ${l.reason==="auth"||l.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:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),r&&o.jsxs("span",{className:"text-fg-faint",title:r.cwd,children:[r.label,c&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(TR,{ref:_,todos:m,open:f,onToggle:()=>b(C=>!C)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.57.1"]})]})}const TR=R.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(d=>d.status==="completed").length,in_progress:e.filter(d=>d.status==="in_progress").length,pending:e.filter(d=>d.status==="pending").length};return o.jsxs("div",{ref:s,className:"relative",children:[o.jsxs("button",{onClick:r,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[o.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),o.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),o.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),o.jsxs("span",{className:"text-fg-faint",children:["todos ",i?"▾":"▴"]})]}),i&&o.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:o.jsx("ul",{className:"space-y-0.5",children:e.map((d,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(NR,{status:d.status}),o.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})]},l))})})]})});function NR({status:n}){return n==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?o.jsx("span",{className:"w-3 shrink-0",children:o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function DR(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function AR({onClose:n,onSent:e}){const i=vt(P=>P.tabs),[r,s]=R.useState(""),[a,d]=R.useState(()=>Object.fromEntries(i.map(P=>[P.id,!0]))),[l,c]=R.useState(!1),[h,m]=R.useState({}),f=R.useRef(null),b=R.useRef(e);R.useEffect(()=>{b.current=e},[e]),R.useEffect(()=>{d(P=>{const I={};for(const O of i)I[O.id]=P[O.id]??!0;return I})},[i]),R.useEffect(()=>{var P;(P=f.current)==null||P.focus()},[]),R.useEffect(()=>window.api.pty.onWriteError(I=>{m(O=>I.tabId in O?{...O,[I.tabId]:"skipped"}:O)}),[]),R.useEffect(()=>{if(Object.keys(h).length===0)return;const P=Object.values(h).filter(O=>O==="sent").length,I=window.setTimeout(()=>b.current(P),1500);return()=>window.clearTimeout(I)},[h]);const _=i.filter(P=>a[P.id]).map(P=>P.id),y=_.length,k=Object.keys(h).length>0,x=r.length>0&&y>0&&!l&&!k,w=()=>{if(!x)return;c(!0);const P=vt.getState().tabs,I=new Set(P.map(H=>H.id)),O={};for(const H of _)I.has(H)?(window.api.pty.write({tabId:H,data:r+"\r"}),O[H]="sent"):O[H]="skipped";m(O),c(!1)},S=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopPropagation(),n();return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),w())},C=i.length>0&&i.every(P=>a[P.id]),T=()=>{const P=!C;d(Object.fromEntries(i.map(I=>[I.id,P])))},N=Object.values(h).some(P=>P==="skipped"),A=k?N?"Sent (some skipped)":"Sent":`Send to ${y} tab${y===1?"":"s"}`;return o.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:S,"data-testid":"broadcast-bar",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),o.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),o.jsx("textarea",{ref:f,value:r,onChange:P=>s(P.target.value),rows:3,placeholder:"Prompt to broadcast…",className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono resize-y focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:C,onChange:T,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",y,"/",i.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:i.map(P=>o.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:!!a[P.id],onChange:I=>d(O=>({...O,[P.id]:I.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:P.label}),h[P.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[P.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},P.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),o.jsx("button",{onClick:w,disabled:!x,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:A})]})]})}function $R({tabId:n,cwd:e,onClose:i}){const r=Tg(y=>y.watchersForTab(n)),s=Tg(y=>y.add),a=Tg(y=>y.remove),d=R.useRef(null),[l,c]=R.useState(""),[h,m]=R.useState(""),[f,b]=R.useState(!1);R.useEffect(()=>{const y=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),R.useEffect(()=>{const y=k=>{d.current&&!d.current.contains(k.target)&&i()};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[i]);const _=async()=>{const y=h.trim();if(!y||f)return;b(!0);const k=await s({tabId:n,label:l.trim(),command:y,cwd:e});b(!1),k&&(c(""),m(""))};return o.jsxs("div",{ref:d,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[o.jsxs("div",{className:"flex items-center mb-2",children:[o.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),o.jsxs("span",{className:"text-fg-faint ml-2",children:[r.length," active"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:i,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[o.jsx("input",{value:l,onChange:y=>c(y.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{value:h,onChange:y=>m(y.target.value),onKeyDown:y=>{y.key==="Enter"&&_()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),o.jsx("button",{onClick:_,disabled:!h.trim()||f,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),o.jsxs("span",{className:"text-fg-faint",children:["cwd: ",o.jsx("span",{className:"font-mono",children:e})]})]}),r.length===0?o.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):o.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:r.map(y=>{const k=y.lines[y.lines.length-1];return o.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-fg truncate",children:y.label}),o.jsxs("span",{className:"text-fg-faint",children:[y.lineCount," line",y.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(y.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${y.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:y.command,children:y.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},y.watcherId)})})]})}/**
2902
2902
  * dockview-core
2903
2903
  * @version 6.6.1
2904
2904
  * @link https://github.com/mathuo/dockview
@@ -3076,7 +3076,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3076
3076
 
3077
3077
  ${i}`}const _g={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},A4=["popover","review","diff"],WN=["popover","review"];function $4(n,e){switch(e.type){case"SELECT":return{..._g,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{..._g,editCount:n.editCount};case"LISTEN":return WN.includes(n.phase)?{...n,phase:"listening",transcript:"",modelStatus:null}:n;case"HEARD":return n.phase!=="listening"?n:{...n,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return A4.includes(n.phase)?{...n,phase:"thinking",instruction:e.recordInstruction?e.instruction:n.instruction}:n;case"RUN_OK":return n.phase!=="thinking"?n:{...n,phase:"diff",diff:e.diff};case"RUN_ERR":return n.phase!=="thinking"?n:{...n,phase:"popover",transcript:"",diff:null};case"ACCEPT":return n.phase!=="diff"?n:{..._g,editCount:n.editCount+1};case"RESET_FILE":return{..._g,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function P4(n,e){let i=null;for(const r of e){const s=r.cwd;!s||!(n===s||n.startsWith(s.endsWith("/")?s:`${s}/`))||(i===null||s.length>i.length)&&(i=s)}return i}function R4(n,e,i){var a;let r=null,s=-1/0;for(const d of e){if(d.cwd!==n||d.status!=="dormant")continue;const l=((a=i[d.id])==null?void 0:a.lastEventAt)??0;(r===null||l>s)&&(r=d,s=l)}return r}const I4="sonnet";function M4(n,e){const[i,r]=R.useReducer($4,_g),s=R.useRef(0),a=R.useRef(null),d=R.useRef(n),l=R.useRef(new Map);R.useEffect(()=>window.api.docEdit.onSessionResult(C=>{const T=l.current.get(C.requestId);T&&(l.current.delete(C.requestId),T(C))}),[]),R.useEffect(()=>{d.current!==n&&(d.current=n,s.current+=1,c(),r({type:"RESET_FILE"}))},[n]);function c(){const C=a.current;C&&(a.current=null,C.stop().catch(()=>{}),C.destroy(),kt.setState({externalRecording:!1}))}const h=R.useCallback(C=>{s.current+=1,c(),r({type:"SELECT",selection:C})},[]),m=R.useCallback(()=>{s.current+=1,c(),r({type:"CANCEL"})},[]),f=R.useCallback(()=>{if(!WN.includes(i.phase))return;if(kt.getState().isRecording){Re.error("Microphone is already in use");return}if(!Cy()){Re.error("Microphone or Web Worker not available");return}const C=++s.current;r({type:"LISTEN"}),kt.setState({externalRecording:!0});const T=()=>{a.current===N&&(a.current=null),kt.setState({externalRecording:!1})},N=rT({onFinal:A=>{if(s.current!==C)return;N.stop().catch(()=>{}),N.destroy(),T();const P=A.trim();if(!P){r({type:"CANCEL"});return}r({type:"HEARD",transcript:P})},onError:A=>{s.current===C&&(N.destroy(),T(),Re.error(`Microphone error: ${A}`),r({type:"CANCEL"}))},onModelStatus:(A,P)=>{s.current===C&&r({type:"MODEL_STATUS",status:A,message:P})},onProgress:A=>{s.current===C&&r({type:"MODEL_STATUS",status:"loading",message:`${A}%`})}});a.current=N,N.start().catch(A=>{s.current===C&&(N.destroy(),T(),Re.error(`Could not start mic: ${A instanceof Error?A.message:String(A)}`),r({type:"CANCEL"}))})},[i.phase]),b=R.useCallback(()=>{const C=P4(n,vt.getState().tabs);if(!C)return null;const T=R4(C,vt.getState().tabs,vb.getState().tabs);return!T||Tn.getState().get(T.id).running?null:T},[n]),_=R.useCallback((C,T,N,A,P,I)=>{const O=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(H=>{l.current.set(O,H),window.api.docEdit.runInSession({tabId:C,sessionId:T,cwd:N,before:A,instruction:P,documentText:I,requestId:O})})},[]),y=R.useCallback(async(C,T)=>{const N=i.selection;if(!N)return;const A=++s.current;r({type:"RUN",instruction:C,recordInstruction:T});const P=D4(e);try{const I=b(),O=I?await _(I.id,I.sessionId,I.cwd,N.text,C,P):await window.api.docEdit.run({path:n,before:N.text,instruction:C,documentText:P});if(s.current!==A)return;if(!O.ok){Re.error(O.error||"Edit failed"),r({type:"RUN_ERR"});return}r({type:"RUN_OK",diff:{before:N.text,after:O.after??""}})}catch(I){if(s.current!==A)return;Re.error(I instanceof Error?I.message:"Edit failed"),r({type:"RUN_ERR"})}},[n,i.selection,e,b,_]),k=R.useCallback(C=>{y(C,!0)},[y]),x=R.useCallback(()=>{i.phase==="review"&&y(i.transcript,!0)},[y,i.phase,i.transcript]),w=R.useCallback(()=>{const C=i.instruction;C&&y(`${C}
3078
3078
 
3079
- (Give a different rewrite than the last one.)`,!1)},[y,i.instruction]),S=R.useCallback(C=>{const T=i.diff;if(!T)return{ok:!1,reason:"not-found"};const N=T4(C,T.before,T.after);return N.ok?(s.current+=1,r({type:"ACCEPT"})):Re.error(N.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),N},[i.diff]);return{state:i,select:h,cancel:m,listen:f,sendHeard:x,run:k,retry:w,accept:S}}const O4=[{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."}],QC=320,ig=8;function L4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function z4(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,ig),Math.max(ig,e-QC-ig)),r=Math.max(n.top-ig,ig);return{position:"fixed",left:i,top:r,width:QC,transform:"translateY(-100%)",zIndex:50}}function B4({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:d,onListen:l,onSendHeard:c,onCancel:h,onAccept:m,onReject:f,onRetry:b}){const[_,y]=R.useState(""),k=()=>{const x=_.trim();x&&(d(x),y(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:z4(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&o.jsxs("div",{className:"p-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{onClick:l,"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"}),O4.map(x=>o.jsx("button",{onClick:()=>a(x.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:x.label},x.label))]}),o.jsx("button",{onClick:h,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:_,onChange:x=>y(x.target.value),onKeyDown:x=>{x.key==="Enter"?k():x.key==="Escape"&&h()},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"})]}),n==="listening"&&o.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[o.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(L4,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:h,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[o.jsxs("p",{className:"italic text-fg mb-2",children:["«",r,"»"]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsxs("div",{className:"p-3 flex items-center justify-between",children:[o.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),o.jsx("button",{onClick:h,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&o.jsxs("div",{className:"p-3",children:[o.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function F4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function e2({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:d,onCancel:l,onAccept:c,onReject:h,onRetry:m}){return o.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[o.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),o.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:ov(I4)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&o.jsxs("div",{className:"text-fg-faint",children:[o.jsx("p",{children:"Select text in the doc…"}),o.jsxs("p",{className:"mt-2 text-[10px]",children:[r," edit",r===1?"":"s"," this session"]})]}),n==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(F4,{}),"Listening…"]}),s&&o.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),o.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{children:[o.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&i&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-3 space-y-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function t2(n){return n.split("/").filter(Boolean).pop()||n}function G4({path:n,onRenamed:e,onDeleted:i}){const[r,s]=R.useState(!1),[a,d]=R.useState(!1),[l,c]=R.useState(""),[h,m]=R.useState(!1),f=Pn(H=>H.buffers[n]),b=Pn(H=>H.openFile),_=Pn(H=>H.renameOpenFile),y=Pn(H=>H.closeFile),k=nc(),x=t2(n),w=()=>s(!1),S=()=>{c(x),d(!0),w()},C=async()=>{const H=l.trim();if(!H||H===x){d(!1);return}try{const B=await window.api.files.rename(n,H);if(B.ok){const Z=n.slice(0,n.lastIndexOf("/")),Q=B.newPath??`${Z}/${H}`;_(n,Q),e==null||e(n,Q),Re.info(`Renamed to ${H}`)}else Re.error(B.error??`Couldn't rename ${x}`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't rename ${x}`)}d(!1)},T=async()=>{w();try{const H=await window.api.files.duplicate(n);H.ok&&H.path?(b(H.path),Re.info(`Duplicated as ${t2(H.path)}`)):Re.error(H.error??`Couldn't duplicate ${x}`)}catch(H){Re.error(H instanceof Error?H.message:`Couldn't duplicate ${x}`)}},N=async()=>{try{const H=await window.api.files.delete(n);H.ok?(y(n),i==null||i(n),Re.info(`Deleted ${x}`)):Re.error(H.error??`Couldn't delete ${x}`)}catch(H){Re.error(H instanceof Error?H.message:`Couldn't delete ${x}`)}m(!1)},A=async()=>{w();const H=f??"";try{await navigator.clipboard.writeText(H),Re.info(`Copied ${H.length} chars`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't copy ${x}`)}},P=()=>{if(w(),!k){Re.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Re.info(`Added ${x} to Claude context`)},I=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(H=>{H.ok||Re.error(H.error??`Couldn't open ${x}`)}).catch(H=>Re.error(H instanceof Error?H.message:`Couldn't open ${x}`))},O=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(H=>{H.ok||Re.error(H.error??`Couldn't reveal ${x}`)}).catch(H=>Re.error(H instanceof Error?H.message:`Couldn't reveal ${x}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(H=>!H),className:`px-2 py-0.5 text-[10px] border border-line rounded ${r?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:w}),o.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:[o.jsx(Lw,{children:"Edit"}),o.jsx(du,{label:"Rename",onClick:S}),o.jsx(du,{label:"Duplicate",onClick:T}),o.jsx(du,{label:"Delete document",danger:!0,onClick:()=>{w(),m(!0)}}),o.jsx(n2,{}),o.jsx(Lw,{children:"Open"}),o.jsx(du,{label:"Open in default app",onClick:I}),o.jsx(du,{label:"Reveal in OS",onClick:O}),o.jsx(n2,{}),o.jsx(Lw,{children:"Export"}),o.jsx(du,{label:"Copy as Markdown",onClick:A}),o.jsx(du,{label:"Add to Claude context",onClick:P,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(U4,{value:l,onChange:c,onCancel:()=>d(!1),onConfirm:()=>void C()}),h&&o.jsx(H4,{name:x,onCancel:()=>m(!1),onConfirm:()=>void N()})]})}function Lw({children:n}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function du({label:n,onClick:e,danger:i,disabled:r,title:s}){return o.jsx("button",{onClick:e,disabled:r,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function n2(){return o.jsx("div",{className:"my-1 border-t border-line"})}function U4({value:n,onChange:e,onCancel:i,onConfirm:r}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:s=>{s.target===s.currentTarget&&i()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),o.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&i()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function H4({name:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function W4(){const[n,e]=R.useState(!1),i=Rp();return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>e(r=>!r),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>e(!1)}),o.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:[o.jsx(Ep,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>i.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),o.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:i.fontSize}),o.jsx("button",{onClick:()=>i.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(Ep,{label:"Word wrap",children:o.jsx(Ux,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(Ep,{label:"Minimap",children:o.jsx(Ux,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(Ep,{label:"Theme",children:o.jsx("button",{onClick:()=>i.setTheme(i.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:i.theme==="dark"?"Dark":"Paper"})}),o.jsx(Ep,{label:"Autosave",children:o.jsx(Ux,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(Ep,{label:"Wide measure",children:o.jsx(Ux,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function Ep({label:n,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Ux({on:n,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const V4=R.lazy(()=>rv(()=>import("./TiptapBody-B1llI4h-.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Hx(n){return n.split("/").filter(Boolean).pop()||n}function Wx(n,e){if(!e.length)return n;const i=new Set(e),r={};for(const[s,a]of Object.entries(n))i.has(s)||(r[s]=a);return r}function Vx(n){return SN(n)||kN(n)}function Zb(){const n=uv(),e=Pn(Ze=>Ze.openFiles),i=Pn(Ze=>Ze.activeFilePath),r=Pn(Ze=>Ze.dirty),s=Pn(Ze=>Ze.viewMode),a=Pn(Ze=>Ze.buffers),d=Pn(Ze=>Ze.setActive),l=Pn(Ze=>Ze.closeFile),c=Pn(Ze=>Ze.closeOthers),h=Pn(Ze=>Ze.closeToTheRight),m=Pn(Ze=>Ze.closeAll),f=Pn(Ze=>Ze.loadBuffer),b=Pn(Ze=>Ze.setBuffer),_=Pn(Ze=>Ze.markSaved),y=Pn(Ze=>Ze.setViewMode),k=Rp(),[x,w]=R.useState({}),[S,C]=R.useState({}),[T,N]=R.useState(null),[A,P]=R.useState(null),[I,O]=R.useState(!1),[H,B]=R.useState(!1),[Z,Q]=R.useState(!0),W=R.useRef(null),Y=R.useRef(null),ee=R.useRef(void 0),re=R.useRef(null),se=R.useRef(null),F=M4(i??"",a[i??""]??""),te=R.useCallback(Ze=>{W.current=Ze},[]),q=R.useCallback(()=>W.current,[]);R.useEffect(()=>{const Ze=i;if(!Ze||Vx(Ze))return;if(Pn.getState().hasBuffer(Ze)){w(xt=>xt[Ze]==="ready"?xt:{...xt,[Ze]:"ready"});return}let Ct=!1;return w(xt=>({...xt,[Ze]:"loading"})),window.api.files.read(Ze).then(xt=>{Ct||(xt.binary?w(pn=>({...pn,[Ze]:{binary:!0,size:xt.size??0,mime:xt.mime??"application/octet-stream",reason:xt.error??"Binary file"}})):xt.ok?(f(Ze,xt.text),w(pn=>({...pn,[Ze]:"ready"}))):w(pn=>({...pn,[Ze]:{error:xt.error??"failed to read"}})))}),()=>{Ct=!0}},[i,f]),R.useEffect(()=>{P(null)},[i]);const le=R.useCallback(async(Ze,Ct=!1)=>{const xt=Pn.getState().buffers[Ze];if(xt==null)return;Ct&&O(!0);const pn=await window.api.files.write(Ze,xt);pn.ok?(_(Ze),C($n=>({...$n,[Ze]:($n[Ze]??0)+1})),Ct||Re.info(`Saved ${Hx(Ze)}`)):Re.error(pn.error??`Couldn't save ${Hx(Ze)}`),Ct&&O(!1)},[_]);R.useEffect(()=>{if(!k.autosave)return;const Ze=i;if(!(!Ze||Vx(Ze)||!r[Ze]))return window.clearTimeout(ee.current),ee.current=window.setTimeout(()=>{le(Ze,!0)},1200),()=>window.clearTimeout(ee.current)},[k.autosave,i,r,a,le]);const ae=R.useCallback(Ze=>{Ze.length&&(w(Ct=>Wx(Ct,Ze)),C(Ct=>Wx(Ct,Ze)))},[]),be=R.useCallback((Ze,Ct)=>{w(xt=>Ze in xt?{...Wx(xt,[Ze]),[Ct]:xt[Ze]}:xt),C(xt=>Ze in xt?{...Wx(xt,[Ze]),[Ct]:xt[Ze]}:xt)},[]),Ne=R.useCallback(Ze=>{r[Ze]?N({kind:"one",path:Ze}):(l(Ze),ae([Ze]))},[r,l,ae]),Se=R.useCallback(Ze=>{e.some(xt=>xt.path!==Ze&&r[xt.path])?N({kind:"others",path:Ze}):(c(Ze),ae(e.filter(xt=>xt.path!==Ze).map(xt=>xt.path)))},[e,r,c,ae]),ce=R.useCallback(Ze=>{const Ct=e.findIndex(pn=>pn.path===Ze);Ct!==-1&&e.slice(Ct+1).some(pn=>r[pn.path])?N({kind:"right",path:Ze}):(h(Ze),ae(Ct!==-1?e.slice(Ct+1).map(pn=>pn.path):[]))},[e,r,h,ae]);R.useEffect(()=>{const Ze=Ct=>{if(n.current)if((Ct.metaKey||Ct.ctrlKey)&&(Ct.key==="s"||Ct.key==="S")){const xt=Pn.getState().activeFilePath;xt&&!Vx(xt)&&(Ct.preventDefault(),le(xt))}else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="f"||Ct.key==="F"))Ct.preventDefault(),B(xt=>!xt);else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="w"||Ct.key==="W")){const xt=Pn.getState().activeFilePath;xt&&Pn.getState().openFiles.length>1&&(Ct.preventDefault(),Se(xt))}else Ct.key==="Escape"&&F.state.phase!=="idle"?F.cancel():Ct.key==="Escape"&&H&&B(!1)};return window.addEventListener("keydown",Ze),()=>window.removeEventListener("keydown",Ze)},[le,H,Se,F.state.phase,F.cancel]),R.useEffect(()=>{if(F.state.phase==="idle")return;const Ze=Ct=>{var pn,$n;const xt=Ct.target;(pn=se.current)!=null&&pn.contains(xt)||($n=re.current)!=null&&$n.contains(xt)||F.cancel()};return window.addEventListener("mousedown",Ze),()=>window.removeEventListener("mousedown",Ze)},[F.state.phase,F.cancel]),R.useEffect(()=>{F.cancel()},[i,F.cancel]);const J=R.useCallback(()=>{e.some(Ct=>r[Ct.path])?N({kind:"all",path:""}):(m(),w({}),C({}))},[e,r,m]),me=()=>{if(T){if(T.kind==="one")l(T.path),ae([T.path]);else if(T.kind==="others"){const Ze=e.filter(Ct=>Ct.path!==T.path).map(Ct=>Ct.path);c(T.path),ae(Ze)}else if(T.kind==="right"){const Ze=e.findIndex(xt=>xt.path===T.path),Ct=Ze!==-1?e.slice(Ze+1).map(xt=>xt.path):[];h(T.path),ae(Ct)}else m(),w({}),C({});N(null)}};if(e.length===0)return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no file open"}),o.jsxs("div",{children:["open the ",o.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const ge=i,Fe=ge?Hx(ge):"",Je=ge?x[ge]:void 0,dt=ge?jN(ge):!1,zt=ge?F5(ge):!1,pt=ge&&dt?s[ge]??G5(ge):"edit",it=!!ge&&!Vx(ge)&&Je==="ready",ot=it,Dt=zt?["edit","wysiwyg","preview","split"]:dt?["edit","preview"]:[],on=ge&&o.jsx(X5,{path:ge,name:Fe,value:a[ge]??"",onChange:Ze=>b(ge,Ze),onSave:()=>void le(ge),onReady:te,onCursor:P}),gn=I?"Saving…":ge&&r[ge]?k.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!H&&o.jsx(V5,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:d,onCloseFile:Ne,onCloseOthers:Se,onCloseToTheRight:ce,onCloseAll:J}),ge&&!H&&o.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[o.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Fe}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:ge}),it&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",gn]}),Ol(ge)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:()=>Q(Ze=>!Ze),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Z?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ol(ge)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Ze=>o.jsx("button",{onClick:()=>y(ge,Ze),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${pt===Ze?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ze},Ze))}),o.jsx("div",{className:"flex-1"}),o.jsx(G4,{path:ge,onRenamed:be,onDeleted:Ze=>ae([Ze])}),it&&o.jsx(W4,{}),o.jsx("button",{onClick:()=>B(!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"})]}),H&&o.jsx("button",{onClick:()=>B(!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"}),o.jsx("div",{className:"flex-1 min-h-0",children:ge?SN(ge)?o.jsx(b4,{path:ge,name:Fe}):kN(ge)?o.jsx(y4,{path:ge}):Je&&typeof Je=="object"&&"binary"in Je?o.jsx(j4,{path:ge,name:Fe,size:Je.size,mime:Je.mime,reason:Je.reason}):Je&&typeof Je=="object"&&"error"in Je?o.jsx("div",{className:"p-6 text-xs text-red-400",children:Je.error}):Je!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):pt==="wysiwyg"&&Ol(ge)?o.jsx(R.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(V4,{value:a[ge]??"",onChange:Ze=>b(ge,Ze)},ge)}):pt==="split"&&Ol(ge)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(XC,{text:a[ge]??"",scrollRef:Y}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(YC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:on})]}),o.jsx("div",{ref:re,className:"flex-1 min-w-0",children:o.jsx(t0,{ref:Y,text:a[ge]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!H&&k.assistantRail&&o.jsx(e2,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ze=F.accept(a[ge]??"");Ze.ok&&b(ge,Ze.next)},onReject:F.cancel,onRetry:F.retry})]}):pt==="preview"&&Ol(ge)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(XC,{text:a[ge]??"",scrollRef:Y}),o.jsx("div",{ref:re,className:"flex-1 min-w-0",children:o.jsx(t0,{ref:Y,text:a[ge]??"",wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!H&&k.assistantRail&&o.jsx(e2,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ze=F.accept(a[ge]??"");Ze.ok&&b(ge,Ze.next)},onReject:F.cancel,onRetry:F.retry})]}):pt==="preview"&&_N(ge)?o.jsx(v4,{path:ge,dirty:!!r[ge],reloadToken:S[ge]??0}):pt==="preview"&&CN(ge)?o.jsx(_4,{path:ge,text:a[ge]??""}):pt==="preview"&&EN(ge)?o.jsx(C4,{path:ge,text:a[ge]??""}):Ol(ge)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(YC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:on})]}):on:null}),ot&&o.jsx(g4,{text:a[ge]??"",cursor:A,language:no(ge)||void 0}),ge&&Ol(ge)&&(pt==="preview"||pt==="split")&&F.state.phase!=="idle"&&F.state.selection&&o.jsx("div",{ref:se,children:o.jsx(B4,{phase:F.state.phase,rect:F.state.selection.rect,diff:F.state.diff,transcript:F.state.transcript,modelStatus:F.state.modelStatus,onQuickAction:F.run,onRunCustom:F.run,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onReject:F.cancel,onRetry:F.retry,onAccept:()=>{const Ze=F.accept(a[ge]??"");Ze.ok&&b(ge,Ze.next)}})}),T&&o.jsx(q4,{message:T.kind==="one"?`Discard unsaved changes to ${Hx(T.path)}?`:T.kind==="others"?"Discard unsaved changes in the other open files?":T.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:me})]})}function q4({message:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const i2={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"},K4={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 zw(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function Y4({open:n,onClose:e,variant:i="overlay"}){const r=vt(N=>N.tabs.find(A=>A.id===N.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,d]=R.useState(null),[l,c]=R.useState(!1),[h,m]=R.useState(null),f=R.useRef(null),b=R.useCallback(async N=>{c(!0),m(null);try{const A=await window.api.repo.analyze(N);A.ok?d(A):(m(A.error||"Analysis failed"),d(null))}catch(A){m(A instanceof Error?A.message:String(A)),d(null)}finally{c(!1)}},[]);R.useEffect(()=>{if(n){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[n,s,b]),R.useEffect(()=>{var A;if(!n)return;const N=P=>{P.key==="Escape"&&(P.stopPropagation(),e())};return window.addEventListener("keydown",N),(A=f.current)==null||A.focus(),()=>window.removeEventListener("keydown",N)},[n,e]);const _=R.useCallback(()=>{s&&b(s)},[s,b]),y=R.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([A,P])=>[A,P.files,P.lines]).sort((A,P)=>P[1]-A[1]).slice(0,12):[],[a]),k=R.useMemo(()=>y.length===0?1:y[0][1],[y]),x=R.useMemo(()=>{if(!a)return[];const N=a.topDirectories;if(N.length===0)return[];const A=N.map(I=>Math.sqrt(Math.max(1,I.fileCount))),P=A.reduce((I,O)=>I+O,0)||1;return N.map((I,O)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:A[O]/P*100}))},[a]);if(!n)return null;const w=N=>{N.target===N.currentTarget&&e()},S=s?s.split("/").filter(Boolean).pop()||s:"no folder",C=i==="page",T=o.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:w,"data-testid":"repoviz-backdrop",children:o.jsxs("div",{ref:f,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:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[o.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),o.jsxs("div",{className:"text-xs text-fg-dim truncate",title:s??"",children:[S,(a==null?void 0:a.gitStatus.branch)&&o.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",a.gitStatus.branch,")"]}),(a==null?void 0:a.truncated)&&o.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[a&&a.gitStatus.uncommitted>0&&o.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${a.gitStatus.uncommitted} uncommitted files`,children:[a.gitStatus.uncommitted," uncommitted"]}),o.jsxs("button",{type:"button",onClick:_,disabled:l||!s,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:[l?"…":"↻"," Refresh"]}),o.jsx("button",{type:"button",onClick:e,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:l&&!a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[o.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),o.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),o.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):h?o.jsxs("div",{className:"py-16 text-center",children:[o.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),o.jsx("div",{className:"text-sm text-red-400",children:h})]}):a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[o.jsx(Bw,{label:"Files",value:zw(a.totalFiles)}),o.jsx(Bw,{label:"Lines of code",value:zw(a.totalLines)}),o.jsx(Bw,{label:"Uncommitted",value:String(a.gitStatus.uncommitted),tone:a.gitStatus.uncommitted>0?"warn":"neutral"})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),y.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:y.map(([N,A,P])=>{const I=i2[N]??i2.other,O=K4[N]??N,H=A/k*100;return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-24 text-fg-dim truncate",title:O,children:O}),o.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:o.jsx("div",{className:"h-full rounded",style:{width:`${H}%`,backgroundColor:I}})}),o.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[A," files"]}),o.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[zw(P)," L"]})]},N)})})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),x.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):o.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:x.map(N=>o.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(N.basis,6)}%`,flexGrow:N.basis>15?1:0},title:`${N.path} — ${N.fileCount} files, ${N.totalLines.toLocaleString()} lines`,children:[o.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:N.path}),o.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[N.fileCount," files"]})]},N.path))})]}),o.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",a.durationMs,"ms",a.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):o.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?Iu.createPortal(T,document.body):T}function Bw({label:n,value:e,tone:i="neutral"}){const r=i==="warn"?"text-amber-400":"text-fg";return o.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[o.jsx("div",{className:`text-xl font-medium ${r}`,children:e}),o.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:n})]})}const r2=n=>/[/\\\-_.\s]/.test(n),s2=n=>n>="A"&&n<="Z";function X4(n,e,i){if(!n)return{match:!0,score:0,matched:[]};const r=n.toLowerCase(),s=e.toLowerCase(),a=(i||e).toLowerCase(),d=e.split("/").pop()||e,l=d.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:d.length},(w,S)=>S)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:n.length},(w,S)=>S)};let c=0;for(const w of a.split("/")){if(w===r)return{match:!0,score:800,matched:[]};w.startsWith(r)&&(c=Math.max(c,700))}const h=l.indexOf(r);if(h!==-1)return{match:!0,score:h===0||r2(l[h-1])||s2(d[h])?650:600,matched:Array.from({length:n.length},(S,C)=>h+C)};if(a.includes(r))return{match:!0,score:Math.max(500,c),matched:[]};let m=0,f=0,b=0,_=-1,y=0;const k=[];for(let w=0;w<s.length&&m<r.length;w++)s[w]===r[m]&&(k.push(w),f+=10,_===w-1?(b++,f+=b*8):b=0,(w===0||r2(s[w-1])||s2(e[w]))&&(y++,f+=15,w===0&&(f+=10)),_=w,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,y>=r.length*.5&&(f+=30),k.length>1){const w=k[k.length-1]-k[0];w>r.length*3&&(f-=Math.min(50,(w-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:k}}function Fw(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function o2(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const a2="session-manager.quickopen.recent",J4=8;function Z4({open:n,onClose:e,variant:i="overlay"}){const r=vt(O=>O.tabs.find(H=>H.id===O.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState([]),[h,m]=R.useState(!1),[f,b]=R.useState(0),[_,y]=R.useState([]),k=R.useRef(null),x=R.useRef(null);R.useEffect(()=>{if(n)try{const O=localStorage.getItem(a2);O&&y(JSON.parse(O))}catch{}},[n]),R.useEffect(()=>{if(!n){d(""),b(0);return}const O=setTimeout(()=>{var H;return(H=k.current)==null?void 0:H.focus()},0);return()=>clearTimeout(O)},[n]),R.useEffect(()=>{if(!n||!s)return;let O=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(H=>{if(!O){if(!H.ok){Re.error(`File search failed: ${H.error??"unknown error"}`),c([]);return}c(H.files)}}).catch(H=>{const B=H instanceof Error?H.message:String(H);ht.error("quick-open","search.files threw",{error:B},{cwd:s,tabId:r==null?void 0:r.id}),Re.error(`File search failed: ${B}`),c([])}).finally(()=>{O||m(!1)}),()=>{O=!0}},[n,s]);const w=R.useMemo(()=>{if(!a.trim())return[...l].sort((Z,Q)=>Z.name.localeCompare(Q.name)).slice(0,100).map(Z=>({file:Z,score:0,matched:[]}));const O=a.trim(),H=[];for(const B of l){const Z=X4(O,B.name,B.path);Z.match&&H.push({file:B,score:Z.score,matched:Z.matched})}return H.sort((B,Z)=>Z.score-B.score),H.slice(0,100)},[l,a]),S=R.useMemo(()=>a.trim()?[]:_.map(O=>l.find(H=>H.path===O)||null).filter(O=>O!==null).slice(0,5),[_,l,a]);R.useEffect(()=>{const O=S.length+w.length;f>=O&&b(Math.max(0,O-1))},[S.length,w.length,f]),R.useEffect(()=>{if(!x.current)return;const O=x.current.querySelector(`[data-row="${f}"]`);O&&O.scrollIntoView({block:"nearest"})},[f]);const C=R.useCallback(O=>{try{const Q=[O,..._.filter(W=>W!==O)].slice(0,J4);y(Q),localStorage.setItem(a2,JSON.stringify(Q))}catch{}const H=r==null?void 0:r.id;if(!H){Re.error("No active tab to receive file path");return}const Z=(s?Fw(O,s):O)||O;try{window.api.pty.write({tabId:H,data:Z})}catch(Q){const W=Q instanceof Error?Q.message:String(Q);ht.error("quick-open","pty.write failed",{error:W},{cwd:s,tabId:H}),Re.error(`Failed to write to terminal: ${W}`);return}e()},[r==null?void 0:r.id,s,_,e]),T=R.useCallback(O=>{const H=S.length+w.length;if(O.key==="Escape"){O.preventDefault(),e();return}if(O.key==="ArrowDown"){if(O.preventDefault(),H===0)return;b(B=>Math.min(H-1,B+1));return}if(O.key==="ArrowUp"){if(O.preventDefault(),H===0)return;b(B=>Math.max(0,B-1));return}if(O.key==="Enter"){if(O.preventDefault(),f<S.length){const Q=S[f];Q&&C(Q.path);return}const B=f-S.length,Z=w[B];Z&&C(Z.file.path)}},[f,w,S,C,e]);if(!n)return null;const N=(O,H)=>{if(H.length===0)return O;const B=new Set(H);return O.split("").map((Z,Q)=>o.jsx("span",{className:B.has(Q)?"text-accent font-semibold":"",children:Z},Q))};let A=-1;const P=i==="page",I=o.jsx("div",{className:P?"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:P?void 0:O=>{O.target===O.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:P?void 0:"dialog","aria-modal":P?void 0:"true","aria-label":"Quick Open",className:P?"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:T,children:[o.jsx("div",{className:"border-b border-line p-2",children:o.jsx("input",{ref:k,type:"text",value:a,onChange:O=>{d(O.target.value),b(0)},placeholder:s?"Search files in this project…":"No active tab — open a terminal first",disabled:!s,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"})}),o.jsx("div",{ref:x,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:h?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):s?S.length===0&&w.length===0?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:a?"No files match.":"No files found in this project."}):o.jsxs(o.Fragment,{children:[S.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),S.map(O=>{A++;const H=A,B=H===f;return o.jsxs("button",{"data-row":H,role:"option","aria-selected":B,onClick:()=>C(O.path),onMouseEnter:()=>b(H),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${B?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:O.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Fw(o2(O.path),s)})]},`r:${O.path}`)})]}),w.length>0&&o.jsxs("div",{children:[S.length>0&&o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),w.map(({file:O,matched:H})=>{A++;const B=A,Z=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":Z,onClick:()=>C(O.path),onMouseEnter:()=>b(B),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Z?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:N(O.name,H)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Fw(o2(O.path),s)})]},O.path)})]})]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[w.length+S.length," ",w.length+S.length===1?"file":"files"]})]})]})});return!P&&typeof document<"u"&&document.body?Iu.createPortal(I,document.body):I}function l2(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function Q4(n,e,i){if(!e)return n;const r=i?n:n.toLowerCase(),s=i?e:e.toLowerCase(),a=r.indexOf(s);return a<0?n:o.jsxs(o.Fragment,{children:[n.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:n.slice(a,a+e.length)}),n.slice(a+e.length)]})}function eB({open:n,onClose:e,variant:i="overlay"}){const r=vt(Q=>Q.tabs.find(W=>W.id===Q.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState(!1),[h,m]=R.useState([]),[f,b]=R.useState(!1),[_,y]=R.useState(null),[k,x]=R.useState(0),[w,S]=R.useState(null),C=R.useRef(null),T=R.useRef(null),N=R.useRef(0);R.useEffect(()=>{if(!n){d(""),m([]),y(null),x(0);return}const Q=setTimeout(()=>{var W;return(W=C.current)==null?void 0:W.focus()},0);return()=>clearTimeout(Q)},[n]),R.useEffect(()=>{if(!n||!s)return;const Q=a.trim();if(!Q){m([]),y(null),b(!1);return}const W=++N.current;b(!0);const Y=setTimeout(()=>{window.api.search.text(s,Q,{caseSensitive:l,limit:500}).then(ee=>{W===N.current&&(ee.ok?(m(ee.matches),y(null)):(y(ee.error??"unknown error"),m([])),S(ee.usedRipgrep))}).catch(ee=>{if(W!==N.current)return;const re=ee instanceof Error?ee.message:String(ee);ht.error("global-search","search.text threw",{error:re},{cwd:s,tabId:r==null?void 0:r.id}),y(re),m([])}).finally(()=>{W===N.current&&b(!1)})},250);return()=>clearTimeout(Y)},[n,s,a,l]);const A=R.useMemo(()=>{const Q=new Map;for(const Y of h){const ee=Q.get(Y.path);ee?ee.push(Y):Q.set(Y.path,[Y])}const W=[];for(const[Y,ee]of Q)W.push({path:Y,matches:ee});return W.sort((Y,ee)=>ee.matches.length-Y.matches.length||Y.path.localeCompare(ee.path)),W},[h]),P=R.useMemo(()=>h,[h]);R.useEffect(()=>{k>=P.length&&x(Math.max(0,P.length-1))},[P.length,k]),R.useEffect(()=>{if(!T.current)return;const Q=T.current.querySelector(`[data-match="${k}"]`);Q&&Q.scrollIntoView({block:"nearest"})},[k]);const I=R.useCallback(Q=>{const W=r==null?void 0:r.id;if(!W){Re.error("No active tab to receive path");return}const ee=`${(s?l2(Q.path,s):Q.path)||Q.path}:${Q.line}`;try{window.api.pty.write({tabId:W,data:ee})}catch(re){const se=re instanceof Error?re.message:String(re);ht.error("global-search","pty.write failed",{error:se},{cwd:s,tabId:W}),Re.error(`Failed to write to terminal: ${se}`);return}e()},[r==null?void 0:r.id,s,e]),O=R.useCallback(Q=>{if(Q.key==="Escape"){Q.preventDefault(),e();return}if(Q.key==="ArrowDown"){if(Q.preventDefault(),P.length===0)return;x(W=>Math.min(P.length-1,W+1));return}if(Q.key==="ArrowUp"){if(Q.preventDefault(),P.length===0)return;x(W=>Math.max(0,W-1));return}if(Q.key==="Enter"){Q.preventDefault();const W=P[k];W&&I(W)}},[P,k,I,e]);if(!n)return null;const H=i==="page";let B=-1;const Z=o.jsx("div",{className:H?"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:H?void 0:Q=>{Q.target===Q.currentTarget&&e()},"data-testid":"global-search-backdrop",children:o.jsxs("div",{role:H?void 0:"dialog","aria-modal":H?void 0:"true","aria-label":"Search in project",className:H?"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:O,children:[o.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[o.jsx("input",{ref:C,type:"text",value:a,onChange:Q=>{d(Q.target.value),x(0)},placeholder:s?"Search in this project…":"No active tab — open a terminal first",disabled:!s,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"}),o.jsx("button",{type:"button",onClick:()=>c(Q=>!Q),className:`px-2 py-1 text-xs rounded border ${l?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":l,children:"Aa"})]}),o.jsx("div",{ref:T,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:s?a.trim()?f?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):_?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:_}):P.length===0?o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(a),"."]}):o.jsx("div",{children:A.map(Q=>o.jsxs("div",{children:[o.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:[l2(Q.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",Q.matches.length,")"]})]}),Q.matches.map(W=>{B++;const Y=B,ee=Y===k;return o.jsxs("button",{"data-match":Y,role:"option","aria-selected":ee,onClick:()=>I(W),onMouseEnter:()=>x(Y),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ee?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:W.line}),o.jsx("span",{className:"truncate",children:Q4(W.text,a,l)})]},`${W.path}:${W.line}:${W.column}:${Y}`)})]},Q.path))}):o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",o.jsx("span",{className:"font-mono",children:s}),"."]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[P.length," ",P.length===1?"match":"matches",w===!1&&" · fs walk (rg missing)"]})]})]})});return!H&&typeof document<"u"&&document.body?Iu.createPortal(Z,document.body):Z}const tB=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function nB({open:n,onClose:e,variant:i="page",initialMode:r="files"}){const[s,a]=R.useState(r);return R.useEffect(()=>{a(r)},[r]),n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[o.jsx(Ao,{options:tB,active:s,onChange:a}),o.jsx("span",{className:"text-[11px] text-fg-faint",children:s==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),o.jsx("div",{className:"flex-1 min-h-0",children:s==="files"?o.jsx(Z4,{open:!0,onClose:e,variant:"page"}):o.jsx(eB,{open:!0,onClose:e,variant:"page"})})]}):null}const iB={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},c2='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function tf({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:d=!1,variant:l="overlay"}){if(l==="page")return n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[r&&o.jsx("h2",{className:`text-base font-medium text-fg ${d?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:r}),o.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${d?"":"p-6 pt-0"}`,children:i})]}):null;const c=R.useRef(null),h=R.useRef(null),m=R.useRef(e);if(m.current=e,R.useEffect(()=>{if(!n)return;h.current=typeof document<"u"?document.activeElement:null;const y=setTimeout(()=>{const x=c.current;if(!x)return;const w=x.querySelector(c2);w?w.focus():x.focus()},0),k=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const w=c.current;if(!w)return;const S=Array.from(w.querySelectorAll(c2)).filter(A=>!A.hasAttribute("disabled")&&A.tabIndex!==-1);if(S.length===0){x.preventDefault(),w.focus();return}const C=S[0],T=S[S.length-1],N=document.activeElement;x.shiftKey?(N===C||!w.contains(N))&&(x.preventDefault(),T.focus()):(N===T||!w.contains(N))&&(x.preventDefault(),C.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(y),document.removeEventListener("keydown",k);const x=h.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}h.current=null}},[n]),!n)return null;const f=_=>{_.target===_.currentTarget&&e()},b=o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:f,"data-testid":"modal-backdrop",children:o.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-label":r??"Dialog",tabIndex:-1,className:`bg-bg-elev border border-line rounded-lg shadow-xl w-full mx-4 outline-none flex flex-col break-words ${iB[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${d?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${d?"px-6 pt-6 pb-3":"mb-3"}`,children:r}):null,a?o.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:i}):i]})});return typeof document<"u"&&document.body?Iu.createPortal(b,document.body):b}class VN extends R.Component{constructor(){super(...arguments);qn(this,"state",{error:null});qn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(i){return{error:i}}componentDidCatch(i,r){console.error("[ErrorBoundary]",i,r)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):o.jsxs("div",{className:"p-6 text-xs",children:[o.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),o.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),o.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 rB({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(tf,{open:n,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[o.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:i}),o.jsx("button",{type:"button",onClick:e,"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:"✕"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o.jsx(VN,{children:r})})]})}function qN(n,e={}){switch(n){case"ready":return e.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 e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.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 d2=n=>Symbol.iterator in n,u2=n=>"entries"in n,h2=(n,e)=>{const i=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(i.size!==r.size)return!1;for(const[s,a]of i)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},sB=(n,e)=>{const i=n[Symbol.iterator](),r=e[Symbol.iterator]();let s=i.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=i.next(),a=r.next()}return!!s.done&&!!a.done};function oB(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null||Object.getPrototypeOf(n)!==Object.getPrototypeOf(e)?!1:d2(n)&&d2(e)?u2(n)&&u2(e)?h2(n,e):sB(n,e):h2({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function I1(n){const e=Rt.useRef(void 0);return i=>{const r=n(i);return oB(e.current,r)?e.current:e.current=r}}let p2=0;const aB=1e3;function lB(n){const e=performance.now();e-p2<aB||(p2=e,ht.debug("voice","mic.gate.click_rejected",{reason:n}))}function KN(){const n=kt(h=>h.isRecording),e=kt(h=>h.error),i=kt(h=>h.loadingProgress),r=kt(I1(Lb)),s=()=>{const h=kt.getState(),{canRecord:m,reason:f}=Lb(h);if(h.isRecording)return h.stopRecording();if(h.wizardArmed&&!h.wizardOpen){h.openWizard();return}if(f==="error"||f==="load-timeout"){h.resetAndRetryModel();return}if(!m)return lB(f);const b=vt.getState().activeTabId;b&&h.startRecording(b)},a=qN(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),d=r.reason==="unsupported",l=!r.canRecord,c=r.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":r.reason==="error"||r.reason==="load-timeout"?"text-red-400 cursor-pointer":r.reason==="permission-denied"?"text-amber-400 cursor-pointer":r.reason==="idle"?"text-fg-faint cursor-pointer":r.reason==="unsupported"?"text-fg-faint cursor-not-allowed":n?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:d,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${c}`,children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function cB(){const n=kt(i=>i.ttsEnabled),e=kt(i=>i.toggleTTS);return o.jsxs("button",{onClick:e,title:n?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${n?"text-accent":"text-fg-dim hover:text-fg"}`,children:[o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n?o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),o.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),o.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function dB(n){return/^monitor of /i.test(n.trim())}function f2(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function m2(n,e,i){if(n){const d=i.find(l=>l.deviceId===n);if(d)return d}if(!e)return null;const r=i.filter(d=>d.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=f2(e),a=i.filter(d=>d.label&&f2(d.label)===s);return a.length===1?a[0]:null}async function g2(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&dB(r.label))):[]}const v2=!1;function YN(){const n=kt(h=>h.isRecording);kt(h=>h.startRecording),kt(h=>h.stopRecording);const[e,i]=R.useState([]),[r,s]=R.useState(null),[a,d]=R.useState(null);R.useEffect(()=>{let h=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(h)return;const f=await g2(v2);if(h)return;i(f),d(m.selectedLabel);const b=m2(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(ht.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),ht.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ht.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{h=!0}},[]);const l=R.useCallback(async()=>{try{const h=await g2(v2);if(i(h),r&&!h.some(m=>m.deviceId===r)){const m=m2(null,a,h);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(h){ht.warn("voice","device-picker refresh failed",{error:h instanceof Error?h.message:String(h)})}},[r,a]);R.useEffect(()=>{const h=()=>{l()};return window.addEventListener("mic-device-change",h),()=>window.removeEventListener("mic-device-change",h)},[l]);const c=async h=>{var _;const m=h.target.value,f=m===""?null:m,b=f?((_=e.find(y=>y.deviceId===f))==null?void 0:_.label)??null:null;s(f),d(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),ht.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(y){ht.warn("voice","setDevicePref failed",{error:y instanceof Error?y.message:String(y)})}if(n)try{await kt.getState().restartWithDevice()}catch(y){ht.warn("voice","device-picker restart failed",{error:y instanceof Error?y.message:String(y)})}};return o.jsxs("select",{value:r??"",onChange:c,onFocus:()=>{l()},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:[o.jsx("option",{value:"",children:"Default"}),e.map(h=>o.jsx("option",{value:h.deviceId,children:h.label||`Mic ${h.deviceId.slice(0,6)}`},h.deviceId))]})}function uB(){const n=kt(_=>_.isRecording),e=kt(_=>_.levelMeterEnabled),[i,r]=R.useState(0),[s,a]=R.useState(0),d=R.useRef(0);d.current=s;const[l,c]=R.useState(0),[h,m]=R.useState(!1),f=R.useRef(null);if(R.useEffect(()=>{if(!n||!e){r(0),a(0);return}let _=0,y=!1,k=null,x=null;const w=()=>{if(y)return;const C=x??aT();if(!C){_=requestAnimationFrame(w);return}x!==C&&(x=C,k=new Uint8Array(new ArrayBuffer(C.fftSize)));const T=k;C.getByteTimeDomainData(T);let N=0;for(let O=0;O<T.length;O++){const H=T[O]-128;N+=H*H}const A=Math.sqrt(N/T.length)/128,P=A>0?20*Math.log10(A):-60,I=Math.max(0,Math.min(1,(P+60)/60));a(A),r(I),A>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),_=requestAnimationFrame(w)};_=requestAnimationFrame(w);const S=setInterval(()=>{y||c(Math.round(d.current*100))},250);return()=>{y=!0,cancelAnimationFrame(_),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!e)return null;const b=h?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return o.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${h?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${i*100}%`}})})}function XN(){const n=kt(h=>h.submitCountdownStartAt),e=kt(h=>h.submitDelayMs),[i,r]=R.useState(()=>performance.now());if(R.useEffect(()=>{if(n===null)return;let h;const m=()=>{r(performance.now()),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>cancelAnimationFrame(h)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),d=Math.max(0,Math.min(100,a/e*100)),l=a<500,c=kt.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:c,title:`Submitting in ${(a/1e3).toFixed(1)}s — click to cancel`,children:o.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:o.jsx("div",{className:`h-full transition-colors ${l?"bg-amber-400":"bg-accent"}`,style:{width:`${d}%`}})})})}function hB({open:n,onClose:e,variant:i="overlay"}){return o.jsx(rB,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(gB,{}),o.jsx(XN,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(KN,{}),o.jsx(YN,{}),o.jsx(cB,{})]}),o.jsx(pB,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(mB,{})]}),o.jsx(uB,{})]})})}function pB(){const n=kt(a=>a.isRecording),[e,i]=R.useState(null);if(R.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,d()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=fB(e.accelerator);return o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("span",{children:[r," "]}),o.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),o.jsx("span",{children:" to record"})]})}function fB(n){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return n.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function mB(){const[n,e]=R.useState(null);if(R.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>ht.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!n)return null;const i=async r=>{if(n.mode===r)return;const s={...n,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){ht.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return o.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:[o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="toggle",onChange:()=>i("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),o.jsx("span",{children:"Tap on/off"})]}),o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="hold",onChange:()=>i("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function gB(){const n=kt(a=>a.isRecording),e=kt(a=>a.lastTranscript),i=kt(a=>a.error),r=kt(a=>a.modelStatus),s=kt(a=>a.loadingProgress);return i?o.jsxs("div",{className:"text-[11px] text-red-400",title:i,children:["⚠ ",i]}):n?o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),o.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):r==="loading"?o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{children:"Loading speech model"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}let Gw=null;function vB(){return Gw||(Gw=rv(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(b1.config({monaco:n}),n))),Gw}function JN({value:n,onChange:e,path:i,readOnly:r}){const s=R.useRef(null),a=d=>{s.current=d};return o.jsx(y1,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:d=>e(d??""),onMount:a,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:r,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let x2=!1;async function xB(n){if(x2)return;const e=await vB(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!d.includes(l))throw new Error("untrusted origin");const c=await fetch(s.uri);c.ok&&(a=await c.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:i.filter(s=>s.schema),enableSchemaRequest:!0}),x2=!0}function M1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,d]=R.useState(""),[l,c]=R.useState(!0),h=[],m=n.kind==="object"&&Object.keys(n.children).length===0,b=((r==null?void 0:r.rootKeys())??[]).length>0;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.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:[o.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",o.jsx("span",{className:"text-fg-dim",children:br[e].label})]}),b&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:_=>c(_.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:_=>d(_.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"})]}),o.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:m&&!l?o.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):o.jsx(ZN,{node:n,path:h,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function ZN(n){return n.node.kind==="object"?o.jsx(bB,{...n,node:n.node}):n.node.kind==="array"?o.jsx(yB,{...n,node:n.node}):o.jsx(wB,{...n,node:n.node})}function b2(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Kp(n,e,i){return!!(!i.trim()||n.some(r=>b2(r,i))||e!=null&&e.description&&b2(e.description,i))}function bB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l,showGhosts:c,defaultOpen:h}){const[m,f]=R.useState(h??d<2),b=(l==null?void 0:l.at(e))??null,_=new Set(Object.keys(n.children)),y=c?(b==null?void 0:b.knownChildren)??[]:[],k=Array.from(new Set([..._,...y])).sort(),x=R.useMemo(()=>a.trim()?k.filter(S=>{const C=(l==null?void 0:l.at([...e,S]))??null;return Kp([...e,S],C,a)?!0:_.has(S)?QN(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&x.length===0&&!Kp(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(S=>w(S))});return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>f(!m),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:m?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" {",_.size,y.length>_.size?`/${new Set([..._,...y]).size}`:"","}"]}),(b==null?void 0:b.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:b.description,children:["— ",b.description]})]}),m&&x.map(S=>w(S))]});function w(S){if(_.has(S))return o.jsx(ZN,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:d+1,schema:l,showGhosts:c},S);const C=(l==null?void 0:l.at([...e,S]))??null;return C?o.jsx(_B,{path:[...e,S],label:S,info:C,targetScope:r,onSet:s,depth:d+1,filter:a},S):null}}function QN(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Kp(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(QN(n.children[a],[...e,a],i,r))return!0;return!1}function yB({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[d,l]=R.useState(!0),c=(a==null?void 0:a.at(e))??null;return Kp(e,c,r)?o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:s*14},onClick:()=>l(!d),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(Yg,{tone:"warn",children:"accumulated"}),(c==null?void 0:c.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:c.description,children:["— ",c.description]})]}),d&&n.items.map((h,m)=>o.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(s+1)*14},children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),o.jsxs("span",{className:"text-fg-faint",children:[m,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:Qb(h.value)}),o.jsx(r0,{scope:h.fromScope})]},m))]}):null}function wB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l}){const[c,h]=R.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Kp(e,m,a))return null;const f=n.winner!==r,b=n.shadowed.length>0;return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&h(!c),children:b?c?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:Qb(n.value)}),o.jsx(r0,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(Yg,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&SB(n.value,m.default)&&o.jsx(Yg,{tone:"dim",children:"= default"}),n.typeMismatch&&o.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(m==null?void 0:m.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:m.description,children:["— ",m.description]}),o.jsx("div",{className:"flex-1"}),(m==null?void 0:m.enum)&&o.jsx(eD,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,n.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${f?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:f?`copy into ${br[r].label} draft`:`already winning in ${br[r].label}`,children:"override"})]}),c&&n.shadowed.map((_,y)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:Qb(_.value)}),o.jsx(r0,{scope:_.scope,dim:!0})]},y))]})}function _B({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:d}){if(!Kp(n,i,d))return null;const l=i.default!==void 0?i.default:kB(i.type),c=Array.isArray(i.type)?i.type.join("|"):i.type??"?";return o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:a*14},children:[o.jsx("span",{className:"w-3 shrink-0"}),o.jsx("span",{className:"text-fg-dim",children:e}),o.jsx(Yg,{tone:"dim",children:c}),i.required&&o.jsx(Yg,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",Qb(i.default)]}),i.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:i.description,children:["— ",i.description]}),o.jsx("div",{className:"flex-1"}),i.enum&&o.jsx(eD,{values:i.enum}),o.jsx("button",{onClick:()=>s(n,l),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 ${br[r].label} draft`,children:"set"})]})}function SB(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function kB(n){switch(Array.isArray(n)?n[0]:n){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 Qb(n){if(typeof n=="string")return JSON.stringify(n);if(n===null)return"null";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>100?e.slice(0,100)+"…":e}return String(n)}function r0({scope:n,dim:e}){const i=n==="user"?"bg-bg-hi text-fg-dim border-line":n==="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 o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i} ${e?"opacity-60":""}`,children:br[n].label})}function Yg({children:n,tone:e="default"}){const i={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"}[e];return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i}`,children:n})}function eD({values:n}){const e=n.map(i=>String(i)).join(" | ");return o.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${e}`,children:["∈ ",e.length>30?e.slice(0,30)+"…":e]})}const CB=[{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"]}],EB={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function tD(n){return n.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((r,s)=>{const a=EB[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function nD(n){const e=new Set,i=[];for(const s of CB){const a=s.keys.filter(d=>n.has(d));a.forEach(d=>e.add(d)),a.length!==0&&i.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(n).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&i.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),i}function jB(n,e){return nD(n).map(i=>({id:i.id,title:i.title,advanced:i.advanced,total:i.keys.length,setCount:i.keys.filter(r=>e.has(r)).length}))}const TB={};function iD(n,e){if(e)return{text:e,authored:!1};const i=TB[n];return i?{text:i,authored:!0}:null}const NB={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"},DB=["user","project","local","default"],AB={user:"user",project:"project",local:"local",default:"default"};function $B({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=R.useState(""),[d,l]=R.useState(!1),[c,h]=R.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),_=new Set([...f,...b]),y=R.useMemo(()=>nD(_),[Array.from(_).sort().join(",")]),k=R.useMemo(()=>jB(_,new Set(f)),[Array.from(_).sort().join(","),f.join(",")]),[x,w]=R.useState(null),S=R.useRef(null),C=N=>{const A=y.find(P=>P.id===N);A!=null&&A.advanced&&!d&&l(!0),w(N)};R.useEffect(()=>{if(!x)return;w(null);const N=S.current,A=document.getElementById(`settings-group-${x}`);if(!N||!A)return;const P=A.getBoundingClientRect().top-N.getBoundingClientRect().top;N.scrollBy({top:P,behavior:"smooth"})},[x]);const T=R.useMemo(()=>y.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter(A=>{const P=(m==null?void 0:m.children[A])!==void 0;if(!c&&!P)return!1;if(!s.trim())return!0;const I=r.at([A]);return[A,tD(A),(I==null?void 0:I.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(N=>N.keys.length>0),[y,s,d,c,m,r]);return o.jsxs("div",{className:"h-full flex flex-col",children:[o.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:[o.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",o.jsx("span",{className:"text-fg-dim font-medium",children:br[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:N=>h(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:N=>l(N.target.checked),className:"accent-accent"}),"show advanced"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:s,onChange:N=>a(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),o.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[o.jsx(PB,{groups:k,onJump:C}),o.jsxs("div",{ref:S,className:"flex-1 overflow-auto py-3",children:[T.map(N=>o.jsx(RB,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map(A=>{const P=m==null?void 0:m.children[A],I=r.at([A]);return o.jsx(IB,{keyName:A,node:P,info:I,targetScope:e,onOverride:(O,H)=>i([A],O,H)},A)})},N.id)),T.length===0&&o.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',s,'"']})]})]})]})}function PB({groups:n,onJump:e}){return o.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:n.map(i=>o.jsxs("button",{onClick:()=>e(i.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${i.title}`,children:[o.jsx(sn,{name:NB[i.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:i.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[i.setCount,"/",i.total]})]},i.id))})}function RB({id:n,title:e,summary:i,advanced:r,children:s}){const[a,d]=R.useState(!0);return o.jsxs("section",{id:`settings-group-${n}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[o.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(!a),children:[o.jsx("span",{className:"text-fg-faint w-3",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h2",{className:"text-fg text-base font-semibold",children:e}),r&&o.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"})]}),o.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:i})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function IB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,d]=R.useState(!1),[l,c]=R.useState(!1),h=tD(n),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,_=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",y=i==null?void 0:i.default,k=b&&y!==void 0&&sD(b.value,y),x=UB({isSet:m,leafNode:b,defaultVal:y,isDefault:!!k,node:e}),w=MB(b,y),S=w.length>=2,C=!!b&&!k,T=iD(n,i==null?void 0:i.description);return o.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("button",{onClick:()=>d(!a),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:a?"collapse":"expand",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[o.jsx("h3",{className:"text-fg text-sm",children:h}),o.jsx(HB,{kind:x.kind,label:x.label}),S&&o.jsxs("button",{onClick:N=>{N.stopPropagation(),a||d(!0),c(A=>!A)},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 · ",w.map(N=>AB[N]).join(" · ")]}),C&&b&&o.jsx("button",{onClick:N=>{N.stopPropagation(),s(void 0,b.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 ${br[b.winner].label}`,children:"↺ reset"}),(i==null?void 0:i.deprecated)&&o.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"}),(i==null?void 0:i.required)&&!m&&o.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"})]}),T&&o.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${T.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:T.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:WB(T.text)}),a&&l&&b&&o.jsx(OB,{leaf:b,defaultVal:y,onReset:N=>s(void 0,N)}),a&&o.jsx(LB,{keyName:n,node:e,info:i,targetScope:r,onOverride:N=>s(N)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(GB,{node:e,info:i,onSet:N=>{s(N)},disabled:_&&m})})]})})}function MB(n,e){if(!n)return[];const i=new Set;i.add(n.winner);for(const r of n.shadowed)i.add(r.scope);return e!==void 0&&i.add("default"),DB.filter(r=>i.has(r))}function OB({leaf:n,defaultVal:e,onReset:i}){const r={};r[n.winner]={value:n.value,winner:!0};for(const s of n.shadowed)r[s.scope]={value:s.value,winner:!1};return o.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[o.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):"}),o.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(s=>{const a=r[s],d=a!==void 0;return o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:br[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:d?Fp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),d?o.jsx("button",{onClick:()=>i(s),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 ${br[s].label}`,children:"↺"}):o.jsx("span",{})]},s)}),o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:"Default"}),o.jsx("span",{className:"font-mono text-fg-dim truncate",children:e!==void 0?Fp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function LB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const d=(e==null?void 0:e.kind)==="leaf"?e:null,l=iD(n,i==null?void 0:i.description);return o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[l&&o.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${l.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:l.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:l.text}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(i==null?void 0:i.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(i.type)?i.type.join(" | "):i.type})]}),(i==null?void 0:i.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Fp(i.default)})]}),(i==null?void 0:i.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:i.enum.map(c=>String(c)).join(" | ")})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Current"}),o.jsxs("dd",{className:"font-mono",children:[o.jsx("span",{className:"text-fg-dim",children:Fp(d.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",br[d.winner].label]})]})]}),d&&d.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((c,h)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Fp(c.value)," —"," ",o.jsx("span",{className:"no-underline",children:br[c.scope].label})]},h))})]}),(e==null?void 0:e.kind)==="array"&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Accumulated"}),o.jsxs("dd",{className:"text-fg-dim",children:[e.items.length," items across all scopes"]})]})]}),o.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:o.jsx(zB,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function zB({node:n,info:e,onChange:i,targetScope:r}){const a=(n==null?void 0:n.kind)==="leaf"?n.value:e==null?void 0:e.default,d=rD(e==null?void 0:e.type);if(d==="boolean"){const l=a===!0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:c,label:h})=>o.jsx("button",{onClick:()=>i(c),className:`px-3 py-0.5 text-xs transition-colors ${l===c?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:h},h))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]})}return e!=null&&e.enum?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-fg-faint",children:"Choose:"}),e.enum.map(l=>{const c=sD(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${c?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(l)},String(l))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]}):d==="integer"||d==="number"?o.jsx(BB,{value:typeof a=="number"?a:void 0,integer:d==="integer",onCommit:i,target:br[r].label}):d==="string"?o.jsx(FB,{value:typeof a=="string"?a:"",onCommit:i,target:br[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function BB({value:n,integer:e,onCommit:i,target:r}){const[s,a]=R.useState(n!==void 0?String(n):""),d=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||i(l)};return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("input",{type:"number",value:s,onChange:l=>a(l.target.value),onBlur:d,onKeyDown:l=>{l.key==="Enter"&&l.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.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 → ",r]})]})}function FB({value:n,onCommit:e,target:i}){const[r,s]=R.useState(n);return o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[o.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),o.jsx("input",{type:"text",value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"&&e(r)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:()=>e(r),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 → ",i]})]})}function GB({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=rD(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const d=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!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 UB({isSet:n,leafNode:e,defaultVal:i,isDefault:r,node:s}){return n?(s==null?void 0:s.kind)==="array"?{kind:"accumulated",label:`${s.items.length} items`}:(s==null?void 0:s.kind)==="object"?{kind:"set",label:"configured"}:e?r?{kind:"default",label:`= default · ${br[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${br[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${Fp(i)}`}:{kind:"unset",label:"not configured"}}function HB({kind:n,label:e}){const i={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"}[n];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${i}`,children:e})}function rD(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function sD(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function WB(n){const e=n.trim().split(`
3079
+ (Give a different rewrite than the last one.)`,!1)},[y,i.instruction]),S=R.useCallback(C=>{const T=i.diff;if(!T)return{ok:!1,reason:"not-found"};const N=T4(C,T.before,T.after);return N.ok?(s.current+=1,r({type:"ACCEPT"})):Re.error(N.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),N},[i.diff]);return{state:i,select:h,cancel:m,listen:f,sendHeard:x,run:k,retry:w,accept:S}}const O4=[{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."}],QC=320,ig=8;function L4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function z4(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,ig),Math.max(ig,e-QC-ig)),r=Math.max(n.top-ig,ig);return{position:"fixed",left:i,top:r,width:QC,transform:"translateY(-100%)",zIndex:50}}function B4({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:d,onListen:l,onSendHeard:c,onCancel:h,onAccept:m,onReject:f,onRetry:b}){const[_,y]=R.useState(""),k=()=>{const x=_.trim();x&&(d(x),y(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:z4(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&o.jsxs("div",{className:"p-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{onClick:l,"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"}),O4.map(x=>o.jsx("button",{onClick:()=>a(x.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:x.label},x.label))]}),o.jsx("button",{onClick:h,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:_,onChange:x=>y(x.target.value),onKeyDown:x=>{x.key==="Enter"?k():x.key==="Escape"&&h()},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"})]}),n==="listening"&&o.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[o.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(L4,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:h,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[o.jsxs("p",{className:"italic text-fg mb-2",children:["«",r,"»"]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsxs("div",{className:"p-3 flex items-center justify-between",children:[o.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),o.jsx("button",{onClick:h,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&o.jsxs("div",{className:"p-3",children:[o.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function F4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function e2({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:d,onCancel:l,onAccept:c,onReject:h,onRetry:m}){return o.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[o.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),o.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:ov(I4)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&o.jsxs("div",{className:"text-fg-faint",children:[o.jsx("p",{children:"Select text in the doc…"}),o.jsxs("p",{className:"mt-2 text-[10px]",children:[r," edit",r===1?"":"s"," this session"]})]}),n==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(F4,{}),"Listening…"]}),s&&o.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),o.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{children:[o.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&i&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-3 space-y-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function t2(n){return n.split("/").filter(Boolean).pop()||n}function G4({path:n,onRenamed:e,onDeleted:i}){const[r,s]=R.useState(!1),[a,d]=R.useState(!1),[l,c]=R.useState(""),[h,m]=R.useState(!1),f=Pn(H=>H.buffers[n]),b=Pn(H=>H.openFile),_=Pn(H=>H.renameOpenFile),y=Pn(H=>H.closeFile),k=nc(),x=t2(n),w=()=>s(!1),S=()=>{c(x),d(!0),w()},C=async()=>{const H=l.trim();if(!H||H===x){d(!1);return}try{const B=await window.api.files.rename(n,H);if(B.ok){const Z=n.slice(0,n.lastIndexOf("/")),Q=B.newPath??`${Z}/${H}`;_(n,Q),e==null||e(n,Q),Re.info(`Renamed to ${H}`)}else Re.error(B.error??`Couldn't rename ${x}`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't rename ${x}`)}d(!1)},T=async()=>{w();try{const H=await window.api.files.duplicate(n);H.ok&&H.path?(b(H.path),Re.info(`Duplicated as ${t2(H.path)}`)):Re.error(H.error??`Couldn't duplicate ${x}`)}catch(H){Re.error(H instanceof Error?H.message:`Couldn't duplicate ${x}`)}},N=async()=>{try{const H=await window.api.files.delete(n);H.ok?(y(n),i==null||i(n),Re.info(`Deleted ${x}`)):Re.error(H.error??`Couldn't delete ${x}`)}catch(H){Re.error(H instanceof Error?H.message:`Couldn't delete ${x}`)}m(!1)},A=async()=>{w();const H=f??"";try{await navigator.clipboard.writeText(H),Re.info(`Copied ${H.length} chars`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't copy ${x}`)}},P=()=>{if(w(),!k){Re.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Re.info(`Added ${x} to Claude context`)},I=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(H=>{H.ok||Re.error(H.error??`Couldn't open ${x}`)}).catch(H=>Re.error(H instanceof Error?H.message:`Couldn't open ${x}`))},O=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(H=>{H.ok||Re.error(H.error??`Couldn't reveal ${x}`)}).catch(H=>Re.error(H instanceof Error?H.message:`Couldn't reveal ${x}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(H=>!H),className:`px-2 py-0.5 text-[10px] border border-line rounded ${r?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:w}),o.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:[o.jsx(Lw,{children:"Edit"}),o.jsx(du,{label:"Rename",onClick:S}),o.jsx(du,{label:"Duplicate",onClick:T}),o.jsx(du,{label:"Delete document",danger:!0,onClick:()=>{w(),m(!0)}}),o.jsx(n2,{}),o.jsx(Lw,{children:"Open"}),o.jsx(du,{label:"Open in default app",onClick:I}),o.jsx(du,{label:"Reveal in OS",onClick:O}),o.jsx(n2,{}),o.jsx(Lw,{children:"Export"}),o.jsx(du,{label:"Copy as Markdown",onClick:A}),o.jsx(du,{label:"Add to Claude context",onClick:P,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(U4,{value:l,onChange:c,onCancel:()=>d(!1),onConfirm:()=>void C()}),h&&o.jsx(H4,{name:x,onCancel:()=>m(!1),onConfirm:()=>void N()})]})}function Lw({children:n}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function du({label:n,onClick:e,danger:i,disabled:r,title:s}){return o.jsx("button",{onClick:e,disabled:r,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function n2(){return o.jsx("div",{className:"my-1 border-t border-line"})}function U4({value:n,onChange:e,onCancel:i,onConfirm:r}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:s=>{s.target===s.currentTarget&&i()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),o.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&i()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function H4({name:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function W4(){const[n,e]=R.useState(!1),i=Rp();return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>e(r=>!r),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>e(!1)}),o.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:[o.jsx(Ep,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>i.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),o.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:i.fontSize}),o.jsx("button",{onClick:()=>i.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(Ep,{label:"Word wrap",children:o.jsx(Ux,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(Ep,{label:"Minimap",children:o.jsx(Ux,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(Ep,{label:"Theme",children:o.jsx("button",{onClick:()=>i.setTheme(i.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:i.theme==="dark"?"Dark":"Paper"})}),o.jsx(Ep,{label:"Autosave",children:o.jsx(Ux,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(Ep,{label:"Wide measure",children:o.jsx(Ux,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function Ep({label:n,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Ux({on:n,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const V4=R.lazy(()=>rv(()=>import("./TiptapBody-CJDxVF7X.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Hx(n){return n.split("/").filter(Boolean).pop()||n}function Wx(n,e){if(!e.length)return n;const i=new Set(e),r={};for(const[s,a]of Object.entries(n))i.has(s)||(r[s]=a);return r}function Vx(n){return SN(n)||kN(n)}function Zb(){const n=uv(),e=Pn(Ze=>Ze.openFiles),i=Pn(Ze=>Ze.activeFilePath),r=Pn(Ze=>Ze.dirty),s=Pn(Ze=>Ze.viewMode),a=Pn(Ze=>Ze.buffers),d=Pn(Ze=>Ze.setActive),l=Pn(Ze=>Ze.closeFile),c=Pn(Ze=>Ze.closeOthers),h=Pn(Ze=>Ze.closeToTheRight),m=Pn(Ze=>Ze.closeAll),f=Pn(Ze=>Ze.loadBuffer),b=Pn(Ze=>Ze.setBuffer),_=Pn(Ze=>Ze.markSaved),y=Pn(Ze=>Ze.setViewMode),k=Rp(),[x,w]=R.useState({}),[S,C]=R.useState({}),[T,N]=R.useState(null),[A,P]=R.useState(null),[I,O]=R.useState(!1),[H,B]=R.useState(!1),[Z,Q]=R.useState(!0),W=R.useRef(null),Y=R.useRef(null),ee=R.useRef(void 0),re=R.useRef(null),se=R.useRef(null),F=M4(i??"",a[i??""]??""),te=R.useCallback(Ze=>{W.current=Ze},[]),q=R.useCallback(()=>W.current,[]);R.useEffect(()=>{const Ze=i;if(!Ze||Vx(Ze))return;if(Pn.getState().hasBuffer(Ze)){w(xt=>xt[Ze]==="ready"?xt:{...xt,[Ze]:"ready"});return}let Ct=!1;return w(xt=>({...xt,[Ze]:"loading"})),window.api.files.read(Ze).then(xt=>{Ct||(xt.binary?w(pn=>({...pn,[Ze]:{binary:!0,size:xt.size??0,mime:xt.mime??"application/octet-stream",reason:xt.error??"Binary file"}})):xt.ok?(f(Ze,xt.text),w(pn=>({...pn,[Ze]:"ready"}))):w(pn=>({...pn,[Ze]:{error:xt.error??"failed to read"}})))}),()=>{Ct=!0}},[i,f]),R.useEffect(()=>{P(null)},[i]);const le=R.useCallback(async(Ze,Ct=!1)=>{const xt=Pn.getState().buffers[Ze];if(xt==null)return;Ct&&O(!0);const pn=await window.api.files.write(Ze,xt);pn.ok?(_(Ze),C($n=>({...$n,[Ze]:($n[Ze]??0)+1})),Ct||Re.info(`Saved ${Hx(Ze)}`)):Re.error(pn.error??`Couldn't save ${Hx(Ze)}`),Ct&&O(!1)},[_]);R.useEffect(()=>{if(!k.autosave)return;const Ze=i;if(!(!Ze||Vx(Ze)||!r[Ze]))return window.clearTimeout(ee.current),ee.current=window.setTimeout(()=>{le(Ze,!0)},1200),()=>window.clearTimeout(ee.current)},[k.autosave,i,r,a,le]);const ae=R.useCallback(Ze=>{Ze.length&&(w(Ct=>Wx(Ct,Ze)),C(Ct=>Wx(Ct,Ze)))},[]),be=R.useCallback((Ze,Ct)=>{w(xt=>Ze in xt?{...Wx(xt,[Ze]),[Ct]:xt[Ze]}:xt),C(xt=>Ze in xt?{...Wx(xt,[Ze]),[Ct]:xt[Ze]}:xt)},[]),Ne=R.useCallback(Ze=>{r[Ze]?N({kind:"one",path:Ze}):(l(Ze),ae([Ze]))},[r,l,ae]),Se=R.useCallback(Ze=>{e.some(xt=>xt.path!==Ze&&r[xt.path])?N({kind:"others",path:Ze}):(c(Ze),ae(e.filter(xt=>xt.path!==Ze).map(xt=>xt.path)))},[e,r,c,ae]),ce=R.useCallback(Ze=>{const Ct=e.findIndex(pn=>pn.path===Ze);Ct!==-1&&e.slice(Ct+1).some(pn=>r[pn.path])?N({kind:"right",path:Ze}):(h(Ze),ae(Ct!==-1?e.slice(Ct+1).map(pn=>pn.path):[]))},[e,r,h,ae]);R.useEffect(()=>{const Ze=Ct=>{if(n.current)if((Ct.metaKey||Ct.ctrlKey)&&(Ct.key==="s"||Ct.key==="S")){const xt=Pn.getState().activeFilePath;xt&&!Vx(xt)&&(Ct.preventDefault(),le(xt))}else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="f"||Ct.key==="F"))Ct.preventDefault(),B(xt=>!xt);else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="w"||Ct.key==="W")){const xt=Pn.getState().activeFilePath;xt&&Pn.getState().openFiles.length>1&&(Ct.preventDefault(),Se(xt))}else Ct.key==="Escape"&&F.state.phase!=="idle"?F.cancel():Ct.key==="Escape"&&H&&B(!1)};return window.addEventListener("keydown",Ze),()=>window.removeEventListener("keydown",Ze)},[le,H,Se,F.state.phase,F.cancel]),R.useEffect(()=>{if(F.state.phase==="idle")return;const Ze=Ct=>{var pn,$n;const xt=Ct.target;(pn=se.current)!=null&&pn.contains(xt)||($n=re.current)!=null&&$n.contains(xt)||F.cancel()};return window.addEventListener("mousedown",Ze),()=>window.removeEventListener("mousedown",Ze)},[F.state.phase,F.cancel]),R.useEffect(()=>{F.cancel()},[i,F.cancel]);const J=R.useCallback(()=>{e.some(Ct=>r[Ct.path])?N({kind:"all",path:""}):(m(),w({}),C({}))},[e,r,m]),me=()=>{if(T){if(T.kind==="one")l(T.path),ae([T.path]);else if(T.kind==="others"){const Ze=e.filter(Ct=>Ct.path!==T.path).map(Ct=>Ct.path);c(T.path),ae(Ze)}else if(T.kind==="right"){const Ze=e.findIndex(xt=>xt.path===T.path),Ct=Ze!==-1?e.slice(Ze+1).map(xt=>xt.path):[];h(T.path),ae(Ct)}else m(),w({}),C({});N(null)}};if(e.length===0)return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no file open"}),o.jsxs("div",{children:["open the ",o.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const ge=i,Fe=ge?Hx(ge):"",Je=ge?x[ge]:void 0,dt=ge?jN(ge):!1,zt=ge?F5(ge):!1,pt=ge&&dt?s[ge]??G5(ge):"edit",it=!!ge&&!Vx(ge)&&Je==="ready",ot=it,Dt=zt?["edit","wysiwyg","preview","split"]:dt?["edit","preview"]:[],on=ge&&o.jsx(X5,{path:ge,name:Fe,value:a[ge]??"",onChange:Ze=>b(ge,Ze),onSave:()=>void le(ge),onReady:te,onCursor:P}),gn=I?"Saving…":ge&&r[ge]?k.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!H&&o.jsx(V5,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:d,onCloseFile:Ne,onCloseOthers:Se,onCloseToTheRight:ce,onCloseAll:J}),ge&&!H&&o.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[o.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Fe}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:ge}),it&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",gn]}),Ol(ge)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:()=>Q(Ze=>!Ze),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Z?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ol(ge)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Ze=>o.jsx("button",{onClick:()=>y(ge,Ze),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${pt===Ze?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ze},Ze))}),o.jsx("div",{className:"flex-1"}),o.jsx(G4,{path:ge,onRenamed:be,onDeleted:Ze=>ae([Ze])}),it&&o.jsx(W4,{}),o.jsx("button",{onClick:()=>B(!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"})]}),H&&o.jsx("button",{onClick:()=>B(!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"}),o.jsx("div",{className:"flex-1 min-h-0",children:ge?SN(ge)?o.jsx(b4,{path:ge,name:Fe}):kN(ge)?o.jsx(y4,{path:ge}):Je&&typeof Je=="object"&&"binary"in Je?o.jsx(j4,{path:ge,name:Fe,size:Je.size,mime:Je.mime,reason:Je.reason}):Je&&typeof Je=="object"&&"error"in Je?o.jsx("div",{className:"p-6 text-xs text-red-400",children:Je.error}):Je!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):pt==="wysiwyg"&&Ol(ge)?o.jsx(R.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(V4,{value:a[ge]??"",onChange:Ze=>b(ge,Ze)},ge)}):pt==="split"&&Ol(ge)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(XC,{text:a[ge]??"",scrollRef:Y}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(YC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:on})]}),o.jsx("div",{ref:re,className:"flex-1 min-w-0",children:o.jsx(t0,{ref:Y,text:a[ge]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!H&&k.assistantRail&&o.jsx(e2,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ze=F.accept(a[ge]??"");Ze.ok&&b(ge,Ze.next)},onReject:F.cancel,onRetry:F.retry})]}):pt==="preview"&&Ol(ge)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(XC,{text:a[ge]??"",scrollRef:Y}),o.jsx("div",{ref:re,className:"flex-1 min-w-0",children:o.jsx(t0,{ref:Y,text:a[ge]??"",wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!H&&k.assistantRail&&o.jsx(e2,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ze=F.accept(a[ge]??"");Ze.ok&&b(ge,Ze.next)},onReject:F.cancel,onRetry:F.retry})]}):pt==="preview"&&_N(ge)?o.jsx(v4,{path:ge,dirty:!!r[ge],reloadToken:S[ge]??0}):pt==="preview"&&CN(ge)?o.jsx(_4,{path:ge,text:a[ge]??""}):pt==="preview"&&EN(ge)?o.jsx(C4,{path:ge,text:a[ge]??""}):Ol(ge)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(YC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:on})]}):on:null}),ot&&o.jsx(g4,{text:a[ge]??"",cursor:A,language:no(ge)||void 0}),ge&&Ol(ge)&&(pt==="preview"||pt==="split")&&F.state.phase!=="idle"&&F.state.selection&&o.jsx("div",{ref:se,children:o.jsx(B4,{phase:F.state.phase,rect:F.state.selection.rect,diff:F.state.diff,transcript:F.state.transcript,modelStatus:F.state.modelStatus,onQuickAction:F.run,onRunCustom:F.run,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onReject:F.cancel,onRetry:F.retry,onAccept:()=>{const Ze=F.accept(a[ge]??"");Ze.ok&&b(ge,Ze.next)}})}),T&&o.jsx(q4,{message:T.kind==="one"?`Discard unsaved changes to ${Hx(T.path)}?`:T.kind==="others"?"Discard unsaved changes in the other open files?":T.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:me})]})}function q4({message:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const i2={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"},K4={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 zw(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function Y4({open:n,onClose:e,variant:i="overlay"}){const r=vt(N=>N.tabs.find(A=>A.id===N.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,d]=R.useState(null),[l,c]=R.useState(!1),[h,m]=R.useState(null),f=R.useRef(null),b=R.useCallback(async N=>{c(!0),m(null);try{const A=await window.api.repo.analyze(N);A.ok?d(A):(m(A.error||"Analysis failed"),d(null))}catch(A){m(A instanceof Error?A.message:String(A)),d(null)}finally{c(!1)}},[]);R.useEffect(()=>{if(n){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[n,s,b]),R.useEffect(()=>{var A;if(!n)return;const N=P=>{P.key==="Escape"&&(P.stopPropagation(),e())};return window.addEventListener("keydown",N),(A=f.current)==null||A.focus(),()=>window.removeEventListener("keydown",N)},[n,e]);const _=R.useCallback(()=>{s&&b(s)},[s,b]),y=R.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([A,P])=>[A,P.files,P.lines]).sort((A,P)=>P[1]-A[1]).slice(0,12):[],[a]),k=R.useMemo(()=>y.length===0?1:y[0][1],[y]),x=R.useMemo(()=>{if(!a)return[];const N=a.topDirectories;if(N.length===0)return[];const A=N.map(I=>Math.sqrt(Math.max(1,I.fileCount))),P=A.reduce((I,O)=>I+O,0)||1;return N.map((I,O)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:A[O]/P*100}))},[a]);if(!n)return null;const w=N=>{N.target===N.currentTarget&&e()},S=s?s.split("/").filter(Boolean).pop()||s:"no folder",C=i==="page",T=o.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:w,"data-testid":"repoviz-backdrop",children:o.jsxs("div",{ref:f,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:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[o.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),o.jsxs("div",{className:"text-xs text-fg-dim truncate",title:s??"",children:[S,(a==null?void 0:a.gitStatus.branch)&&o.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",a.gitStatus.branch,")"]}),(a==null?void 0:a.truncated)&&o.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[a&&a.gitStatus.uncommitted>0&&o.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${a.gitStatus.uncommitted} uncommitted files`,children:[a.gitStatus.uncommitted," uncommitted"]}),o.jsxs("button",{type:"button",onClick:_,disabled:l||!s,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:[l?"…":"↻"," Refresh"]}),o.jsx("button",{type:"button",onClick:e,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:l&&!a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[o.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),o.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),o.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):h?o.jsxs("div",{className:"py-16 text-center",children:[o.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),o.jsx("div",{className:"text-sm text-red-400",children:h})]}):a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[o.jsx(Bw,{label:"Files",value:zw(a.totalFiles)}),o.jsx(Bw,{label:"Lines of code",value:zw(a.totalLines)}),o.jsx(Bw,{label:"Uncommitted",value:String(a.gitStatus.uncommitted),tone:a.gitStatus.uncommitted>0?"warn":"neutral"})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),y.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:y.map(([N,A,P])=>{const I=i2[N]??i2.other,O=K4[N]??N,H=A/k*100;return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-24 text-fg-dim truncate",title:O,children:O}),o.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:o.jsx("div",{className:"h-full rounded",style:{width:`${H}%`,backgroundColor:I}})}),o.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[A," files"]}),o.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[zw(P)," L"]})]},N)})})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),x.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):o.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:x.map(N=>o.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(N.basis,6)}%`,flexGrow:N.basis>15?1:0},title:`${N.path} — ${N.fileCount} files, ${N.totalLines.toLocaleString()} lines`,children:[o.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:N.path}),o.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[N.fileCount," files"]})]},N.path))})]}),o.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",a.durationMs,"ms",a.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):o.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?Iu.createPortal(T,document.body):T}function Bw({label:n,value:e,tone:i="neutral"}){const r=i==="warn"?"text-amber-400":"text-fg";return o.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[o.jsx("div",{className:`text-xl font-medium ${r}`,children:e}),o.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:n})]})}const r2=n=>/[/\\\-_.\s]/.test(n),s2=n=>n>="A"&&n<="Z";function X4(n,e,i){if(!n)return{match:!0,score:0,matched:[]};const r=n.toLowerCase(),s=e.toLowerCase(),a=(i||e).toLowerCase(),d=e.split("/").pop()||e,l=d.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:d.length},(w,S)=>S)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:n.length},(w,S)=>S)};let c=0;for(const w of a.split("/")){if(w===r)return{match:!0,score:800,matched:[]};w.startsWith(r)&&(c=Math.max(c,700))}const h=l.indexOf(r);if(h!==-1)return{match:!0,score:h===0||r2(l[h-1])||s2(d[h])?650:600,matched:Array.from({length:n.length},(S,C)=>h+C)};if(a.includes(r))return{match:!0,score:Math.max(500,c),matched:[]};let m=0,f=0,b=0,_=-1,y=0;const k=[];for(let w=0;w<s.length&&m<r.length;w++)s[w]===r[m]&&(k.push(w),f+=10,_===w-1?(b++,f+=b*8):b=0,(w===0||r2(s[w-1])||s2(e[w]))&&(y++,f+=15,w===0&&(f+=10)),_=w,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,y>=r.length*.5&&(f+=30),k.length>1){const w=k[k.length-1]-k[0];w>r.length*3&&(f-=Math.min(50,(w-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:k}}function Fw(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function o2(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const a2="session-manager.quickopen.recent",J4=8;function Z4({open:n,onClose:e,variant:i="overlay"}){const r=vt(O=>O.tabs.find(H=>H.id===O.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState([]),[h,m]=R.useState(!1),[f,b]=R.useState(0),[_,y]=R.useState([]),k=R.useRef(null),x=R.useRef(null);R.useEffect(()=>{if(n)try{const O=localStorage.getItem(a2);O&&y(JSON.parse(O))}catch{}},[n]),R.useEffect(()=>{if(!n){d(""),b(0);return}const O=setTimeout(()=>{var H;return(H=k.current)==null?void 0:H.focus()},0);return()=>clearTimeout(O)},[n]),R.useEffect(()=>{if(!n||!s)return;let O=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(H=>{if(!O){if(!H.ok){Re.error(`File search failed: ${H.error??"unknown error"}`),c([]);return}c(H.files)}}).catch(H=>{const B=H instanceof Error?H.message:String(H);ht.error("quick-open","search.files threw",{error:B},{cwd:s,tabId:r==null?void 0:r.id}),Re.error(`File search failed: ${B}`),c([])}).finally(()=>{O||m(!1)}),()=>{O=!0}},[n,s]);const w=R.useMemo(()=>{if(!a.trim())return[...l].sort((Z,Q)=>Z.name.localeCompare(Q.name)).slice(0,100).map(Z=>({file:Z,score:0,matched:[]}));const O=a.trim(),H=[];for(const B of l){const Z=X4(O,B.name,B.path);Z.match&&H.push({file:B,score:Z.score,matched:Z.matched})}return H.sort((B,Z)=>Z.score-B.score),H.slice(0,100)},[l,a]),S=R.useMemo(()=>a.trim()?[]:_.map(O=>l.find(H=>H.path===O)||null).filter(O=>O!==null).slice(0,5),[_,l,a]);R.useEffect(()=>{const O=S.length+w.length;f>=O&&b(Math.max(0,O-1))},[S.length,w.length,f]),R.useEffect(()=>{if(!x.current)return;const O=x.current.querySelector(`[data-row="${f}"]`);O&&O.scrollIntoView({block:"nearest"})},[f]);const C=R.useCallback(O=>{try{const Q=[O,..._.filter(W=>W!==O)].slice(0,J4);y(Q),localStorage.setItem(a2,JSON.stringify(Q))}catch{}const H=r==null?void 0:r.id;if(!H){Re.error("No active tab to receive file path");return}const Z=(s?Fw(O,s):O)||O;try{window.api.pty.write({tabId:H,data:Z})}catch(Q){const W=Q instanceof Error?Q.message:String(Q);ht.error("quick-open","pty.write failed",{error:W},{cwd:s,tabId:H}),Re.error(`Failed to write to terminal: ${W}`);return}e()},[r==null?void 0:r.id,s,_,e]),T=R.useCallback(O=>{const H=S.length+w.length;if(O.key==="Escape"){O.preventDefault(),e();return}if(O.key==="ArrowDown"){if(O.preventDefault(),H===0)return;b(B=>Math.min(H-1,B+1));return}if(O.key==="ArrowUp"){if(O.preventDefault(),H===0)return;b(B=>Math.max(0,B-1));return}if(O.key==="Enter"){if(O.preventDefault(),f<S.length){const Q=S[f];Q&&C(Q.path);return}const B=f-S.length,Z=w[B];Z&&C(Z.file.path)}},[f,w,S,C,e]);if(!n)return null;const N=(O,H)=>{if(H.length===0)return O;const B=new Set(H);return O.split("").map((Z,Q)=>o.jsx("span",{className:B.has(Q)?"text-accent font-semibold":"",children:Z},Q))};let A=-1;const P=i==="page",I=o.jsx("div",{className:P?"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:P?void 0:O=>{O.target===O.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:P?void 0:"dialog","aria-modal":P?void 0:"true","aria-label":"Quick Open",className:P?"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:T,children:[o.jsx("div",{className:"border-b border-line p-2",children:o.jsx("input",{ref:k,type:"text",value:a,onChange:O=>{d(O.target.value),b(0)},placeholder:s?"Search files in this project…":"No active tab — open a terminal first",disabled:!s,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"})}),o.jsx("div",{ref:x,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:h?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):s?S.length===0&&w.length===0?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:a?"No files match.":"No files found in this project."}):o.jsxs(o.Fragment,{children:[S.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),S.map(O=>{A++;const H=A,B=H===f;return o.jsxs("button",{"data-row":H,role:"option","aria-selected":B,onClick:()=>C(O.path),onMouseEnter:()=>b(H),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${B?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:O.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Fw(o2(O.path),s)})]},`r:${O.path}`)})]}),w.length>0&&o.jsxs("div",{children:[S.length>0&&o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),w.map(({file:O,matched:H})=>{A++;const B=A,Z=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":Z,onClick:()=>C(O.path),onMouseEnter:()=>b(B),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Z?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:N(O.name,H)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Fw(o2(O.path),s)})]},O.path)})]})]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[w.length+S.length," ",w.length+S.length===1?"file":"files"]})]})]})});return!P&&typeof document<"u"&&document.body?Iu.createPortal(I,document.body):I}function l2(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function Q4(n,e,i){if(!e)return n;const r=i?n:n.toLowerCase(),s=i?e:e.toLowerCase(),a=r.indexOf(s);return a<0?n:o.jsxs(o.Fragment,{children:[n.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:n.slice(a,a+e.length)}),n.slice(a+e.length)]})}function eB({open:n,onClose:e,variant:i="overlay"}){const r=vt(Q=>Q.tabs.find(W=>W.id===Q.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState(!1),[h,m]=R.useState([]),[f,b]=R.useState(!1),[_,y]=R.useState(null),[k,x]=R.useState(0),[w,S]=R.useState(null),C=R.useRef(null),T=R.useRef(null),N=R.useRef(0);R.useEffect(()=>{if(!n){d(""),m([]),y(null),x(0);return}const Q=setTimeout(()=>{var W;return(W=C.current)==null?void 0:W.focus()},0);return()=>clearTimeout(Q)},[n]),R.useEffect(()=>{if(!n||!s)return;const Q=a.trim();if(!Q){m([]),y(null),b(!1);return}const W=++N.current;b(!0);const Y=setTimeout(()=>{window.api.search.text(s,Q,{caseSensitive:l,limit:500}).then(ee=>{W===N.current&&(ee.ok?(m(ee.matches),y(null)):(y(ee.error??"unknown error"),m([])),S(ee.usedRipgrep))}).catch(ee=>{if(W!==N.current)return;const re=ee instanceof Error?ee.message:String(ee);ht.error("global-search","search.text threw",{error:re},{cwd:s,tabId:r==null?void 0:r.id}),y(re),m([])}).finally(()=>{W===N.current&&b(!1)})},250);return()=>clearTimeout(Y)},[n,s,a,l]);const A=R.useMemo(()=>{const Q=new Map;for(const Y of h){const ee=Q.get(Y.path);ee?ee.push(Y):Q.set(Y.path,[Y])}const W=[];for(const[Y,ee]of Q)W.push({path:Y,matches:ee});return W.sort((Y,ee)=>ee.matches.length-Y.matches.length||Y.path.localeCompare(ee.path)),W},[h]),P=R.useMemo(()=>h,[h]);R.useEffect(()=>{k>=P.length&&x(Math.max(0,P.length-1))},[P.length,k]),R.useEffect(()=>{if(!T.current)return;const Q=T.current.querySelector(`[data-match="${k}"]`);Q&&Q.scrollIntoView({block:"nearest"})},[k]);const I=R.useCallback(Q=>{const W=r==null?void 0:r.id;if(!W){Re.error("No active tab to receive path");return}const ee=`${(s?l2(Q.path,s):Q.path)||Q.path}:${Q.line}`;try{window.api.pty.write({tabId:W,data:ee})}catch(re){const se=re instanceof Error?re.message:String(re);ht.error("global-search","pty.write failed",{error:se},{cwd:s,tabId:W}),Re.error(`Failed to write to terminal: ${se}`);return}e()},[r==null?void 0:r.id,s,e]),O=R.useCallback(Q=>{if(Q.key==="Escape"){Q.preventDefault(),e();return}if(Q.key==="ArrowDown"){if(Q.preventDefault(),P.length===0)return;x(W=>Math.min(P.length-1,W+1));return}if(Q.key==="ArrowUp"){if(Q.preventDefault(),P.length===0)return;x(W=>Math.max(0,W-1));return}if(Q.key==="Enter"){Q.preventDefault();const W=P[k];W&&I(W)}},[P,k,I,e]);if(!n)return null;const H=i==="page";let B=-1;const Z=o.jsx("div",{className:H?"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:H?void 0:Q=>{Q.target===Q.currentTarget&&e()},"data-testid":"global-search-backdrop",children:o.jsxs("div",{role:H?void 0:"dialog","aria-modal":H?void 0:"true","aria-label":"Search in project",className:H?"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:O,children:[o.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[o.jsx("input",{ref:C,type:"text",value:a,onChange:Q=>{d(Q.target.value),x(0)},placeholder:s?"Search in this project…":"No active tab — open a terminal first",disabled:!s,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"}),o.jsx("button",{type:"button",onClick:()=>c(Q=>!Q),className:`px-2 py-1 text-xs rounded border ${l?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":l,children:"Aa"})]}),o.jsx("div",{ref:T,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:s?a.trim()?f?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):_?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:_}):P.length===0?o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(a),"."]}):o.jsx("div",{children:A.map(Q=>o.jsxs("div",{children:[o.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:[l2(Q.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",Q.matches.length,")"]})]}),Q.matches.map(W=>{B++;const Y=B,ee=Y===k;return o.jsxs("button",{"data-match":Y,role:"option","aria-selected":ee,onClick:()=>I(W),onMouseEnter:()=>x(Y),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ee?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:W.line}),o.jsx("span",{className:"truncate",children:Q4(W.text,a,l)})]},`${W.path}:${W.line}:${W.column}:${Y}`)})]},Q.path))}):o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",o.jsx("span",{className:"font-mono",children:s}),"."]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[P.length," ",P.length===1?"match":"matches",w===!1&&" · fs walk (rg missing)"]})]})]})});return!H&&typeof document<"u"&&document.body?Iu.createPortal(Z,document.body):Z}const tB=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function nB({open:n,onClose:e,variant:i="page",initialMode:r="files"}){const[s,a]=R.useState(r);return R.useEffect(()=>{a(r)},[r]),n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[o.jsx(Ao,{options:tB,active:s,onChange:a}),o.jsx("span",{className:"text-[11px] text-fg-faint",children:s==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),o.jsx("div",{className:"flex-1 min-h-0",children:s==="files"?o.jsx(Z4,{open:!0,onClose:e,variant:"page"}):o.jsx(eB,{open:!0,onClose:e,variant:"page"})})]}):null}const iB={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},c2='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function tf({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:d=!1,variant:l="overlay"}){if(l==="page")return n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[r&&o.jsx("h2",{className:`text-base font-medium text-fg ${d?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:r}),o.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${d?"":"p-6 pt-0"}`,children:i})]}):null;const c=R.useRef(null),h=R.useRef(null),m=R.useRef(e);if(m.current=e,R.useEffect(()=>{if(!n)return;h.current=typeof document<"u"?document.activeElement:null;const y=setTimeout(()=>{const x=c.current;if(!x)return;const w=x.querySelector(c2);w?w.focus():x.focus()},0),k=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const w=c.current;if(!w)return;const S=Array.from(w.querySelectorAll(c2)).filter(A=>!A.hasAttribute("disabled")&&A.tabIndex!==-1);if(S.length===0){x.preventDefault(),w.focus();return}const C=S[0],T=S[S.length-1],N=document.activeElement;x.shiftKey?(N===C||!w.contains(N))&&(x.preventDefault(),T.focus()):(N===T||!w.contains(N))&&(x.preventDefault(),C.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(y),document.removeEventListener("keydown",k);const x=h.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}h.current=null}},[n]),!n)return null;const f=_=>{_.target===_.currentTarget&&e()},b=o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:f,"data-testid":"modal-backdrop",children:o.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-label":r??"Dialog",tabIndex:-1,className:`bg-bg-elev border border-line rounded-lg shadow-xl w-full mx-4 outline-none flex flex-col break-words ${iB[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${d?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${d?"px-6 pt-6 pb-3":"mb-3"}`,children:r}):null,a?o.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:i}):i]})});return typeof document<"u"&&document.body?Iu.createPortal(b,document.body):b}class VN extends R.Component{constructor(){super(...arguments);qn(this,"state",{error:null});qn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(i){return{error:i}}componentDidCatch(i,r){console.error("[ErrorBoundary]",i,r)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):o.jsxs("div",{className:"p-6 text-xs",children:[o.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),o.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),o.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 rB({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(tf,{open:n,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[o.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:i}),o.jsx("button",{type:"button",onClick:e,"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:"✕"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o.jsx(VN,{children:r})})]})}function qN(n,e={}){switch(n){case"ready":return e.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 e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.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 d2=n=>Symbol.iterator in n,u2=n=>"entries"in n,h2=(n,e)=>{const i=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(i.size!==r.size)return!1;for(const[s,a]of i)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},sB=(n,e)=>{const i=n[Symbol.iterator](),r=e[Symbol.iterator]();let s=i.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=i.next(),a=r.next()}return!!s.done&&!!a.done};function oB(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null||Object.getPrototypeOf(n)!==Object.getPrototypeOf(e)?!1:d2(n)&&d2(e)?u2(n)&&u2(e)?h2(n,e):sB(n,e):h2({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function I1(n){const e=Rt.useRef(void 0);return i=>{const r=n(i);return oB(e.current,r)?e.current:e.current=r}}let p2=0;const aB=1e3;function lB(n){const e=performance.now();e-p2<aB||(p2=e,ht.debug("voice","mic.gate.click_rejected",{reason:n}))}function KN(){const n=kt(h=>h.isRecording),e=kt(h=>h.error),i=kt(h=>h.loadingProgress),r=kt(I1(Lb)),s=()=>{const h=kt.getState(),{canRecord:m,reason:f}=Lb(h);if(h.isRecording)return h.stopRecording();if(h.wizardArmed&&!h.wizardOpen){h.openWizard();return}if(f==="error"||f==="load-timeout"){h.resetAndRetryModel();return}if(!m)return lB(f);const b=vt.getState().activeTabId;b&&h.startRecording(b)},a=qN(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),d=r.reason==="unsupported",l=!r.canRecord,c=r.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":r.reason==="error"||r.reason==="load-timeout"?"text-red-400 cursor-pointer":r.reason==="permission-denied"?"text-amber-400 cursor-pointer":r.reason==="idle"?"text-fg-faint cursor-pointer":r.reason==="unsupported"?"text-fg-faint cursor-not-allowed":n?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:d,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${c}`,children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function cB(){const n=kt(i=>i.ttsEnabled),e=kt(i=>i.toggleTTS);return o.jsxs("button",{onClick:e,title:n?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${n?"text-accent":"text-fg-dim hover:text-fg"}`,children:[o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n?o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),o.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),o.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function dB(n){return/^monitor of /i.test(n.trim())}function f2(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function m2(n,e,i){if(n){const d=i.find(l=>l.deviceId===n);if(d)return d}if(!e)return null;const r=i.filter(d=>d.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=f2(e),a=i.filter(d=>d.label&&f2(d.label)===s);return a.length===1?a[0]:null}async function g2(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&dB(r.label))):[]}const v2=!1;function YN(){const n=kt(h=>h.isRecording);kt(h=>h.startRecording),kt(h=>h.stopRecording);const[e,i]=R.useState([]),[r,s]=R.useState(null),[a,d]=R.useState(null);R.useEffect(()=>{let h=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(h)return;const f=await g2(v2);if(h)return;i(f),d(m.selectedLabel);const b=m2(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(ht.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),ht.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ht.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{h=!0}},[]);const l=R.useCallback(async()=>{try{const h=await g2(v2);if(i(h),r&&!h.some(m=>m.deviceId===r)){const m=m2(null,a,h);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(h){ht.warn("voice","device-picker refresh failed",{error:h instanceof Error?h.message:String(h)})}},[r,a]);R.useEffect(()=>{const h=()=>{l()};return window.addEventListener("mic-device-change",h),()=>window.removeEventListener("mic-device-change",h)},[l]);const c=async h=>{var _;const m=h.target.value,f=m===""?null:m,b=f?((_=e.find(y=>y.deviceId===f))==null?void 0:_.label)??null:null;s(f),d(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),ht.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(y){ht.warn("voice","setDevicePref failed",{error:y instanceof Error?y.message:String(y)})}if(n)try{await kt.getState().restartWithDevice()}catch(y){ht.warn("voice","device-picker restart failed",{error:y instanceof Error?y.message:String(y)})}};return o.jsxs("select",{value:r??"",onChange:c,onFocus:()=>{l()},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:[o.jsx("option",{value:"",children:"Default"}),e.map(h=>o.jsx("option",{value:h.deviceId,children:h.label||`Mic ${h.deviceId.slice(0,6)}`},h.deviceId))]})}function uB(){const n=kt(_=>_.isRecording),e=kt(_=>_.levelMeterEnabled),[i,r]=R.useState(0),[s,a]=R.useState(0),d=R.useRef(0);d.current=s;const[l,c]=R.useState(0),[h,m]=R.useState(!1),f=R.useRef(null);if(R.useEffect(()=>{if(!n||!e){r(0),a(0);return}let _=0,y=!1,k=null,x=null;const w=()=>{if(y)return;const C=x??aT();if(!C){_=requestAnimationFrame(w);return}x!==C&&(x=C,k=new Uint8Array(new ArrayBuffer(C.fftSize)));const T=k;C.getByteTimeDomainData(T);let N=0;for(let O=0;O<T.length;O++){const H=T[O]-128;N+=H*H}const A=Math.sqrt(N/T.length)/128,P=A>0?20*Math.log10(A):-60,I=Math.max(0,Math.min(1,(P+60)/60));a(A),r(I),A>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),_=requestAnimationFrame(w)};_=requestAnimationFrame(w);const S=setInterval(()=>{y||c(Math.round(d.current*100))},250);return()=>{y=!0,cancelAnimationFrame(_),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!e)return null;const b=h?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return o.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${h?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${i*100}%`}})})}function XN(){const n=kt(h=>h.submitCountdownStartAt),e=kt(h=>h.submitDelayMs),[i,r]=R.useState(()=>performance.now());if(R.useEffect(()=>{if(n===null)return;let h;const m=()=>{r(performance.now()),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>cancelAnimationFrame(h)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),d=Math.max(0,Math.min(100,a/e*100)),l=a<500,c=kt.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:c,title:`Submitting in ${(a/1e3).toFixed(1)}s — click to cancel`,children:o.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:o.jsx("div",{className:`h-full transition-colors ${l?"bg-amber-400":"bg-accent"}`,style:{width:`${d}%`}})})})}function hB({open:n,onClose:e,variant:i="overlay"}){return o.jsx(rB,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(gB,{}),o.jsx(XN,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(KN,{}),o.jsx(YN,{}),o.jsx(cB,{})]}),o.jsx(pB,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(mB,{})]}),o.jsx(uB,{})]})})}function pB(){const n=kt(a=>a.isRecording),[e,i]=R.useState(null);if(R.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,d()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=fB(e.accelerator);return o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("span",{children:[r," "]}),o.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),o.jsx("span",{children:" to record"})]})}function fB(n){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return n.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function mB(){const[n,e]=R.useState(null);if(R.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>ht.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!n)return null;const i=async r=>{if(n.mode===r)return;const s={...n,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){ht.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return o.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:[o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="toggle",onChange:()=>i("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),o.jsx("span",{children:"Tap on/off"})]}),o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="hold",onChange:()=>i("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function gB(){const n=kt(a=>a.isRecording),e=kt(a=>a.lastTranscript),i=kt(a=>a.error),r=kt(a=>a.modelStatus),s=kt(a=>a.loadingProgress);return i?o.jsxs("div",{className:"text-[11px] text-red-400",title:i,children:["⚠ ",i]}):n?o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),o.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):r==="loading"?o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{children:"Loading speech model"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}let Gw=null;function vB(){return Gw||(Gw=rv(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(b1.config({monaco:n}),n))),Gw}function JN({value:n,onChange:e,path:i,readOnly:r}){const s=R.useRef(null),a=d=>{s.current=d};return o.jsx(y1,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:d=>e(d??""),onMount:a,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:r,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let x2=!1;async function xB(n){if(x2)return;const e=await vB(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!d.includes(l))throw new Error("untrusted origin");const c=await fetch(s.uri);c.ok&&(a=await c.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:i.filter(s=>s.schema),enableSchemaRequest:!0}),x2=!0}function M1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,d]=R.useState(""),[l,c]=R.useState(!0),h=[],m=n.kind==="object"&&Object.keys(n.children).length===0,b=((r==null?void 0:r.rootKeys())??[]).length>0;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.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:[o.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",o.jsx("span",{className:"text-fg-dim",children:br[e].label})]}),b&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:_=>c(_.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:_=>d(_.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"})]}),o.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:m&&!l?o.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):o.jsx(ZN,{node:n,path:h,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function ZN(n){return n.node.kind==="object"?o.jsx(bB,{...n,node:n.node}):n.node.kind==="array"?o.jsx(yB,{...n,node:n.node}):o.jsx(wB,{...n,node:n.node})}function b2(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Kp(n,e,i){return!!(!i.trim()||n.some(r=>b2(r,i))||e!=null&&e.description&&b2(e.description,i))}function bB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l,showGhosts:c,defaultOpen:h}){const[m,f]=R.useState(h??d<2),b=(l==null?void 0:l.at(e))??null,_=new Set(Object.keys(n.children)),y=c?(b==null?void 0:b.knownChildren)??[]:[],k=Array.from(new Set([..._,...y])).sort(),x=R.useMemo(()=>a.trim()?k.filter(S=>{const C=(l==null?void 0:l.at([...e,S]))??null;return Kp([...e,S],C,a)?!0:_.has(S)?QN(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&x.length===0&&!Kp(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(S=>w(S))});return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>f(!m),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:m?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" {",_.size,y.length>_.size?`/${new Set([..._,...y]).size}`:"","}"]}),(b==null?void 0:b.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:b.description,children:["— ",b.description]})]}),m&&x.map(S=>w(S))]});function w(S){if(_.has(S))return o.jsx(ZN,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:d+1,schema:l,showGhosts:c},S);const C=(l==null?void 0:l.at([...e,S]))??null;return C?o.jsx(_B,{path:[...e,S],label:S,info:C,targetScope:r,onSet:s,depth:d+1,filter:a},S):null}}function QN(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Kp(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(QN(n.children[a],[...e,a],i,r))return!0;return!1}function yB({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[d,l]=R.useState(!0),c=(a==null?void 0:a.at(e))??null;return Kp(e,c,r)?o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:s*14},onClick:()=>l(!d),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(Yg,{tone:"warn",children:"accumulated"}),(c==null?void 0:c.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:c.description,children:["— ",c.description]})]}),d&&n.items.map((h,m)=>o.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(s+1)*14},children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),o.jsxs("span",{className:"text-fg-faint",children:[m,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:Qb(h.value)}),o.jsx(r0,{scope:h.fromScope})]},m))]}):null}function wB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l}){const[c,h]=R.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Kp(e,m,a))return null;const f=n.winner!==r,b=n.shadowed.length>0;return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&h(!c),children:b?c?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:Qb(n.value)}),o.jsx(r0,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(Yg,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&SB(n.value,m.default)&&o.jsx(Yg,{tone:"dim",children:"= default"}),n.typeMismatch&&o.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(m==null?void 0:m.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:m.description,children:["— ",m.description]}),o.jsx("div",{className:"flex-1"}),(m==null?void 0:m.enum)&&o.jsx(eD,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,n.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${f?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:f?`copy into ${br[r].label} draft`:`already winning in ${br[r].label}`,children:"override"})]}),c&&n.shadowed.map((_,y)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:Qb(_.value)}),o.jsx(r0,{scope:_.scope,dim:!0})]},y))]})}function _B({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:d}){if(!Kp(n,i,d))return null;const l=i.default!==void 0?i.default:kB(i.type),c=Array.isArray(i.type)?i.type.join("|"):i.type??"?";return o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:a*14},children:[o.jsx("span",{className:"w-3 shrink-0"}),o.jsx("span",{className:"text-fg-dim",children:e}),o.jsx(Yg,{tone:"dim",children:c}),i.required&&o.jsx(Yg,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",Qb(i.default)]}),i.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:i.description,children:["— ",i.description]}),o.jsx("div",{className:"flex-1"}),i.enum&&o.jsx(eD,{values:i.enum}),o.jsx("button",{onClick:()=>s(n,l),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 ${br[r].label} draft`,children:"set"})]})}function SB(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function kB(n){switch(Array.isArray(n)?n[0]:n){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 Qb(n){if(typeof n=="string")return JSON.stringify(n);if(n===null)return"null";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>100?e.slice(0,100)+"…":e}return String(n)}function r0({scope:n,dim:e}){const i=n==="user"?"bg-bg-hi text-fg-dim border-line":n==="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 o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i} ${e?"opacity-60":""}`,children:br[n].label})}function Yg({children:n,tone:e="default"}){const i={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"}[e];return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i}`,children:n})}function eD({values:n}){const e=n.map(i=>String(i)).join(" | ");return o.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${e}`,children:["∈ ",e.length>30?e.slice(0,30)+"…":e]})}const CB=[{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"]}],EB={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function tD(n){return n.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((r,s)=>{const a=EB[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function nD(n){const e=new Set,i=[];for(const s of CB){const a=s.keys.filter(d=>n.has(d));a.forEach(d=>e.add(d)),a.length!==0&&i.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(n).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&i.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),i}function jB(n,e){return nD(n).map(i=>({id:i.id,title:i.title,advanced:i.advanced,total:i.keys.length,setCount:i.keys.filter(r=>e.has(r)).length}))}const TB={};function iD(n,e){if(e)return{text:e,authored:!1};const i=TB[n];return i?{text:i,authored:!0}:null}const NB={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"},DB=["user","project","local","default"],AB={user:"user",project:"project",local:"local",default:"default"};function $B({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=R.useState(""),[d,l]=R.useState(!1),[c,h]=R.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),_=new Set([...f,...b]),y=R.useMemo(()=>nD(_),[Array.from(_).sort().join(",")]),k=R.useMemo(()=>jB(_,new Set(f)),[Array.from(_).sort().join(","),f.join(",")]),[x,w]=R.useState(null),S=R.useRef(null),C=N=>{const A=y.find(P=>P.id===N);A!=null&&A.advanced&&!d&&l(!0),w(N)};R.useEffect(()=>{if(!x)return;w(null);const N=S.current,A=document.getElementById(`settings-group-${x}`);if(!N||!A)return;const P=A.getBoundingClientRect().top-N.getBoundingClientRect().top;N.scrollBy({top:P,behavior:"smooth"})},[x]);const T=R.useMemo(()=>y.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter(A=>{const P=(m==null?void 0:m.children[A])!==void 0;if(!c&&!P)return!1;if(!s.trim())return!0;const I=r.at([A]);return[A,tD(A),(I==null?void 0:I.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(N=>N.keys.length>0),[y,s,d,c,m,r]);return o.jsxs("div",{className:"h-full flex flex-col",children:[o.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:[o.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",o.jsx("span",{className:"text-fg-dim font-medium",children:br[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:N=>h(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:N=>l(N.target.checked),className:"accent-accent"}),"show advanced"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:s,onChange:N=>a(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),o.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[o.jsx(PB,{groups:k,onJump:C}),o.jsxs("div",{ref:S,className:"flex-1 overflow-auto py-3",children:[T.map(N=>o.jsx(RB,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map(A=>{const P=m==null?void 0:m.children[A],I=r.at([A]);return o.jsx(IB,{keyName:A,node:P,info:I,targetScope:e,onOverride:(O,H)=>i([A],O,H)},A)})},N.id)),T.length===0&&o.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',s,'"']})]})]})]})}function PB({groups:n,onJump:e}){return o.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:n.map(i=>o.jsxs("button",{onClick:()=>e(i.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${i.title}`,children:[o.jsx(sn,{name:NB[i.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:i.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[i.setCount,"/",i.total]})]},i.id))})}function RB({id:n,title:e,summary:i,advanced:r,children:s}){const[a,d]=R.useState(!0);return o.jsxs("section",{id:`settings-group-${n}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[o.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(!a),children:[o.jsx("span",{className:"text-fg-faint w-3",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h2",{className:"text-fg text-base font-semibold",children:e}),r&&o.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"})]}),o.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:i})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function IB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,d]=R.useState(!1),[l,c]=R.useState(!1),h=tD(n),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,_=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",y=i==null?void 0:i.default,k=b&&y!==void 0&&sD(b.value,y),x=UB({isSet:m,leafNode:b,defaultVal:y,isDefault:!!k,node:e}),w=MB(b,y),S=w.length>=2,C=!!b&&!k,T=iD(n,i==null?void 0:i.description);return o.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("button",{onClick:()=>d(!a),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:a?"collapse":"expand",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[o.jsx("h3",{className:"text-fg text-sm",children:h}),o.jsx(HB,{kind:x.kind,label:x.label}),S&&o.jsxs("button",{onClick:N=>{N.stopPropagation(),a||d(!0),c(A=>!A)},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 · ",w.map(N=>AB[N]).join(" · ")]}),C&&b&&o.jsx("button",{onClick:N=>{N.stopPropagation(),s(void 0,b.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 ${br[b.winner].label}`,children:"↺ reset"}),(i==null?void 0:i.deprecated)&&o.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"}),(i==null?void 0:i.required)&&!m&&o.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"})]}),T&&o.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${T.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:T.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:WB(T.text)}),a&&l&&b&&o.jsx(OB,{leaf:b,defaultVal:y,onReset:N=>s(void 0,N)}),a&&o.jsx(LB,{keyName:n,node:e,info:i,targetScope:r,onOverride:N=>s(N)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(GB,{node:e,info:i,onSet:N=>{s(N)},disabled:_&&m})})]})})}function MB(n,e){if(!n)return[];const i=new Set;i.add(n.winner);for(const r of n.shadowed)i.add(r.scope);return e!==void 0&&i.add("default"),DB.filter(r=>i.has(r))}function OB({leaf:n,defaultVal:e,onReset:i}){const r={};r[n.winner]={value:n.value,winner:!0};for(const s of n.shadowed)r[s.scope]={value:s.value,winner:!1};return o.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[o.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):"}),o.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(s=>{const a=r[s],d=a!==void 0;return o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:br[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:d?Fp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),d?o.jsx("button",{onClick:()=>i(s),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 ${br[s].label}`,children:"↺"}):o.jsx("span",{})]},s)}),o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:"Default"}),o.jsx("span",{className:"font-mono text-fg-dim truncate",children:e!==void 0?Fp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function LB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const d=(e==null?void 0:e.kind)==="leaf"?e:null,l=iD(n,i==null?void 0:i.description);return o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[l&&o.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${l.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:l.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:l.text}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(i==null?void 0:i.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(i.type)?i.type.join(" | "):i.type})]}),(i==null?void 0:i.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Fp(i.default)})]}),(i==null?void 0:i.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:i.enum.map(c=>String(c)).join(" | ")})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Current"}),o.jsxs("dd",{className:"font-mono",children:[o.jsx("span",{className:"text-fg-dim",children:Fp(d.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",br[d.winner].label]})]})]}),d&&d.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((c,h)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Fp(c.value)," —"," ",o.jsx("span",{className:"no-underline",children:br[c.scope].label})]},h))})]}),(e==null?void 0:e.kind)==="array"&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Accumulated"}),o.jsxs("dd",{className:"text-fg-dim",children:[e.items.length," items across all scopes"]})]})]}),o.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:o.jsx(zB,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function zB({node:n,info:e,onChange:i,targetScope:r}){const a=(n==null?void 0:n.kind)==="leaf"?n.value:e==null?void 0:e.default,d=rD(e==null?void 0:e.type);if(d==="boolean"){const l=a===!0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:c,label:h})=>o.jsx("button",{onClick:()=>i(c),className:`px-3 py-0.5 text-xs transition-colors ${l===c?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:h},h))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]})}return e!=null&&e.enum?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-fg-faint",children:"Choose:"}),e.enum.map(l=>{const c=sD(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${c?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(l)},String(l))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]}):d==="integer"||d==="number"?o.jsx(BB,{value:typeof a=="number"?a:void 0,integer:d==="integer",onCommit:i,target:br[r].label}):d==="string"?o.jsx(FB,{value:typeof a=="string"?a:"",onCommit:i,target:br[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function BB({value:n,integer:e,onCommit:i,target:r}){const[s,a]=R.useState(n!==void 0?String(n):""),d=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||i(l)};return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("input",{type:"number",value:s,onChange:l=>a(l.target.value),onBlur:d,onKeyDown:l=>{l.key==="Enter"&&l.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.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 → ",r]})]})}function FB({value:n,onCommit:e,target:i}){const[r,s]=R.useState(n);return o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[o.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),o.jsx("input",{type:"text",value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"&&e(r)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:()=>e(r),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 → ",i]})]})}function GB({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=rD(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const d=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!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 UB({isSet:n,leafNode:e,defaultVal:i,isDefault:r,node:s}){return n?(s==null?void 0:s.kind)==="array"?{kind:"accumulated",label:`${s.items.length} items`}:(s==null?void 0:s.kind)==="object"?{kind:"set",label:"configured"}:e?r?{kind:"default",label:`= default · ${br[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${br[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${Fp(i)}`}:{kind:"unset",label:"not configured"}}function HB({kind:n,label:e}){const i={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"}[n];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${i}`,children:e})}function rD(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function sD(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function WB(n){const e=n.trim().split(`
3080
3080
  `)[0],i=e.match(/^([^.!?]+[.!?])/);return i?i[1]:e.length>120?e.slice(0,120)+"…":e}function Fp(n){if(typeof n=="string")return n===""?'""':JSON.stringify(n);if(n===null)return"null";if(n===void 0)return"—";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>60?e.slice(0,60)+"…":e}return String(n)}function O1(n,e,i){const r=cn(c=>c.files),s=cn(c=>c.loadJson),a=cn(c=>c.watchFile),d=cn(c=>c.unwatchFile),l=R.useMemo(()=>{const c={};for(const h of n.scopes){const m=n.resolve(h,e??"",i);m&&(c[h]=m)}return c},[n,e,i]);return R.useEffect(()=>{const c=Object.values(l).filter(Boolean);return c.forEach(h=>{r[h]||s(h),a(h)}),()=>{c.forEach(h=>d(h))}},[JSON.stringify(l)]),l}const VB=[];function qx(n){return Array.isArray(n)?"array":n!==null&&typeof n=="object"?"object":"scalar"}function L1(n){const e=n.filter(i=>i.data!==void 0);return e.length===0?{kind:"object",children:{}}:oD(e,[])}function oD(n,e){const i=VB.includes(e.join(".")),r=n.every(m=>qx(m.data)==="object"),s=n.every(m=>qx(m.data)==="array");if(r){const m=new Set;for(const b of n)for(const _ of Object.keys(b.data))m.add(_);const f={};for(const b of m){const _=n.filter(y=>b in y.data).map(y=>({scope:y.scope,data:y.data[b]}));f[b]=oD(_,[...e,b])}return{kind:"object",children:f}}if(s&&!i){const m=[];for(const f of[...n].reverse())for(const b of f.data)m.push({value:b,fromScope:f.scope,index:m.length});return{kind:"array",items:m}}const a=[...n].reverse(),d=a[0],l=a.slice(1).map(m=>({scope:m.scope,value:m.data})),c=qx(d.data),h=l.some(m=>qx(m.value)!==c);return{kind:"leaf",value:d.data,winner:d.scope,shadowed:l,...h?{typeMismatch:!0}:{}}}function z1(n,e){if(e.length===0)return n;if(n.kind!=="object")return null;const[i,...r]=e,s=n.children[i];return s?z1(s,r):null}function My(n,e,i){if(e.length===0)return i;const[r,...s]=e,a=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};return a[r]=My(a[r],s,i),a}const qB=["user","project","local"];function B1(n,e){const i=[];for(const r of qB){const s=e[r];if(!s)continue;const a=n[s];if(!a||!a.exists)continue;const d=a.draftRaw??"";if(d.trim())try{i.push({scope:r,data:JSON.parse(d)})}catch{}}return i}const KB="http://json-schema.org/draft-07/schema#",YB="https://json.schemastore.org/claude-code-settings.json",XB={permissionRule:{type:"string",description:`Tool permission rule.
3081
3081
  See https://code.claude.com/docs/en/settings#permission-rule-syntax
3082
3082
  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"}}}}},JB="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",ZB=!0,QB=!0,e6="object",t6=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"]}]}}}`),n6="Claude Code Settings",i6={$schema:KB,$id:YB,$defs:XB,description:JB,allowTrailingCommas:ZB,additionalProperties:QB,type:e6,properties:t6,title:n6};function r6(n){const e=n??{},i={...e.$defs??{},...e.definitions??{}},r=_=>{if(!_)return{};if(!_.$ref)return d(_);const y=/^#\/(\$defs|definitions)\/(.+)$/.exec(_.$ref);if(!y)return d(_);const k=i[y[2]];return k?r({...k,...l(_)}):d(_)},s=new Set(["__proto__","constructor","prototype"]),a=_=>{if(!_)return{};const y={};for(const[k,x]of Object.entries(_))s.has(k)||(y[k]=x);return y},d=_=>{if(!_.allOf||_.allOf.length===0)return _;const y={..._};delete y.allOf;for(const k of _.allOf){const x=r(k);Object.assign(y,{properties:{...a(y.properties),...a(x.properties)},required:s6([...y.required??[],...x.required??[]])}),!y.description&&x.description&&(y.description=x.description),y.default===void 0&&x.default!==void 0&&(y.default=x.default),!y.type&&x.type&&(y.type=x.type)}return y},l=_=>{const{$ref:y,...k}=_;return k},c=(_,y)=>{let k=r(_);for(const x of y){if(!k)return null;if(/^\d+$/.test(x)){const C=Array.isArray(k.items)?k.items[Number(x)]:k.items;k=C?r(C):null;continue}const w=k.properties;if(w&&!s.has(x)&&x in w){k=r(w[x]);continue}const S=k.additionalProperties;if(S&&typeof S=="object"){k=r(S);continue}return null}return k},h=(_,y,k)=>{if(!_)return null;const x={};if(_.description&&(x.description=_.description),_.type&&(x.type=_.type),_.default!==void 0&&(x.default=_.default),_.enum&&(x.enum=_.enum),_.const!==void 0&&(x.const=_.const),_.deprecated&&(x.deprecated=!0),_.examples&&(x.examples=_.examples),_.properties&&(x.knownChildren=Object.keys(_.properties)),k&&(y!=null&&y.includes(k))&&(x.required=!0),_.items&&!Array.isArray(_.items)){const w=r(_.items),S=h(w,void 0,null);S&&(x.itemsInfo=S)}return(_.additionalProperties===!0||typeof _.additionalProperties=="object")&&(x.open=!0),x},m=_=>y=>{if(y.length===0)return h(r(_),void 0,null);const k=c(_,y.slice(0,-1));if(!k)return null;const x=y[y.length-1],w=c(k,[x]);return h(w,k.required,x)},f=_=>{const y=r(_);return Object.keys(y.properties??{})},b=_=>({at:m(_),rootKeys:()=>f(_),rootedAt:y=>{const k=c(_,y);return b(k??{})}});return b(e)}function s6(n){return Array.from(new Set(n))}let Uw=null;function ey(){return Uw||(Uw=r6(i6)),Uw}function o6(){const[n,e]=R.useState(null),[i,r]=R.useState(null),[s,a]=R.useState(null),[d,l]=R.useState(null),[c,h]=R.useState(!1),[m,f]=R.useState(null),[b,_]=R.useState(null);if(R.useEffect(()=>{let S=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([C,T,N])=>{S||(e(C),a(C),r(T),l(N))}).catch(C=>{console.warn("[telemetry] load failed:",C==null?void 0:C.message)}),()=>{S=!0}},[]),!s||!n)return o.jsx(It,{title:"loading…"});const y=JSON.stringify(s)!==JSON.stringify(n),k=(S,C)=>{f(null),a({...s,[S]:C})},x=async()=>{h(!0),f(null);try{const S=await window.api.otel.setConfig(s);!S.ok&&S.error&&f(S.error),e(S.config),a(S.config),r(S.status),_(Date.now())}catch(S){f(S instanceof Error?S.message:String(S))}finally{h(!1)}},w=()=>{f(null),a(n)};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[o.jsxs("header",{className:"space-y-1",children:[o.jsx("h2",{className:"text-fg text-base font-medium",children:"Telemetry — OpenTelemetry export"}),o.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&&o.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",o.jsx("span",{className:"font-mono",children:d})]})]}),o.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-fg",children:"Export transcripts to OTEL"}),o.jsx("div",{className:"text-fg-faint text-xs",children:"Toggle off to disable all span emission immediately."})]}),o.jsx(qg,{checked:s.enabled,onChange:S=>k("enabled",S),label:s.enabled?"on":"off"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"OTLP/HTTP traces endpoint"}),o.jsx("input",{type:"text",value:s.endpoint,onChange:S=>k("endpoint",S.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"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsxs("span",{className:"text-fg-dim text-xs",children:["Headers (newline-separated ",o.jsx("span",{className:"font-mono",children:"Key: Value"}),")"]}),o.jsx("textarea",{value:s.headers,onChange:S=>k("headers",S.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"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"Service name"}),o.jsx("input",{type:"text",value:s.serviceName,onChange:S=>k("serviceName",S.target.value),placeholder:"session-manager",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-fg",children:"Include content (PII)"}),o.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 ",o.jsx("span",{className:"font-mono",children:"OTEL_LOG_USER_PROMPTS"})," opt-in."]})]}),o.jsx(qg,{checked:s.includeContent,onChange:S=>k("includeContent",S),label:s.includeContent?"on":"off"})]})]}),i&&o.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1",children:[o.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),o.jsxs("div",{children:[o.jsx("span",{className:"text-fg-faint",children:"enabled:"})," ",o.jsx("span",{className:i.enabled?"text-accent":"text-fg-dim",children:String(i.enabled)})]}),i.error&&o.jsxs("div",{className:"text-red-400 break-words",children:[o.jsx("span",{className:"text-fg-faint",children:"error:"})," ",i.error]}),!i.error&&i.enabled&&o.jsx("div",{className:"text-fg-faint",children:"spans batched and exported in the background. Verify by enabling and pointing at a local Jaeger."})]}),o.jsxs("footer",{className:"flex items-center gap-3 pt-2 border-t border-line",children:[o.jsx("button",{onClick:x,disabled:!y||c,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:c?"saving…":"Save"}),o.jsx("button",{onClick:w,disabled:!y||c,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"}),m&&o.jsx("span",{className:"text-red-400 text-xs",children:m}),!m&&b&&!y&&o.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function a6(){const{model:n,setModel:e}=z$();return o.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[o.jsxs("header",{className:"space-y-1",children:[o.jsx("h2",{className:"text-fg text-base font-medium",children:"Session Manager preferences"}),o.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"Native app preferences, stored locally — not part of Claude Code's own settings."})]}),o.jsx("section",{className:"border border-line rounded p-3 space-y-3",children:o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"Default model for raw sessions"}),o.jsx("select",{value:n,onChange:i=>e(i.target.value),className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs",children:Lj.map(i=>o.jsx("option",{value:i,children:i.charAt(0).toUpperCase()+i.slice(1)},i))}),o.jsx("span",{className:"text-fg-faint text-[11px]",children:"Used when opening a raw interactive session without an explicit per-launch override."})]})})]})}function l6(){const n=Oi(),e=vt(O=>O.tabs),i=vt(O=>O.activeTabId),r=e.find(O=>O.id===i)??null,s=(r==null?void 0:r.cwd)??null,a=mn(O=>O.navFace),d=R.useRef(!1),l=R.useRef(a),[c,h]=R.useState(()=>a==="project"&&s?"project":"user"),[m,f]=R.useState("effective");R.useEffect(()=>{if(l.current!==a){if(l.current=a,d.current){d.current=!1;return}h(a==="project"&&s?"project":"user")}},[a,s]),R.useEffect(()=>{a==="project"&&(m==="telemetry"||m==="app")&&f("effective")},[a,m]);const b=O=>{d.current=!0,h(O)},_=O1(Du,n,s),y=_[c]??null,k=cn(O=>O.files),x=cn(O=>O.setDraft),w=cn(O=>O.saveJson),S=cn(O=>O.revert),[C,T]=R.useState(null),N=R.useMemo(()=>L1(B1(k,_)),[k,_]),A=(O,H,B)=>{var re;const Q=_[B??c];if(!Q)return;T(null);const W=((re=k[Q])==null?void 0:re.draftRaw)??"";let Y={};if(W.trim())try{Y=JSON.parse(W)}catch{Y={}}const ee=My(Y,O,H);x(Q,JSON.stringify(ee,null,2)+`