claude-code-session-manager 0.59.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-PUx4oZTh.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-BtVPGBaq.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
2
2
  var A$=Object.defineProperty;var $$=(n,e,i)=>e in n?A$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var Kn=(n,e,i)=>$$(n,typeof e!="symbol"?e+"":e,i);import{_ as pv}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 c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).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 Ry(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var gw={exports:{}},Wm={},vw={exports:{}},wn={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -53,7 +53,7 @@ ${s}`,d={...a,goalText:l},p={...e().sessions,[i]:d};n({sessions:p}),await uu(a.c
53
53
  `):a();case"queued_command":return Ln(c.prompt)??a();case"skill_listing":return Ln(c.content)??a();case"edited_text_file":return Ln(c.snippet)??a();default:return a()}}default:return a()}}function vP(n,e){var a;let i;try{i=JSON.parse(e)}catch{return null}const r=Lr((a=Lr(i))==null?void 0:a.attachment);if(!r)return null;const s=c=>Array.isArray(c)?c.filter(l=>typeof l=="string"):null;switch(n){case"deferred_tools_delta":return s(r.addedNames);case"agent_listing_delta":return s(r.addedTypes);case"command_permissions":return s(r.allowedTools);case"skill_listing":{const l=(Ln(r.content)??"").split(`
54
54
  `).map(d=>{var p,m;return(m=(p=/^-\s*([^:]+):/.exec(d))==null?void 0:p[1])==null?void 0:m.trim()}).filter(d=>!!d);return l.length?l:null}default:return null}}function xP(n){return n==="tool_use"||n==="todo_write"||n==="plan"||n==="agent_spawn"}function yp(n){return typeof n=="string"&&n.length>0?n:void 0}function Cx(n){return n===!0?!0:void 0}function bP(n){if(!n||typeof n!="object")return;const e=n,i={},r=(s,a)=>{a!==void 0&&(i[s]=a)};return r("attributionSkill",yp(e.attributionSkill)),r("attributionPlugin",yp(e.attributionPlugin)),r("attributionMcpServer",yp(e.attributionMcpServer)),r("attributionMcpTool",yp(e.attributionMcpTool)),r("effort",yp(e.effort)),r("gitBranch",yp(e.gitBranch)),r("isSidechain",Cx(e.isSidechain)),r("isMeta",Cx(e.isMeta)),r("isApiErrorMessage",Cx(e.isApiErrorMessage)),r("interruptedByShutdown",Cx(e.interruptedByShutdown)),Object.keys(i).length>0?i:void 0}const sd={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},rk=20;function Wb(n,e){const i=[...n,e];return i.length>rk?i.slice(i.length-rk):i}let sk=0;function Za(){return sk+=1,`t${Date.now().toString(36)}-${sk}`}const yP="Landed",ok=60;function wP(n){const e=n.trim();if(e.length<=ok)return e;const i=e.slice(0,ok),r=i.lastIndexOf(" ");return(r>0?i.slice(0,r):i).trim()}const mn=Ti((n,e)=>({chats:{},hydratedTabs:{},get:i=>e().chats[i]??sd,hydrate:async({tabId:i,cwd:r,sessionId:s})=>{var a,c,l;if(!e().hydratedTabs[i]&&(n({hydratedTabs:{...e().hydratedTabs,[i]:!0}}),!(typeof window>"u"||!((a=window.api)!=null&&a.exchanges))))try{const d=await window.api.exchanges.list({cwd:r,sessionId:s});if(!d.length)return;const p=[];for(const f of[...d].reverse()){const x=new Date(f.ts).getTime();p.push({id:Za(),role:"user",text:f.prompt,at:x}),p.push({id:Za(),role:"assistant",text:f.result,at:x})}const m=e().chats[i]??sd;n({chats:{...e().chats,[i]:{...m,turns:[...p,...m.turns],started:!0}}})}catch(d){const p=d instanceof Error?d.message:String(d);(l=(c=window.api)==null?void 0:c.logs)==null||l.write("chat","warn",`exchange hydration failed for tab ${i}: ${p}`)}},send:({tabId:i,sessionId:r,cwd:s,prompt:a,tag:c,chainRootId:l,external:d})=>{const p=a.trim();if(!p)return;if(Kl.getState().isAttached(i)){Me.error("Terminal mode is active for this Epic — switch back to Chat to send a message.");return}const m=e().chats[i]??sd;if(m.running){const f={id:crypto.randomUUID(),tabId:i,sessionId:r,cwd:s,text:p,status:"queued",createdAt:Date.now(),tag:c,chainRootId:l,external:d};n({chats:{...e().chats,[i]:{...m,queue:[...m.queue,f]}}});return}_P(i),eT({tabId:i,sessionId:r,cwd:s,text:p,tag:c,chainRootId:l})},resetThread:i=>{Kb.delete(i),n({chats:{...e().chats,[i]:{...sd}}})},pushNotice:(i,r)=>{Vb(i,"",r)},setPendingVoiceText:(i,r)=>{zr(i,s=>({...s,pendingVoiceText:r}))},clearPendingVoiceText:i=>{zr(i,r=>({...r,pendingVoiceText:void 0}))},dropTab:i=>{if(!(i in e().chats)&&!(i in e().hydratedTabs))return;Kb.delete(i);const r={...e().chats};delete r[i];const s={...e().hydratedTabs};delete s[i],n({chats:r,hydratedTabs:s})}}));function zr(n,e){const i=mn.getState().chats[n]??sd;mn.setState({chats:{...mn.getState().chats,[n]:e(i)}})}function yb(n,e,i={},r="done",s={}){zr(n,a=>{const c=a.activeTicket?Wb(a.ticketHistory??[],{...a.activeTicket,status:r,completedAt:Date.now(),...s}):a.ticketHistory??[],l=nT(n)&&(e.role==="assistant"||e.role==="user")?h1(a.turns,e.role,e.text):-1,d=l!==-1?a.turns.map((p,m)=>{var f;return m===l?{...p,outcome:e.outcome??p.outcome,toolUses:(f=p.toolUses)!=null&&f.length?p.toolUses:a.liveToolUses}:p}):[...a.turns,{...e,toolUses:a.liveToolUses}];return{...a,turns:d,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:c,...i}}),I_(n)}function _P(n){zr(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 eT(n){const{tabId:e,sessionId:i,cwd:r,text:s,promptId:a,tag:c,chainRootId:l}=n,d=mn.getState().chats[e]??sd,p={id:Za(),role:"user",text:s,at:Date.now()};M_(e,"user",s);const m=d.activeTicket??{id:a??crypto.randomUUID(),tabId:e,sessionId:i,cwd:r,text:s,status:"running",createdAt:Date.now(),startedAt:Date.now(),tag:c,chainRootId:l};mn.setState({chats:{...mn.getState().chats,[e]:{...d,turns:[...d.turns,p],running:!0,queuedPosition:0,stream:"",activeTicket:m}}}),Iy(r,i).catch(f=>{var y,w;const x=f instanceof Error?f.message:String(f);return(w=(y=window.api)==null?void 0:y.logs)==null||w.write("chat","warn",`transcript-exists check failed for tab ${e}: ${x}`),d.started}).then(f=>window.api.chat.run({tabId:e,sessionId:i,prompt:s,cwd:r,resume:f,promptId:a})).catch(f=>{const x=f instanceof Error?f.message:String(f);tT(e,i,x)})}function I_(n){const e=mn.getState().chats[n]??sd;if(e.queue.length===0)return;const[i,...r]=e.queue;if(zr(n,s=>({...s,queue:r,running:!0,queuedPosition:0,activeTicket:i})),i.external){Ex(n,i);return}if(Kt.getState().sessions[n]){Ex(n,i);return}if(iP(i.tag)){Ex(n,i);return}tP(i.text).then(s=>{if(s==="develop"){CP(n,i);return}Ex(n,i)})}function Ex(n,e){const i={...e,status:"running",startedAt:Date.now()};zr(n,r=>({...r,activeTicket:i})),eT({tabId:i.tabId,sessionId:i.sessionId,cwd:i.cwd,text:i.text,promptId:i.id,tag:i.tag,chainRootId:i.chainRootId})}function SP(n,e){var i,r,s,a,c;try{const l=(i=Kt.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}Kt.getState().appendPromptSessionEvent(n,{kind:"prd_created",causedByEventId:l.id,prdSlug:e})}catch(l){const d=l instanceof Error?l.message:String(l);(c=(a=window.api)==null?void 0:a.logs)==null||c.write("chat","warn",`appendPrdCreatedEvent failed for ${n}: ${d}`)}}const ak=2e3;function M_(n,e,i){var s,a,c,l;const r=Kt.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(d){const p=d instanceof Error?d.message:String(d);(l=(c=window.api)==null?void 0:c.logs)==null||l.write("chat","warn",`capturePromptSessionTurn failed for ${n}: ${p}`)}}function lk(n,e){var i,r,s;try{const a=(i=Kt.getState().events[n])==null?void 0:i.slice(-1)[0];if(!a)return;const c=e.length>ak?`${e.slice(0,ak)}…`:e;Kt.getState().appendPromptSessionEvent(n,{kind:"response",causedByEventId:a.id,text:c})}catch(a){const c=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}: ${c}`)}}async function kP(n,e){var r,s,a,c;const i=l=>{var d;return!!l&&((d=Kt.getState().sessions[l])==null?void 0:d.status)==="active"};if(e.chainRootId){const d=((mn.getState().chats[n]??sd).ticketHistory??[]).find(m=>m.id===e.chainRootId),p=(d==null?void 0:d.promptSessionId)??null;if(p){const m=Kt.getState().sessions[p];if(!m||m.status==="active")return p}}return i(n)||(await Kt.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)`):(c=(a=window.api)==null?void 0:a.logs)==null||c.write("chat","warn",`ticket ${e.id}: no resolvable PromptSession for tab ${n} — refusing dispatch (sessions must never mint an Epic)`),null)}function CP(n,e){const i=r=>{zr(n,s=>({...s,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:Wb(s.ticketHistory??[],{...e,status:"failed",completedAt:Date.now()})})),Vb(n,e.sessionId,r),Me.error(r),I_(n)};kP(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:wP(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,c=a.endsWith(".md")?a.slice(0,-3):a;SP(r,c);const l={...e,status:"dispatched-to-prd",completedAt:Date.now(),promptSessionId:r,...e.chainRootId?{}:{prdSlugs:[c]}};Vb(n,l.sessionId,`→ dispatched to PRD ${a} (ticket ${l.id})`),zr(n,d=>{let p=Wb(d.ticketHistory??[],l);if(e.chainRootId){const m=e.chainRootId;p=p.map(f=>f.id===m?{...f,prdSlugs:[...f.prdSlugs??[],c]}:f)}return{...d,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:p}}),I_(n)}).catch(s=>{const a=s instanceof Error?s.message:String(s);i(`→ PRD authoring failed for ticket ${e.id}: ${a}`)})})}function tT(n,e,i){zr(n,r=>r.activeTicket?{...r,activeTicket:null,ticketHistory:Wb(r.ticketHistory??[],{...r.activeTicket,status:"failed",completedAt:Date.now()})}:r),yb(n,{id:Za(),role:"error",text:i,at:Date.now()}),Me.error(i)}function Vb(n,e,i){zr(n,r=>({...r,turns:[...r.turns,{id:Za(),role:"notice",text:i,at:Date.now()}]}))}const EP=20,ck=1e3,od=new Map,qb=new Map,Kb=new Map;function h1(n,e,i){const r=i.trim(),s=Math.max(0,n.length-EP);for(let a=n.length-1;a>=s;a--)if(n[a].role===e&&n[a].text.trim()===r)return a;return-1}function dk(n){return n.length>ck?n.slice(n.length-ck):n}function nT(n){return od.has(n)}function uk(n,e){var p;if(e.ref){const m=Kb.get(n)??{seen:new Set,lastOffset:-1,lineIndex:-1};e.ref.byteOffset===m.lastOffset?m.lineIndex+=1:(m.lastOffset=e.ref.byteOffset,m.lineIndex=0),Kb.set(n,m);const f=`${e.ref.byteOffset}:${m.lineIndex}`;if(m.seen.has(f))return;m.seen.add(f)}const i=e.raw??{},r=typeof i.timestamp=="string"&&Date.parse(i.timestamp)||Date.now(),s=i.isMeta===!0||i.isSidechain===!0,a=bP(i),c=e.data,l=typeof c=="string"?c:typeof((p=c==null?void 0:c.message)==null?void 0:p.content)=="string"?c.message.content:null;if((e.kind==="assistant"||e.kind==="user")&&l!==null&&!s){const m=e.kind;zr(n,f=>{if(h1(f.turns,m,l)!==-1)return f;let x=f.stream;if(f.running&&m==="assistant"&&x){const y=x.indexOf(l);y!==-1&&(x=x.slice(0,y)+x.slice(y+l.length))}return{...f,stream:x,turns:dk([...f.turns,{id:Za(),role:m,text:l,at:r,kind:e.kind,ref:e.ref,attribution:a}])}});return}let d;try{d=gP(e.kind,e.data,e.raw)}catch{d=void 0}zr(n,m=>({...m,turns:dk([...m.turns,{id:Za(),role:"event",text:e.previewText??"",at:r,kind:e.kind,ref:e.ref,signal:d,attribution:a}])}))}function jP(n){var l;const{tabId:e,cwd:i,sessionUuid:r}=n,s=typeof window<"u"?(l=window.api)==null?void 0:l.transcripts:void 0;if(!(s!=null&&s.onEvent)||!s.subscribe||!s.buffer)return;const a=(od.get(e)??0)+1;if(od.set(e,a),a>1)return;mn.setState({hydratedTabs:{...mn.getState().hydratedTabs,[e]:!0}});const c=window.api.transcripts.onEvent(e,d=>uk(e,d));qb.set(e,c),window.api.transcripts.subscribe({tabId:e,cwd:i,sessionUuid:r}).then(async d=>{if(!od.has(e))return;if(!d.ok){Me.error(`Chat transcript feed unavailable: ${d.error??"subscribe failed"}`),c(),qb.delete(e),od.delete(e);const m={...mn.getState().hydratedTabs};delete m[e],mn.setState({hydratedTabs:m});return}const p=await window.api.transcripts.buffer(e);for(const m of p)uk(e,m)}).catch(d=>{var m,f;const p=d instanceof Error?d.message:String(d);(f=(m=window.api)==null?void 0:m.logs)==null||f.write("chat","warn",`transcript feed attach failed for ${e}: ${p}`)})}function TP(n){var i,r,s;const e=od.get(n);if(e){if(e>1){od.set(n,e-1);return}od.delete(n),(i=qb.get(n))==null||i(),qb.delete(n),(s=(r=window.api)==null?void 0:r.transcripts)==null||s.unsubscribe(n)}}var Hj;typeof window<"u"&&((Hj=window.api)!=null&&Hj.chat)&&(window.api.chat.onQueued(({tabId:n,position:e})=>{zr(n,i=>({...i,running:!0,queuedPosition:e}))}),window.api.chat.onRunStarted(({tabId:n})=>{zr(n,e=>({...e,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:n,delta:e})=>{zr(n,i=>({...i,stream:i.stream+e}))}),window.api.chat.onToolUse(({tabId:n,id:e,kind:i,label:r,diff:s})=>{zr(n,a=>({...a,liveToolUses:[...a.liveToolUses,{id:e,kind:i,label:r,diff:s}]}))}),window.api.chat.onComplete(({tabId:n,finalMessage:e})=>{M_(n,"assistant",e),lk(n,e),yb(n,{id:Za(),role:"assistant",text:e,at:Date.now(),outcome:yP})}),window.api.chat.onNeedsInput(({tabId:n,questions:e,answerBody:i})=>{const r=Za();if(i&&i.trim()){M_(n,"assistant",i),lk(n,i),zr(n,s=>{const a=nT(n)&&h1(s.turns,"assistant",i)!==-1;return{...s,turns:a?s.turns:[...s.turns,{id:Za(),role:"assistant",text:i,at:Date.now(),toolUses:s.liveToolUses}],liveToolUses:[]}}),yb(n,{id:r,role:"question",text:e.join(`
55
55
  `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r});return}yb(n,{id:r,role:"question",text:e.join(`
56
- `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{tT(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{Vb(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,c,l;const i=xt.getState().tabs.find(d=>d.id===n);if(i){mn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=Kt.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}mn.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(c=window.api)==null?void 0:c.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function NP(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function iT(n,e=!1,i=Ub()){let r=!e;r&&(r=await Iy(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${ha(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${ha(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const xt=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:c,dormant:l=!1})=>{const d=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===d))return n({activeTabId:d}),d;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:d,sessionId:d,label:c??NP(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:d}),d},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(()=>{}),mn.getState().dropTab(i);const r=e().tabs.filter(c=>c.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(c=>c.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=c=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:c,generation:l.generation+1}:l)})};r.presetId?Vj(r.presetId).then(c=>{a(c?qj(c,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${ha(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${ha(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(d=>d.id===i);if(!s||s.status!=="dormant")return;(l=mn.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Me.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:c}=await iT({cwd:s.cwd,sessionId:s.sessionId},!1,r??Ub());n({tabs:e().tabs.map(d=>d.id===i?{...d,sessionId:a,status:"spawning",startupCommand:c,generation:d.generation+1}:d)})},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 O_(){var i;if(xt.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 p=>{try{const{sessionId:m}=await iT(p,a);return{id:p.id,sessionId:m,cwd:p.cwd,label:p.label,presetId:p.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",p==null?void 0:p.id,m),null}}))).filter(p=>p!==null),d=s&&l.find(p=>p.id===s)?s:((i=l[0])==null?void 0:i.id)??null;xt.getState().restoreTabs(l,d)}else xt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),xt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=xt.getState(),a=r.map(c=>({id:c.id,sessionId:c.sessionId,cwd:c.cwd,label:c.label,presetId:c.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(c=>{console.warn("[sessions] save failed:",c)})};let e=null;xt.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 DP=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:O_,useSessions:xt},Symbol.toStringTag,{value:"Module"})),hk=200,AP=/\x1b\[[0-9;]*m/g;function $P(n){return n.replace(AP,"")}const Ig=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 c=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={watcherId:c.watcherId,tabId:c.tabId,label:c.label,command:c.command,cwd:c.cwd,pid:c.pid,startedAt:c.startedAt,lineCount:0,lines:[],lastLineAt:null};return n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(c){return console.error("[watchers] add failed:",c),Me.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);Me.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=$P(i.line),a=r.lines.length>=hk?[...r.lines.slice(r.lines.length-hk+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})}})),PP="~/.claude/session-manager/browser/history.json",pk="~/.claude/session-manager/browser/bookmarks.json",RP=.25,IP=3,fk=.1,mk=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let gk=0;function MP(){const n=mk[gk%mk.length];return gk+=1,n}const Yb=new Map;function OP(n){if(Yb.has(n))return;const e=window.api.browser.onNavState(n,i=>{Rt.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)}))});Yb.set(n,e)}function LP(n){const e=Yb.get(n);e&&(e(),Yb.delete(n))}const L_=new Map;let wb=null;function vk(n){const e=L_.get(n);e&&(e(),L_.delete(n))}function xk(){wb&&(clearInterval(wb),wb=null)}const z_=new Map;function _w(n){const e=z_.get(n);e&&(e(),z_.delete(n))}const Rt=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)??MP(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(c=>({tabs:[...c.tabs,a],activeTabId:r})),OP(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(c=>{var d,p;const l=c instanceof Error?c.message:String(c);(p=(d=window.api)==null?void 0:d.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(LP(r.viewId),_w(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),c=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:c}}))},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(),c=s.find(d=>d.id===r);if(!c)throw new Error("No active browser tab");if(a==="shot"){const d=await window.api.browser.captureShot(c.viewId);if(!d.ok)throw new Error(d.error);n({captured:{mode:a,url:d.url,title:d.title,dataUrl:d.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:c.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:c.url,title:c.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(()=>{}),vk(i);const r=window.api.browser.onRecordStep(i,s=>{Rt.getState().recording&&Rt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});L_.set(i,r),xk(),wb=setInterval(()=>{Rt.getState().recording&&Rt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),vk(i),xk(),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(pk),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,c=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:c}),window.api.config.writeJson(pk,c).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(PP),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(c=>c.id===i);if(!s)return;const a=Math.min(IP,Math.max(RP,r));n(c=>({tabs:c.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+fk)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-fk)},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}),_w(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Rt.setState({findMatches:a})});z_.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(_w(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(()=>{})}})),to=["home"],jx=["project"],Sw=["home","project"],Oy=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:to},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:jx},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics for this project",faces:jx},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:to},{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:Sw},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Global policy + this project's live PRD queue",faces:Sw},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Sw},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:to},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:to},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:to},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:to},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:to},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:jx},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:to},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window — per-Epic model lives in Agent Library",faces:to},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:to},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:to},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Epic intent tags and their /develop behavior",faces:to},{key:"bilko-host",group:"Configure",label:"Host on Bilko.run",icon:"link",hint:"Publish this project's Marketing page to bilko.run",faces:jx},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:to}];function zP(n){return Oy.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 BP=Object.fromEntries(Oy.map(n=>[n.key,n.group]));function bk(n){const e=Oy.find(i=>i.key===n);return e!=null&&e.faces.length===1&&e.faces[0]==="home"}const kw={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."},rT=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","memory","projects","system-prompt","permissions","settings","remote","agent-library","tag-library","bilko-host","voice","editor"],FP={editor:"Editor"},GP=Object.fromEntries(Oy.map(n=>[n.key,n.label])),HP=Object.fromEntries(rT.map(n=>[n,FP[n]??GP[n]??n])),sT="~/.claude/session-manager/app-prefs.json";async function p1(){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(sT);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function UP(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await p1();await window.api.config.writeJson(sT,{...e,...n})}const Su=rT.map(n=>({id:n,title:HP[n],component:"screen"})),gn=Ti((n,e)=>{var i;return{panels:[...Su],focusedPanelId:((i=Su[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"||bk(r)?{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"||bk(r)?{navFace:"home"}:null})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=Su[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var s;(await p1()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=Su[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview",navFace:"home"})}}});function WP(n){return gn.getState().panels.find(e=>e.id===n)}function VP(n,e,i="project"){return n==="projects"&&e===null&&i==="project"}function an({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":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"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 qP=4,yk=40,wk=6;function KP(n){const{onReorder:e,onActivate:i}=n,r=P.useRef(null),s=P.useRef(null),a=P.useRef(0),c=P.useRef(0),[l,d]=P.useState(!1),[,p]=P.useState(0),m=P.useRef(i);m.current=i;const f=P.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),x=P.useCallback((b,_,S)=>{for(let E=0;E<_.length;E++){const T=_[E].left+_[E].width/2;if(b<T)return E<=S?E:E-1}return _.length-1},[]),y=P.useCallback(()=>{const b=s.current,_=r.current;if(!(b!=null&&b.active)||!_)return;const S=_.getBoundingClientRect(),E=b.startX+b.deltaX,T=E-S.left,N=S.right-E;T<yk?_.scrollLeft-=wk:N<yk&&(_.scrollLeft+=wk),a.current=requestAnimationFrame(y)},[]);P.useEffect(()=>{const b=r.current;if(!b)return;let _=!1;const S=()=>{_||(_=!0,c.current=requestAnimationFrame(()=>{_=!1,p(N=>N+1)}))},E=N=>{var V;const $=s.current;if(!$)return;const R=N.clientX-$.startX;if(!$.active&&Math.abs(R)<qP)return;if(!$.active){$.active=!0,$.tabRects=f().map(H=>H.getBoundingClientRect()),d(!0);try{(V=r.current)==null||V.setPointerCapture($.pointerId)}catch{}a.current=requestAnimationFrame(y)}$.deltaX=R;const M=$.tabRects[$.fromIndex],z=M.left+M.width/2+R;$.currentIndex=x(z,$.tabRects,$.fromIndex),S()},T=N=>{const $=s.current;if($&&$.pointerId===N.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(c.current);try{b.releasePointerCapture($.pointerId)}catch{}$.active&&$.fromIndex!==$.currentIndex?e($.fromIndex,$.currentIndex):m.current($.fromIndex),s.current=null,d(!1),p(R=>R+1)}};return b.addEventListener("pointermove",E),b.addEventListener("pointerup",T),b.addEventListener("pointercancel",T),()=>{b.removeEventListener("pointermove",E),b.removeEventListener("pointerup",T),b.removeEventListener("pointercancel",T),cancelAnimationFrame(a.current),cancelAnimationFrame(c.current)}},[e,f,x,y]);const w=P.useCallback((b,_)=>{b.button!==0||b.target.closest("button")||(s.current={active:!1,fromIndex:_,currentIndex:_,startX:b.clientX,deltaX:0,tabRects:[],pointerId:b.pointerId})},[]);return{getTabDragProps:P.useCallback(b=>{var E;const _=s.current,S={};if(_!=null&&_.active)if(b===_.fromIndex)S.transform=`translateX(${_.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=_.fromIndex,N=_.currentIndex,R=(((E=_.tabRects[T])==null?void 0:E.width)??0)+4;S.transition="transform 0.15s ease",T<N&&b>T&&b<=N?S.transform=`translateX(-${R}px)`:T>N&&b>=N&&b<T?S.transform=`translateX(${R}px)`:S.transform="translateX(0)"}return{onPointerDown:T=>w(T,b),style:S,"data-drag-index":b}},[w]),isDragging:l,containerRef:r}}const YP=3e4;function XP({onToggleSplitView:n,splitViewActive:e}={}){const i=xt(N=>N.tabs),r=xt(N=>N.activeTabId),s=xt(N=>N.closeTab),a=xt(N=>N.setActive),c=xt(N=>N.reorderTab),l=Ig(N=>N.watchers),d=Rt(N=>N.tabs.length>0),p=r!=null&&d,m=gn(N=>N.openPanel),f=gn(N=>N.openProjectPanel),x=gn(N=>N.setEpicsWorkspaceOpen),y=gn(N=>N.navFace==="home"),[w,k]=P.useState(()=>Date.now());P.useEffect(()=>{const N=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(N)},[]);const b=N=>{for(const $ of Object.values(l))if($.tabId===N&&$.lastLineAt&&w-$.lastLineAt<YP)return!0;return!1},{getTabDragProps:_,isDragging:S,containerRef:E}=KP({tabCount:i.length,onReorder:c,onActivate:N=>{const $=i[N];$&&(a($.id),x(!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":y?"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 ${y?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(an,{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:E,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((N,$)=>{const R=N.id===r,M=_($),z=T[$%T.length];return o.jsxs("div",{...M,style:M.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"} ${R?"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":R?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:z,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"}),b(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:V=>{V.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:[p&&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.59.0"]})]})]})}var Cw={},qm={},_k;function oT(){if(_k)return qm;_k=1,Object.defineProperty(qm,"__esModule",{value:!0}),qm.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(/\/[^/]+$/,"/")),qm.baseAssetPath=i,qm}var Km={},Sk;function f1(){if(Sk)return Km;Sk=1,Object.defineProperty(Km,"__esModule",{value:!0}),Km.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return Km.defaultModelFetcher=n,Km}var $l={},Ym={},kk;function fv(){if(kk)return Ym;kk=1,Object.defineProperty(Ym,"__esModule",{value:!0}),Ym.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Ym.log={error:n("error"),debug:n("debug"),warn:n("warn")},Ym}var Xm={},Ck;function Ly(){if(Ck)return Xm;Ck=1,Object.defineProperty(Xm,"__esModule",{value:!0}),Xm.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||(Xm.Message=n={})),Xm}var Ek;function m1(){if(Ek)return $l;Ek=1,Object.defineProperty($l,"__esModule",{value:!0}),$l.FrameProcessor=$l.validateOptions=$l.defaultFrameProcessorOptions=void 0;const n=fv(),e=Ly();$l.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(c){(c.positiveSpeechThreshold<0||c.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(c.negativeSpeechThreshold<0||c.negativeSpeechThreshold>c.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),c.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),c.redemptionMs<0&&n.log.error("redemptionMs should be positive"),c.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}$l.validateOptions=i;const r=c=>{const l=c.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),d=new Float32Array(l.at(-1));return c.forEach((p,m)=>{const f=l[m];d.set(p,f)}),d};function s(c,l){const d=Math.floor(c.redemptionMs/l),p=Math.floor(c.preSpeechPadMs/l),m=Math.floor(c.minSpeechMs/l);return{redemptionFrames:d,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,d,p,m){this.modelProcessFunc=l,this.modelResetFunc=d,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=w=>{this.options={...this.options,...w};const{redemptionFrames:k,preSpeechPadFrames:b,minSpeechFrames:_}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=b,this.minSpeechFrames=_},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=w=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(w):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=w=>{const k=this.audioBuffer;this.audioBuffer=[];const b=this.speaking;if(this.reset(),b)if(k.reduce((S,E)=>E.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(E=>E.frame));w({msg:e.Message.SpeechEnd,audio:S})}else w({msg:e.Message.VADMisfire});return{}},this.process=async(w,k)=>{if(!this.active)return;const b=await this.modelProcessFunc(w),_=b.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:b,msg:e.Message.FrameProcessed,frame:w}),this.audioBuffer.push({frame:w,isSpeech:_}),_&&(this.speechFrameCount++,this.redemptionCounter=0),_&&!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})),b.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:x,minSpeechFrames:y}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=x,this.minSpeechFrames=y,this.reset()}}return $l.FrameProcessor=a,$l}var Pl={};function No(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 Ew={exports:{}};/*!
56
+ `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{tT(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{Vb(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,c,l;const i=xt.getState().tabs.find(d=>d.id===n);if(i){mn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=Kt.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}mn.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(c=window.api)==null?void 0:c.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function NP(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function iT(n,e=!1,i=Ub()){let r=!e;r&&(r=await Iy(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${ha(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${ha(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const xt=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:c,dormant:l=!1})=>{const d=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===d))return n({activeTabId:d}),d;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:d,sessionId:d,label:c??NP(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:d}),d},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(()=>{}),mn.getState().dropTab(i);const r=e().tabs.filter(c=>c.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(c=>c.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=c=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:c,generation:l.generation+1}:l)})};r.presetId?Vj(r.presetId).then(c=>{a(c?qj(c,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${ha(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${ha(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(d=>d.id===i);if(!s||s.status!=="dormant")return;(l=mn.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Me.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:c}=await iT({cwd:s.cwd,sessionId:s.sessionId},!1,r??Ub());n({tabs:e().tabs.map(d=>d.id===i?{...d,sessionId:a,status:"spawning",startupCommand:c,generation:d.generation+1}:d)})},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 O_(){var i;if(xt.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 p=>{try{const{sessionId:m}=await iT(p,a);return{id:p.id,sessionId:m,cwd:p.cwd,label:p.label,presetId:p.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",p==null?void 0:p.id,m),null}}))).filter(p=>p!==null),d=s&&l.find(p=>p.id===s)?s:((i=l[0])==null?void 0:i.id)??null;xt.getState().restoreTabs(l,d)}else xt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),xt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=xt.getState(),a=r.map(c=>({id:c.id,sessionId:c.sessionId,cwd:c.cwd,label:c.label,presetId:c.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(c=>{console.warn("[sessions] save failed:",c)})};let e=null;xt.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 DP=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:O_,useSessions:xt},Symbol.toStringTag,{value:"Module"})),hk=200,AP=/\x1b\[[0-9;]*m/g;function $P(n){return n.replace(AP,"")}const Ig=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 c=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={watcherId:c.watcherId,tabId:c.tabId,label:c.label,command:c.command,cwd:c.cwd,pid:c.pid,startedAt:c.startedAt,lineCount:0,lines:[],lastLineAt:null};return n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(c){return console.error("[watchers] add failed:",c),Me.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);Me.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=$P(i.line),a=r.lines.length>=hk?[...r.lines.slice(r.lines.length-hk+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})}})),PP="~/.claude/session-manager/browser/history.json",pk="~/.claude/session-manager/browser/bookmarks.json",RP=.25,IP=3,fk=.1,mk=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let gk=0;function MP(){const n=mk[gk%mk.length];return gk+=1,n}const Yb=new Map;function OP(n){if(Yb.has(n))return;const e=window.api.browser.onNavState(n,i=>{Rt.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)}))});Yb.set(n,e)}function LP(n){const e=Yb.get(n);e&&(e(),Yb.delete(n))}const L_=new Map;let wb=null;function vk(n){const e=L_.get(n);e&&(e(),L_.delete(n))}function xk(){wb&&(clearInterval(wb),wb=null)}const z_=new Map;function _w(n){const e=z_.get(n);e&&(e(),z_.delete(n))}const Rt=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)??MP(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(c=>({tabs:[...c.tabs,a],activeTabId:r})),OP(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(c=>{var d,p;const l=c instanceof Error?c.message:String(c);(p=(d=window.api)==null?void 0:d.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(LP(r.viewId),_w(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),c=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:c}}))},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(),c=s.find(d=>d.id===r);if(!c)throw new Error("No active browser tab");if(a==="shot"){const d=await window.api.browser.captureShot(c.viewId);if(!d.ok)throw new Error(d.error);n({captured:{mode:a,url:d.url,title:d.title,dataUrl:d.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:c.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:c.url,title:c.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(()=>{}),vk(i);const r=window.api.browser.onRecordStep(i,s=>{Rt.getState().recording&&Rt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});L_.set(i,r),xk(),wb=setInterval(()=>{Rt.getState().recording&&Rt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),vk(i),xk(),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(pk),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,c=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:c}),window.api.config.writeJson(pk,c).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(PP),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(c=>c.id===i);if(!s)return;const a=Math.min(IP,Math.max(RP,r));n(c=>({tabs:c.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+fk)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-fk)},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}),_w(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Rt.setState({findMatches:a})});z_.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(_w(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(()=>{})}})),to=["home"],jx=["project"],Sw=["home","project"],Oy=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:to},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:jx},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics for this project",faces:jx},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:to},{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:Sw},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Global policy + this project's live PRD queue",faces:Sw},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Sw},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:to},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:to},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:to},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:to},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:to},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:jx},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:to},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window — per-Epic model lives in Agent Library",faces:to},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:to},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:to},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Epic intent tags and their /develop behavior",faces:to},{key:"bilko-host",group:"Configure",label:"Host on Bilko.run",icon:"link",hint:"Publish this project's Marketing page to bilko.run",faces:jx},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:to}];function zP(n){return Oy.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 BP=Object.fromEntries(Oy.map(n=>[n.key,n.group]));function bk(n){const e=Oy.find(i=>i.key===n);return e!=null&&e.faces.length===1&&e.faces[0]==="home"}const kw={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."},rT=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","memory","projects","system-prompt","permissions","settings","remote","agent-library","tag-library","bilko-host","voice","editor"],FP={editor:"Editor"},GP=Object.fromEntries(Oy.map(n=>[n.key,n.label])),HP=Object.fromEntries(rT.map(n=>[n,FP[n]??GP[n]??n])),sT="~/.claude/session-manager/app-prefs.json";async function p1(){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(sT);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function UP(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await p1();await window.api.config.writeJson(sT,{...e,...n})}const Su=rT.map(n=>({id:n,title:HP[n],component:"screen"})),gn=Ti((n,e)=>{var i;return{panels:[...Su],focusedPanelId:((i=Su[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"||bk(r)?{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"||bk(r)?{navFace:"home"}:null})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=Su[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var s;(await p1()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=Su[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview",navFace:"home"})}}});function WP(n){return gn.getState().panels.find(e=>e.id===n)}function VP(n,e,i="project"){return n==="projects"&&e===null&&i==="project"}function an({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":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"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 qP=4,yk=40,wk=6;function KP(n){const{onReorder:e,onActivate:i}=n,r=P.useRef(null),s=P.useRef(null),a=P.useRef(0),c=P.useRef(0),[l,d]=P.useState(!1),[,p]=P.useState(0),m=P.useRef(i);m.current=i;const f=P.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),x=P.useCallback((b,_,S)=>{for(let E=0;E<_.length;E++){const T=_[E].left+_[E].width/2;if(b<T)return E<=S?E:E-1}return _.length-1},[]),y=P.useCallback(()=>{const b=s.current,_=r.current;if(!(b!=null&&b.active)||!_)return;const S=_.getBoundingClientRect(),E=b.startX+b.deltaX,T=E-S.left,N=S.right-E;T<yk?_.scrollLeft-=wk:N<yk&&(_.scrollLeft+=wk),a.current=requestAnimationFrame(y)},[]);P.useEffect(()=>{const b=r.current;if(!b)return;let _=!1;const S=()=>{_||(_=!0,c.current=requestAnimationFrame(()=>{_=!1,p(N=>N+1)}))},E=N=>{var V;const $=s.current;if(!$)return;const R=N.clientX-$.startX;if(!$.active&&Math.abs(R)<qP)return;if(!$.active){$.active=!0,$.tabRects=f().map(H=>H.getBoundingClientRect()),d(!0);try{(V=r.current)==null||V.setPointerCapture($.pointerId)}catch{}a.current=requestAnimationFrame(y)}$.deltaX=R;const M=$.tabRects[$.fromIndex],z=M.left+M.width/2+R;$.currentIndex=x(z,$.tabRects,$.fromIndex),S()},T=N=>{const $=s.current;if($&&$.pointerId===N.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(c.current);try{b.releasePointerCapture($.pointerId)}catch{}$.active&&$.fromIndex!==$.currentIndex?e($.fromIndex,$.currentIndex):m.current($.fromIndex),s.current=null,d(!1),p(R=>R+1)}};return b.addEventListener("pointermove",E),b.addEventListener("pointerup",T),b.addEventListener("pointercancel",T),()=>{b.removeEventListener("pointermove",E),b.removeEventListener("pointerup",T),b.removeEventListener("pointercancel",T),cancelAnimationFrame(a.current),cancelAnimationFrame(c.current)}},[e,f,x,y]);const w=P.useCallback((b,_)=>{b.button!==0||b.target.closest("button")||(s.current={active:!1,fromIndex:_,currentIndex:_,startX:b.clientX,deltaX:0,tabRects:[],pointerId:b.pointerId})},[]);return{getTabDragProps:P.useCallback(b=>{var E;const _=s.current,S={};if(_!=null&&_.active)if(b===_.fromIndex)S.transform=`translateX(${_.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=_.fromIndex,N=_.currentIndex,R=(((E=_.tabRects[T])==null?void 0:E.width)??0)+4;S.transition="transform 0.15s ease",T<N&&b>T&&b<=N?S.transform=`translateX(-${R}px)`:T>N&&b>=N&&b<T?S.transform=`translateX(${R}px)`:S.transform="translateX(0)"}return{onPointerDown:T=>w(T,b),style:S,"data-drag-index":b}},[w]),isDragging:l,containerRef:r}}const YP=3e4;function XP({onToggleSplitView:n,splitViewActive:e}={}){const i=xt(N=>N.tabs),r=xt(N=>N.activeTabId),s=xt(N=>N.closeTab),a=xt(N=>N.setActive),c=xt(N=>N.reorderTab),l=Ig(N=>N.watchers),d=Rt(N=>N.tabs.length>0),p=r!=null&&d,m=gn(N=>N.openPanel),f=gn(N=>N.openProjectPanel),x=gn(N=>N.setEpicsWorkspaceOpen),y=gn(N=>N.navFace==="home"),[w,k]=P.useState(()=>Date.now());P.useEffect(()=>{const N=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(N)},[]);const b=N=>{for(const $ of Object.values(l))if($.tabId===N&&$.lastLineAt&&w-$.lastLineAt<YP)return!0;return!1},{getTabDragProps:_,isDragging:S,containerRef:E}=KP({tabCount:i.length,onReorder:c,onActivate:N=>{const $=i[N];$&&(a($.id),x(!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":y?"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 ${y?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(an,{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:E,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((N,$)=>{const R=N.id===r,M=_($),z=T[$%T.length];return o.jsxs("div",{...M,style:M.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"} ${R?"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":R?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:z,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"}),b(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:V=>{V.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:[p&&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.60.0"]})]})]})}var Cw={},qm={},_k;function oT(){if(_k)return qm;_k=1,Object.defineProperty(qm,"__esModule",{value:!0}),qm.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(/\/[^/]+$/,"/")),qm.baseAssetPath=i,qm}var Km={},Sk;function f1(){if(Sk)return Km;Sk=1,Object.defineProperty(Km,"__esModule",{value:!0}),Km.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return Km.defaultModelFetcher=n,Km}var $l={},Ym={},kk;function fv(){if(kk)return Ym;kk=1,Object.defineProperty(Ym,"__esModule",{value:!0}),Ym.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Ym.log={error:n("error"),debug:n("debug"),warn:n("warn")},Ym}var Xm={},Ck;function Ly(){if(Ck)return Xm;Ck=1,Object.defineProperty(Xm,"__esModule",{value:!0}),Xm.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||(Xm.Message=n={})),Xm}var Ek;function m1(){if(Ek)return $l;Ek=1,Object.defineProperty($l,"__esModule",{value:!0}),$l.FrameProcessor=$l.validateOptions=$l.defaultFrameProcessorOptions=void 0;const n=fv(),e=Ly();$l.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(c){(c.positiveSpeechThreshold<0||c.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(c.negativeSpeechThreshold<0||c.negativeSpeechThreshold>c.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),c.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),c.redemptionMs<0&&n.log.error("redemptionMs should be positive"),c.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}$l.validateOptions=i;const r=c=>{const l=c.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),d=new Float32Array(l.at(-1));return c.forEach((p,m)=>{const f=l[m];d.set(p,f)}),d};function s(c,l){const d=Math.floor(c.redemptionMs/l),p=Math.floor(c.preSpeechPadMs/l),m=Math.floor(c.minSpeechMs/l);return{redemptionFrames:d,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,d,p,m){this.modelProcessFunc=l,this.modelResetFunc=d,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=w=>{this.options={...this.options,...w};const{redemptionFrames:k,preSpeechPadFrames:b,minSpeechFrames:_}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=b,this.minSpeechFrames=_},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=w=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(w):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=w=>{const k=this.audioBuffer;this.audioBuffer=[];const b=this.speaking;if(this.reset(),b)if(k.reduce((S,E)=>E.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(E=>E.frame));w({msg:e.Message.SpeechEnd,audio:S})}else w({msg:e.Message.VADMisfire});return{}},this.process=async(w,k)=>{if(!this.active)return;const b=await this.modelProcessFunc(w),_=b.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:b,msg:e.Message.FrameProcessed,frame:w}),this.audioBuffer.push({frame:w,isSpeech:_}),_&&(this.speechFrameCount++,this.redemptionCounter=0),_&&!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})),b.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:x,minSpeechFrames:y}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=x,this.minSpeechFrames=y,this.reset()}}return $l.FrameProcessor=a,$l}var Pl={};function No(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 Ew={exports:{}};/*!
57
57
  * ONNX Runtime Web v1.26.0
58
58
  * Copyright (c) Microsoft Corporation. All rights reserved.
59
59
  * Licensed under the MIT License.
@@ -2907,7 +2907,7 @@ ${O}`,F=C.createShaderModule({code:L,label:u.name});cn("verbose",()=>`[WebGPU] $
2907
2907
  * ONNX Runtime Web v1.26.0
2908
2908
  * Copyright (c) Microsoft Corporation. All rights reserved.
2909
2909
  * Licensed under the MIT License.
2910
- */var Ik;function iR(){return Ik||(Ik=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,c=Object.prototype.hasOwnProperty,l=(oe=>typeof No<"u"?No:typeof Proxy<"u"?new Proxy(oe,{get:(pe,we)=>(typeof No<"u"?No:pe)[we]}):oe)(function(oe){if(typeof No<"u")return No.apply(this,arguments);throw Error('Dynamic require of "'+oe+'" is not supported')}),d=(oe,pe)=>()=>(oe&&(pe=oe(oe=0)),pe),p=(oe,pe)=>{for(var we in pe)r(oe,we,{get:pe[we],enumerable:!0})},m=(oe,pe,we,$e)=>{if(pe&&typeof pe=="object"||typeof pe=="function")for(let Ee of a(pe))!c.call(oe,Ee)&&Ee!==we&&r(oe,Ee,{get:()=>pe[Ee],enumerable:!($e=s(pe,Ee))||$e.enumerable});return oe},f=oe=>m(r({},"__esModule",{value:!0}),oe),x,y,w,k,b,_=d(()=>{x=new Map,y=[],w=(oe,pe,we)=>{if(pe&&typeof pe.init=="function"&&typeof pe.createInferenceSessionHandler=="function"){let $e=x.get(oe);if($e===void 0)x.set(oe,{backend:pe,priority:we});else{if($e.priority>we)return;if($e.priority===we&&$e.backend!==pe)throw new Error(`cannot register backend "${oe}" using priority ${we}`)}if(we>=0){let Ee=y.indexOf(oe);Ee!==-1&&y.splice(Ee,1);for(let Ge=0;Ge<y.length;Ge++)if(x.get(y[Ge]).priority<=we){y.splice(Ge,0,oe);return}y.push(oe)}return}throw new TypeError("not a valid backend")},k=async oe=>{let pe=x.get(oe);if(!pe)return"backend not found.";if(pe.initialized)return pe.backend;if(pe.aborted)return pe.error;{let we=!!pe.initPromise;try{return we||(pe.initPromise=pe.backend.init(oe)),await pe.initPromise,pe.initialized=!0,pe.backend}catch($e){return we||(pe.error=`${$e}`,pe.aborted=!0),pe.error}finally{delete pe.initPromise}}},b=async oe=>{let pe=oe.executionProviders||[],we=pe.map(He=>typeof He=="string"?He:He.name),$e=we.length===0?y:we,Ee,Ge=[],Re=new Set;for(let He of $e){let it=await k(He);typeof it=="string"?Ge.push({name:He,err:it}):(Ee||(Ee=it),Ee===it&&Re.add(He))}if(!Ee)throw new Error(`no available backend found. ERR: ${Ge.map(He=>`[${He.name}] ${He.err}`).join(", ")}`);for(let{name:He,err:it}of Ge)we.includes(He)&&console.warn(`removing requested execution provider "${He}" from session options because it is not available: ${it}`);let Ie=pe.filter(He=>Re.has(typeof He=="string"?He:He.name));return[Ee,new Proxy(oe,{get:(He,it)=>it==="executionProviders"?Ie:Reflect.get(He,it)})]}}),S=d(()=>{_()}),E,T=d(()=>{E="1.26.0"}),N,$,R=d(()=>{T(),N="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:E},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($,"logLevel",{enumerable:!0})}),M,z=d(()=>{R(),M=$}),V,H,Q=d(()=>{V=(oe,pe)=>{let we=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);we.width=oe.dims[3],we.height=oe.dims[2];let $e=we.getContext("2d");if($e!=null){let Ee,Ge;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Ge=oe.dims[3]):(Ee=oe.dims[3],Ge=oe.dims[2]);let Re=(pe==null?void 0:pe.format)!==void 0?pe.format:"RGB",Ie=pe==null?void 0:pe.norm,He,it;Ie===void 0||Ie.mean===void 0?He=[255,255,255,255]:typeof Ie.mean=="number"?He=[Ie.mean,Ie.mean,Ie.mean,Ie.mean]:(He=[Ie.mean[0],Ie.mean[1],Ie.mean[2],0],Ie.mean[3]!==void 0&&(He[3]=Ie.mean[3])),Ie===void 0||Ie.bias===void 0?it=[0,0,0,0]:typeof Ie.bias=="number"?it=[Ie.bias,Ie.bias,Ie.bias,Ie.bias]:(it=[Ie.bias[0],Ie.bias[1],Ie.bias[2],0],Ie.bias[3]!==void 0&&(it[3]=Ie.bias[3]));let lt=Ge*Ee,rt=0,Je=lt,Pt=lt*2,Fe=-1;Re==="RGBA"?(rt=0,Je=lt,Pt=lt*2,Fe=lt*3):Re==="RGB"?(rt=0,Je=lt,Pt=lt*2):Re==="RBG"&&(rt=0,Pt=lt,Je=lt*2);for(let ht=0;ht<Ge;ht++)for(let Rn=0;Rn<Ee;Rn++){let tn=(oe.data[rt++]-it[0])*He[0],nn=(oe.data[Je++]-it[1])*He[1],In=(oe.data[Pt++]-it[2])*He[2],Bt=Fe===-1?255:(oe.data[Fe++]-it[3])*He[3];$e.fillStyle="rgba("+tn+","+nn+","+In+","+Bt+")",$e.fillRect(Rn,ht,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")},H=(oe,pe)=>{let we=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),$e;if(we!=null){let Ee,Ge,Re;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Ge=oe.dims[1],Re=oe.dims[3]):(Ee=oe.dims[3],Ge=oe.dims[2],Re=oe.dims[1]);let Ie=pe!==void 0&&pe.format!==void 0?pe.format:"RGB",He=pe==null?void 0:pe.norm,it,lt;He===void 0||He.mean===void 0?it=[255,255,255,255]:typeof He.mean=="number"?it=[He.mean,He.mean,He.mean,He.mean]:(it=[He.mean[0],He.mean[1],He.mean[2],255],He.mean[3]!==void 0&&(it[3]=He.mean[3])),He===void 0||He.bias===void 0?lt=[0,0,0,0]:typeof He.bias=="number"?lt=[He.bias,He.bias,He.bias,He.bias]:(lt=[He.bias[0],He.bias[1],He.bias[2],0],He.bias[3]!==void 0&&(lt[3]=He.bias[3]));let rt=Ge*Ee;if(pe!==void 0&&(pe.format!==void 0&&Re===4&&pe.format!=="RGBA"||Re===3&&pe.format!=="RGB"&&pe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Je=4,Pt=0,Fe=1,ht=2,Rn=3,tn=0,nn=rt,In=rt*2,Bt=-1;Ie==="RGBA"?(tn=0,nn=rt,In=rt*2,Bt=rt*3):Ie==="RGB"?(tn=0,nn=rt,In=rt*2):Ie==="RBG"&&(tn=0,In=rt,nn=rt*2),$e=we.createImageData(Ee,Ge);for(let Fn=0;Fn<Ge*Ee;Pt+=Je,Fe+=Je,ht+=Je,Rn+=Je,Fn++)$e.data[Pt]=(oe.data[tn++]-lt[0])*it[0],$e.data[Fe]=(oe.data[nn++]-lt[1])*it[1],$e.data[ht]=(oe.data[In++]-lt[2])*it[2],$e.data[Rn]=Bt===-1?255:(oe.data[Bt++]-lt[3])*it[3]}else throw new Error("Can not access image data");return $e}}),X,q,J,ee,ie,re,B=d(()=>{Ae(),X=(oe,pe)=>{if(oe===void 0)throw new Error("Image buffer must be defined");if(pe.height===void 0||pe.width===void 0)throw new Error("Image height and width must be defined");if(pe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:we,width:$e}=pe,Ee=pe.norm??{mean:255,bias:0},Ge,Re;typeof Ee.mean=="number"?Ge=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:Ge=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?Re=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:Re=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let Ie=pe.format!==void 0?pe.format:"RGBA",He=pe.tensorFormat!==void 0&&pe.tensorFormat!==void 0?pe.tensorFormat:"RGB",it=we*$e,lt=He==="RGBA"?new Float32Array(it*4):new Float32Array(it*3),rt=4,Je=0,Pt=1,Fe=2,ht=3,Rn=0,tn=it,nn=it*2,In=-1;Ie==="RGB"&&(rt=3,Je=0,Pt=1,Fe=2,ht=-1),He==="RGBA"?In=it*3:He==="RBG"?(Rn=0,nn=it,tn=it*2):He==="BGR"&&(nn=0,tn=it,Rn=it*2);for(let Bt=0;Bt<it;Bt++,Je+=rt,Fe+=rt,Pt+=rt,ht+=rt)lt[Rn++]=(oe[Je]+Re[0])/Ge[0],lt[tn++]=(oe[Pt]+Re[1])/Ge[1],lt[nn++]=(oe[Fe]+Re[2])/Ge[2],In!==-1&&ht!==-1&&(lt[In++]=(oe[ht]+Re[3])/Ge[3]);return He==="RGBA"?new se("float32",lt,[1,4,we,$e]):new se("float32",lt,[1,3,we,$e])},q=async(oe,pe)=>{let we=typeof HTMLImageElement<"u"&&oe instanceof HTMLImageElement,$e=typeof ImageData<"u"&&oe instanceof ImageData,Ee=typeof ImageBitmap<"u"&&oe instanceof ImageBitmap,Ge=typeof oe=="string",Re,Ie=pe??{},He=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},it=lt=>typeof HTMLCanvasElement<"u"&&lt instanceof HTMLCanvasElement||lt instanceof OffscreenCanvas?lt.getContext("2d"):null;if(we){let lt=He();lt.width=oe.width,lt.height=oe.height;let rt=it(lt);if(rt!=null){let Je=oe.height,Pt=oe.width;if(pe!==void 0&&pe.resizedHeight!==void 0&&pe.resizedWidth!==void 0&&(Je=pe.resizedHeight,Pt=pe.resizedWidth),pe!==void 0){if(Ie=pe,pe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ie.tensorFormat="RGBA",Ie.height=Je,Ie.width=Pt}else Ie.tensorFormat="RGBA",Ie.height=Je,Ie.width=Pt;rt.drawImage(oe,0,0),Re=rt.getImageData(0,0,Pt,Je).data}else throw new Error("Can not access image data")}else if($e){let lt,rt;if(pe!==void 0&&pe.resizedWidth!==void 0&&pe.resizedHeight!==void 0?(lt=pe.resizedHeight,rt=pe.resizedWidth):(lt=oe.height,rt=oe.width),pe!==void 0&&(Ie=pe),Ie.format="RGBA",Ie.height=lt,Ie.width=rt,pe!==void 0){let Je=He();Je.width=rt,Je.height=lt;let Pt=it(Je);if(Pt!=null)Pt.putImageData(oe,0,0),Re=Pt.getImageData(0,0,rt,lt).data;else throw new Error("Can not access image data")}else Re=oe.data}else if(Ee){if(pe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let lt=He();lt.width=oe.width,lt.height=oe.height;let rt=it(lt);if(rt!=null){let Je=oe.height,Pt=oe.width;return rt.drawImage(oe,0,0,Pt,Je),Re=rt.getImageData(0,0,Pt,Je).data,Ie.height=Je,Ie.width=Pt,X(Re,Ie)}else throw new Error("Can not access image data")}else{if(Ge)return new Promise((lt,rt)=>{let Je=He(),Pt=it(Je);if(!oe||!Pt)return rt();let Fe=new Image;Fe.crossOrigin="Anonymous",Fe.src=oe,Fe.onload=()=>{Je.width=Fe.width,Je.height=Fe.height,Pt.drawImage(Fe,0,0,Je.width,Je.height);let ht=Pt.getImageData(0,0,Je.width,Je.height);Ie.height=Je.height,Ie.width=Je.width,lt(X(ht.data,Ie))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Re!==void 0)return X(Re,Ie);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(oe,pe)=>{let{width:we,height:$e,download:Ee,dispose:Ge}=pe,Re=[1,$e,we,4];return new se({location:"texture",type:"float32",texture:oe,dims:Re,download:Ee,dispose:Ge})},ee=(oe,pe)=>{let{dataType:we,dims:$e,download:Ee,dispose:Ge}=pe;return new se({location:"gpu-buffer",type:we??"float32",gpuBuffer:oe,dims:$e,download:Ee,dispose:Ge})},ie=(oe,pe)=>{let{dataType:we,dims:$e,download:Ee,dispose:Ge}=pe;return new se({location:"ml-tensor",type:we??"float32",mlTensor:oe,dims:$e,download:Ee,dispose:Ge})},re=(oe,pe,we)=>new se({location:"cpu-pinned",type:oe,data:pe,dims:we??[pe.length]})}),Z,W,le,ae,fe=d(()=>{Z=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),W=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,pe=typeof BigUint64Array<"u"&&BigUint64Array.from,we=globalThis.Float16Array,$e=typeof we<"u"&&we.from;oe&&(Z.set("int64",BigInt64Array),W.set(BigInt64Array,"int64")),pe&&(Z.set("uint64",BigUint64Array),W.set(BigUint64Array,"uint64")),$e?(Z.set("float16",we),W.set(we,"float16")):Z.set("float16",Uint16Array)}}}),Te,Ne,me=d(()=>{Ae(),Te=oe=>{let pe=1;for(let we=0;we<oe.length;we++){let $e=oe[we];if(typeof $e!="number"||!Number.isSafeInteger($e))throw new TypeError(`dims[${we}] must be an integer, got: ${$e}`);if($e<0)throw new RangeError(`dims[${we}] must be a non-negative integer, got: ${$e}`);pe*=$e}return pe},Ne=(oe,pe)=>{switch(oe.location){case"cpu":return new se(oe.type,oe.data,pe);case"cpu-pinned":return new se({location:"cpu-pinned",data:oe.data,type:oe.type,dims:pe});case"texture":return new se({location:"texture",texture:oe.texture,type:oe.type,dims:pe});case"gpu-buffer":return new se({location:"gpu-buffer",gpuBuffer:oe.gpuBuffer,type:oe.type,dims:pe});case"ml-tensor":return new se({location:"ml-tensor",mlTensor:oe.mlTensor,type:oe.type,dims:pe});default:throw new Error(`tensorReshape: tensor location ${oe.location} is not supported`)}}}),se,Ae=d(()=>{Q(),B(),fe(),me(),se=class{constructor(oe,pe,we){ae();let $e,Ee;if(typeof oe=="object"&&"location"in oe)switch(this.dataLocation=oe.location,$e=oe.type,Ee=oe.dims,oe.location){case"cpu-pinned":{let Re=Z.get($e);if(!Re)throw new TypeError(`unsupported type "${$e}" to create tensor from pinned buffer`);if(!(oe.data instanceof Re))throw new TypeError(`buffer should be of type ${Re.name}`);this.cpuData=oe.data;break}case"texture":{if($e!=="float32")throw new TypeError(`unsupported type "${$e}" to create tensor from texture`);this.gpuTextureData=oe.texture,this.downloader=oe.download,this.disposer=oe.dispose;break}case"gpu-buffer":{if($e!=="float32"&&$e!=="float16"&&$e!=="int32"&&$e!=="int64"&&$e!=="uint32"&&$e!=="uint8"&&$e!=="bool"&&$e!=="uint4"&&$e!=="int4")throw new TypeError(`unsupported type "${$e}" to create tensor from gpu buffer`);this.gpuBufferData=oe.gpuBuffer,this.downloader=oe.download,this.disposer=oe.dispose;break}case"ml-tensor":{if($e!=="float32"&&$e!=="float16"&&$e!=="int32"&&$e!=="int64"&&$e!=="uint32"&&$e!=="uint64"&&$e!=="int8"&&$e!=="uint8"&&$e!=="bool"&&$e!=="uint4"&&$e!=="int4")throw new TypeError(`unsupported type "${$e}" 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 Re,Ie;if(typeof oe=="string")if($e=oe,Ie=we,oe==="string"){if(!Array.isArray(pe))throw new TypeError("A string tensor's data must be a string array.");Re=pe}else{let He=Z.get(oe);if(He===void 0)throw new TypeError(`Unsupported tensor type: ${oe}.`);if(Array.isArray(pe)){if(oe==="float16"&&He===Uint16Array||oe==="uint4"||oe==="int4")throw new TypeError(`Creating a ${oe} tensor from number array is not supported. Please use ${He.name} as data.`);oe==="uint64"||oe==="int64"?Re=He.from(pe,BigInt):Re=He.from(pe)}else if(pe instanceof He)Re=pe;else if(pe instanceof Uint8ClampedArray)if(oe==="uint8")Re=Uint8Array.from(pe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(oe==="float16"&&pe instanceof Uint16Array&&He!==Uint16Array)Re=new globalThis.Float16Array(pe.buffer,pe.byteOffset,pe.length);else throw new TypeError(`A ${$e} tensor's data must be type of ${He}`)}else if(Ie=pe,Array.isArray(oe)){if(oe.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let He=typeof oe[0];if(He==="string")$e="string",Re=oe;else if(He==="boolean")$e="bool",Re=Uint8Array.from(oe);else throw new TypeError(`Invalid element type of data array: ${He}.`)}else if(oe instanceof Uint8ClampedArray)$e="uint8",Re=Uint8Array.from(oe);else{let He=W.get(oe.constructor);if(He===void 0)throw new TypeError(`Unsupported type for tensor data: ${oe.constructor}.`);$e=He,Re=oe}if(Ie===void 0)Ie=[Re.length];else if(!Array.isArray(Ie))throw new TypeError("A tensor's dims must be a number array");Ee=Ie,this.cpuData=Re,this.dataLocation="cpu"}let Ge=Te(Ee);if(this.cpuData&&Ge!==this.cpuData.length&&!(($e==="uint4"||$e==="int4")&&Math.ceil(Ge/2)===this.cpuData.length))throw new Error(`Tensor's size(${Ge}) does not match data length(${this.cpuData.length}).`);this.type=$e,this.dims=Ee,this.size=Ge}static async fromImage(oe,pe){return q(oe,pe)}static fromTexture(oe,pe){return J(oe,pe)}static fromGpuBuffer(oe,pe){return ee(oe,pe)}static fromMLTensor(oe,pe){return ie(oe,pe)}static fromPinnedBuffer(oe,pe,we){return re(oe,pe,we)}toDataURL(oe){return V(this,oe)}toImageData(oe){return H(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 pe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=pe,oe&&this.disposer&&(this.disposer(),this.disposer=void 0),pe}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 Ne(this,oe)}}}),ge,Se=d(()=>{Ae(),ge=se}),ye,et,pt,ot,nt,at,Nt=d(()=>{R(),ye=(oe,pe)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${oe}::ORT::${pe}`)},et=(oe,pe)=>{var Ee;let we=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],$e=!1;for(let Ge=0;Ge<we.length;Ge++){if($e&&!we[Ge].includes("TRACE_FUNC")){let Re=`FUNC_${oe}::${we[Ge].trim().split(" ")[1]}`;pe&&(Re+=`::${pe}`),ye("CPU",Re);return}we[Ge].includes("TRACE_FUNC")&&($e=!0)}},pt=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||et("BEGIN",oe)},ot=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||et("END",oe)},nt=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${oe}`)},at=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${oe}`)}}),sn,vn=d(()=>{_(),Se(),Nt(),sn=class uT{constructor(pe){this.handler=pe}async run(pe,we,$e){pt(),nt("InferenceSession.run");let Ee={},Ge={};if(typeof pe!="object"||pe===null||pe instanceof ge||Array.isArray(pe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Re=!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.");Re=!1;for(let it of we){if(typeof it!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(it)===-1)throw new RangeError(`'fetches' contains invalid output name: ${it}.`);Ee[it]=null}if(typeof $e=="object"&&$e!==null)Ge=$e;else if(typeof $e<"u")throw new TypeError("'options' must be an object.")}else{let it=!1,lt=Object.getOwnPropertyNames(we);for(let rt of this.outputNames)if(lt.indexOf(rt)!==-1){let Je=we[rt];(Je===null||Je instanceof ge)&&(it=!0,Re=!1,Ee[rt]=Je)}if(it){if(typeof $e=="object"&&$e!==null)Ge=$e;else if(typeof $e<"u")throw new TypeError("'options' must be an object.")}else Ge=we}}else if(typeof we<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let it of this.inputNames)if(typeof pe[it]>"u")throw new Error(`input '${it}' is missing in 'feeds'.`);if(Re)for(let it of this.outputNames)Ee[it]=null;let Ie=await this.handler.run(pe,Ee,Ge),He={};for(let it in Ie)if(Object.hasOwnProperty.call(Ie,it)){let lt=Ie[it];lt instanceof ge?He[it]=lt:He[it]=new ge(lt.type,lt.data,lt.dims)}return at("InferenceSession.run"),ot(),He}async release(){return this.handler.dispose()}static async create(pe,we,$e,Ee){pt(),nt("InferenceSession.create");let Ge,Re={};if(typeof pe=="string"){if(Ge=pe,typeof we=="object"&&we!==null)Re=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof Uint8Array){if(Ge=pe,typeof we=="object"&&we!==null)Re=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&pe instanceof SharedArrayBuffer){let lt=pe,rt=0,Je=pe.byteLength;if(typeof we=="object"&&we!==null)Re=we;else if(typeof we=="number"){if(rt=we,!Number.isSafeInteger(rt))throw new RangeError("'byteOffset' must be an integer.");if(rt<0||rt>=lt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${lt.byteLength}).`);if(Je=pe.byteLength-rt,typeof $e=="number"){if(Je=$e,!Number.isSafeInteger(Je))throw new RangeError("'byteLength' must be an integer.");if(Je<=0||rt+Je>lt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${lt.byteLength-rt}].`);if(typeof Ee=="object"&&Ee!==null)Re=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else if(typeof $e<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof we<"u")throw new TypeError("'options' must be an object.");Ge=new Uint8Array(lt,rt,Je)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ie,He]=await b(Re),it=await Ie.createInferenceSessionHandler(Ge,He);return at("InferenceSession.create"),ot(),new uT(it)}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,Et=d(()=>{vn(),Ze=sn}),bt=d(()=>{}),pn=d(()=>{}),$n=d(()=>{}),tr=d(()=>{}),wr={};p(wr,{InferenceSession:()=>Ze,TRACE:()=>ye,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>at,TRACE_FUNC_BEGIN:()=>pt,TRACE_FUNC_END:()=>ot,Tensor:()=>ge,env:()=>M,registerBackend:()=>w});var xn=d(()=>{S(),z(),Et(),Se(),bt(),pn(),Nt(),$n(),tr()}),Wi=d(()=>{}),Jn={};p(Jn,{default:()=>Os});var ui,bn,Os,ol=d(()=>{var oe;_e(),rr(),ir(),ui="ort-wasm-proxy-worker",bn=((oe=globalThis.self)==null?void 0:oe.name)===ui,bn&&(self.onmessage=pe=>{let{type:we,in:$e}=pe.data;try{switch(we){case"init-wasm":bs($e.wasm).then(()=>{ya($e).then(()=>{postMessage({type:we})},Ee=>{postMessage({type:we,err:Ee})})},Ee=>{postMessage({type:we,err:Ee})});break;case"init-ep":{let{epName:Ee,env:Ge}=$e;Us(Ge,Ee).then(()=>{postMessage({type:we})},Re=>{postMessage({type:we,err:Re})});break}case"copy-from":{let{buffer:Ee}=$e,Ge=cn(Ee);postMessage({type:we,out:Ge});break}case"create":{let{model:Ee,options:Ge}=$e;Er(Ee,Ge).then(Re=>{postMessage({type:we,out:Re})},Re=>{postMessage({type:we,err:Re})});break}case"release":uo($e),postMessage({type:we});break;case"run":{let{sessionId:Ee,inputIndices:Ge,inputs:Re,outputIndices:Ie,options:He}=$e;Xe(Ee,Ge,Re,Ie,new Array(Ie.length).fill(null),He).then(it=>{it.some(lt=>lt[3]!=="cpu")?postMessage({type:we,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:we,out:it},gt([...Re,...it]))},it=>{postMessage({type:we,err:it})});break}case"end-profiling":or($e),postMessage({type:we});break;default:}}catch(Ee){postMessage({type:we,err:Ee})}}),Os=bn?null:pe=>new Worker(pe??Cn,{type:"classic",name:ui})}),xa,Ls,Cn,nr,hi,zs,Zr,_r,ao,Bs,Fs,Qr,Vi,ir=d(()=>{Wi(),xa=typeof location>"u"?void 0:location.origin,Ls=()=>{var oe,pe;return typeof document<"u"?(oe=document.currentScript)==null?void 0:oe.src:typeof self<"u"?(pe=self.location)==null?void 0:pe.href:void 0},Cn=Ls(),nr=()=>{if(Cn&&!Cn.startsWith("blob:"))return Cn.substring(0,Cn.lastIndexOf("/")+1)},hi=(oe,pe)=>{try{let we=pe??Cn;return(we?new URL(oe,we):new URL(oe)).origin===xa}catch{return!1}},zs=(oe,pe)=>{let we=pe??Cn;try{return(we?new URL(oe,we):new URL(oe)).href}catch{return}},Zr=(oe,pe)=>`${pe??"./"}${oe}`,_r=async oe=>{let pe=await(await fetch(oe,{credentials:"same-origin"})).blob();return URL.createObjectURL(pe)},ao=async oe=>(await import(oe)).default,Bs=(ol(),f(Jn)).default,Fs=async()=>{if(!Cn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(hi(Cn))return[void 0,Bs()];let oe=await _r(Cn);return[oe,Bs(oe)]},Qr=void 0,Vi=async(oe,pe,we,$e)=>{let Ee=Qr&&!(oe||pe);if(Ee)if(Cn)Ee=hi(Cn)||$e&&!we;else if($e&&!we)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Qr];{let Ge="ort-wasm-simd-threaded.mjs",Re=oe??zs(Ge,pe),Ie=we&&Re&&!hi(Re,pe),He=Ie?await _r(Re):Re??Zr(Ge,pe);return[Ie?He:void 0,await ao(He)]}}}),gs,qi,Sr,Hr,Ro,vs,xs,bs,Gt,rr=d(()=>{ir(),qi=!1,Sr=!1,Hr=!1,Ro=()=>{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}},vs=()=>{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}},xs=()=>{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}},bs=async oe=>{if(qi)return Promise.resolve();if(Sr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Hr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Sr=!0;let pe=oe.initTimeout,we=oe.numThreads;if(oe.simd!==!1){if(oe.simd==="relaxed"){if(!xs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let $e=Ro();we>1&&!$e&&(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,Ge=typeof Ee=="string"?Ee:void 0,Re=Ee==null?void 0:Ee.mjs,Ie=(Re==null?void 0:Re.href)??Re,He=Ee==null?void 0:Ee.wasm,it=(He==null?void 0:He.href)??He,lt=oe.wasmBinary,[rt,Je]=await Vi(Ie,Ge,we>1,!!lt||!!it),Pt=!1,Fe=[];if(pe>0&&Fe.push(new Promise(ht=>{setTimeout(()=>{Pt=!0,ht()},pe)})),Fe.push(new Promise((ht,Rn)=>{let tn={numThreads:we};if(lt)tn.wasmBinary=lt,tn.locateFile=nn=>nn;else if(it||Ge)tn.locateFile=nn=>it??Ge+nn;else if(Ie&&Ie.indexOf("blob:")!==0)tn.locateFile=nn=>new URL(nn,Ie).href;else if(rt){let nn=nr();nn&&(tn.locateFile=In=>nn+In)}Je(tn).then(nn=>{Sr=!1,qi=!0,gs=nn,ht(),rt&&URL.revokeObjectURL(rt)},nn=>{Sr=!1,Hr=!0,Rn(nn)})})),await Promise.race(Fe),Pt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${pe}ms`)},Gt=()=>{if(qi&&gs)return gs;throw new Error("WebAssembly is not initialized yet.")}}),Zn,Nn,jt,lo=d(()=>{rr(),Zn=(oe,pe)=>{let we=Gt(),$e=we.lengthBytesUTF8(oe)+1,Ee=we._malloc($e);return we.stringToUTF8(oe,Ee,$e),pe.push(Ee),Ee},Nn=(oe,pe,we,$e)=>{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,Ge])=>{let Re=pe?pe+Ee:Ee;if(typeof Ge=="object")Nn(Ge,Re+".",we,$e);else if(typeof Ge=="string"||typeof Ge=="number")$e(Re,Ge.toString());else if(typeof Ge=="boolean")$e(Re,Ge?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Ge}`)})},jt=oe=>{let pe=Gt(),we=pe.stackSave();try{let $e=pe.PTR_SIZE,Ee=pe.stackAlloc(2*$e);pe._OrtGetLastError(Ee,Ee+$e);let Ge=Number(pe.getValue(Ee,$e===4?"i32":"i64")),Re=pe.getValue(Ee+$e,"*"),Ie=Re?pe.UTF8ToString(Re):"";throw new Error(`${oe} ERROR_CODE: ${Ge}, ERROR_MESSAGE: ${Ie}`)}finally{pe.stackRestore(we)}}}),Io,al=d(()=>{rr(),lo(),Io=oe=>{let pe=Gt(),we=0,$e=[],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 Ge=0;return(oe==null?void 0:oe.tag)!==void 0&&(Ge=Zn(oe.tag,$e)),we=pe._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,Ge),we===0&&jt("Can't create run options."),(oe==null?void 0:oe.extra)!==void 0&&Nn(oe.extra,"",new WeakSet,(Re,Ie)=>{let He=Zn(Re,$e),it=Zn(Ie,$e);pe._OrtAddRunConfigEntry(we,He,it)!==0&&jt(`Can't set a run config entry: ${Re} - ${Ie}.`)}),[we,$e]}catch(Ge){throw we!==0&&pe._OrtReleaseRunOptions(we),$e.forEach(Re=>pe._free(Re)),Ge}}}),Mo,Oo,ba,Li,ll,cl,Dn=d(()=>{rr(),lo(),Mo=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}`)}},Oo=oe=>{switch(oe){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${oe}`)}},ba=oe=>{oe.extra||(oe.extra={}),oe.extra.session||(oe.extra.session={});let pe=oe.extra.session;pe.use_ort_model_bytes_directly||(pe.use_ort_model_bytes_directly="1"),oe.executionProviders&&oe.executionProviders.some(we=>(typeof we=="string"?we:we.name)==="webgpu")&&(oe.enableMemPattern=!1)},Li=(oe,pe,we,$e)=>{let Ee=Zn(pe,$e),Ge=Zn(we,$e);Gt()._OrtAddSessionConfigEntry(oe,Ee,Ge)!==0&&jt(`Can't set a session config entry: ${pe} - ${we}.`)},ll=async(oe,pe,we)=>{let $e=pe.executionProviders;for(let Ee of $e){let Ge=typeof Ee=="string"?Ee:Ee.name,Re=[];switch(Ge){case"webnn":if(Ge="WEBNN",Li(oe,"session.disable_quant_qdq","1",we),Li(oe,"session.disable_qdq_constant_folding","1",we),typeof Ee!="string"){let rt=Ee==null?void 0:Ee.deviceType;rt&&Li(oe,"deviceType",rt,we)}break;case"webgpu":if(Ge="JS",typeof Ee!="string"){let rt=Ee;if(rt!=null&&rt.preferredLayout){if(rt.preferredLayout!=="NCHW"&&rt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${rt.preferredLayout}`);Li(oe,"preferredLayout",rt.preferredLayout,we)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Ge}`)}let Ie=Zn(Ge,we),He=Re.length,it=0,lt=0;if(He>0){it=Gt()._malloc(He*Gt().PTR_SIZE),we.push(it),lt=Gt()._malloc(He*Gt().PTR_SIZE),we.push(lt);for(let rt=0;rt<He;rt++)Gt().setValue(it+rt*Gt().PTR_SIZE,Re[rt][0],"*"),Gt().setValue(lt+rt*Gt().PTR_SIZE,Re[rt][1],"*")}await Gt()._OrtAppendExecutionProvider(oe,Ie,it,lt,He)!==0&&jt(`Can't append execution provider: ${Ge}.`)}},cl=async oe=>{let pe=Gt(),we=0,$e=[],Ee=oe||{};ba(Ee);try{let Ge=Mo(Ee.graphOptimizationLevel??"all"),Re=Oo(Ee.executionMode??"sequential"),Ie=typeof Ee.logId=="string"?Zn(Ee.logId,$e):0,He=Ee.logSeverityLevel??2;if(!Number.isInteger(He)||He<0||He>4)throw new Error(`log severity level is not valid: ${He}`);let it=Ee.logVerbosityLevel??0;if(!Number.isInteger(it)||it<0||it>4)throw new Error(`log verbosity level is not valid: ${it}`);let lt=typeof Ee.optimizedModelFilePath=="string"?Zn(Ee.optimizedModelFilePath,$e):0;if(we=pe._OrtCreateSessionOptions(Ge,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,Re,!!Ee.enableProfiling,0,Ie,He,it,lt),we===0&&jt("Can't create session options."),Ee.executionProviders&&await ll(we,Ee,$e),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(),$e)}if(Ee.freeDimensionOverrides)for(let[rt,Je]of Object.entries(Ee.freeDimensionOverrides)){if(typeof rt!="string")throw new Error(`free dimension override name must be a string: ${rt}`);if(typeof Je!="number"||!Number.isInteger(Je)||Je<0)throw new Error(`free dimension override value must be a non-negative integer: ${Je}`);let Pt=Zn(rt,$e);pe._OrtAddFreeDimensionOverride(we,Pt,Je)!==0&&jt(`Can't set a free dimension override: ${rt} - ${Je}.`)}return Ee.extra!==void 0&&Nn(Ee.extra,"",new WeakSet,(rt,Je)=>{Li(we,rt,Je,$e)}),[we,$e]}catch(Ge){throw we!==0&&pe._OrtReleaseSessionOptions(we)!==0&&jt("Can't release session options."),$e.forEach(Re=>pe._free(Re)),Ge}}}),Ki,ti,Yi,ys,co,Gs,kr,Ni,Ht=d(()=>{Ki=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}`)}},ti=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}`)}},Yi=(oe,pe)=>{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],$e=typeof pe=="number"?pe:pe.reduce((Ee,Ge)=>Ee*Ge,1);return we>0?Math.ceil($e*we):void 0},ys=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}`)}},co=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}`)}},Gs=oe=>oe==="float32"||oe==="float16"||oe==="int32"||oe==="int64"||oe==="uint32"||oe==="uint8"||oe==="bool"||oe==="uint4"||oe==="int4",kr=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}`)}}}),ni,Hs=d(()=>{Wi(),ni=async oe=>{if(typeof oe=="string"){let pe=await fetch(oe);if(!pe.ok)throw new Error(`failed to load external data file: ${oe}`);let we=pe.headers.get("Content-Length"),$e=we?parseInt(we,10):0;if($e<1073741824)return new Uint8Array(await pe.arrayBuffer());{if(!pe.body)throw new Error(`failed to load external data file: ${oe}, no response body.`);let Ee=pe.body.getReader(),Ge;try{Ge=new ArrayBuffer($e)}catch(Ie){if(Ie instanceof RangeError){let He=Math.ceil($e/65536);Ge=new WebAssembly.Memory({initial:He,maximum:He}).buffer}else throw Ie}let Re=0;for(;;){let{done:Ie,value:He}=await Ee.read();if(Ie)break;let it=He.byteLength;new Uint8Array(Ge,Re,it).set(He),Re+=it}return new Uint8Array(Ge,0,$e)}}else return oe instanceof Blob?new Uint8Array(await oe.arrayBuffer()):oe instanceof Uint8Array?oe:new Uint8Array(oe)}}),Cr,ya,Us,sr,es,Ws,cn,Er,uo,Ur,Xe,or,gt,_e=d(()=>{xn(),al(),Dn(),Ht(),rr(),lo(),Hs(),Cr=(oe,pe)=>{Gt()._OrtInit(oe,pe)!==0&&jt("Can't initialize onnxruntime.")},ya=async oe=>{Cr(oe.wasm.numThreads,co(oe.logLevel))},Us=async(oe,pe)=>{var $e,Ee;(Ee=($e=Gt()).asyncInit)==null||Ee.call($e);let we=oe.webgpu.adapter;if(pe==="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 Ge=oe.webgpu.powerPreference;if(Ge!==void 0&&Ge!=="low-power"&&Ge!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Ge}"`);let Re=oe.webgpu.forceFallbackAdapter;if(Re!==void 0&&typeof Re!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Re}"`);if(we=await navigator.gpu.requestAdapter({powerPreference:Ge,forceFallbackAdapter:Re}),!we)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(pe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},sr=new Map,es=oe=>{let pe=Gt(),we=pe.stackSave();try{let $e=pe.PTR_SIZE,Ee=pe.stackAlloc(2*$e);pe._OrtGetInputOutputCount(oe,Ee,Ee+$e)!==0&&jt("Can't get session input/output count.");let Ge=$e===4?"i32":"i64";return[Number(pe.getValue(Ee,Ge)),Number(pe.getValue(Ee+$e,Ge))]}finally{pe.stackRestore(we)}},Ws=(oe,pe)=>{let we=Gt(),$e=we.stackSave(),Ee=0;try{let Ge=we.PTR_SIZE,Re=we.stackAlloc(2*Ge);we._OrtGetInputOutputMetadata(oe,pe,Re,Re+Ge)!==0&&jt("Can't get session input/output metadata.");let Ie=Number(we.getValue(Re,"*"));Ee=Number(we.getValue(Re+Ge,"*"));let He=we.HEAP32[Ee/4];if(He===0)return[Ie,0];let it=we.HEAPU32[Ee/4+1],lt=[];for(let rt=0;rt<it;rt++){let Je=Number(we.getValue(Ee+8+rt*Ge,"*"));lt.push(Je!==0?we.UTF8ToString(Je):Number(we.getValue(Ee+8+(rt+it)*Ge,"*")))}return[Ie,He,lt]}finally{we.stackRestore($e),Ee!==0&&we._OrtFree(Ee)}},cn=oe=>{let pe=Gt(),we=pe._malloc(oe.byteLength);if(we===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${oe.byteLength}.`);return pe.HEAPU8.set(oe,we),[we,oe.byteLength]},Er=async(oe,pe)=>{var lt,rt,Je;let we,$e,Ee=Gt();Array.isArray(oe)?[we,$e]=oe:oe.buffer===Ee.HEAPU8.buffer?[we,$e]=[oe.byteOffset,oe.byteLength]:[we,$e]=cn(oe);let Ge=0,Re=0,Ie=[],He=[],it=[];try{if([Re,Ie]=await cl(pe),(pe==null?void 0:pe.externalData)&&Ee.mountExternalData){let Fn=[];for(let fn of pe.externalData){let Di=typeof fn=="string"?fn:fn.path;Fn.push(ni(typeof fn=="string"?fn:fn.data).then(Xi=>{Ee.mountExternalData(Di,Xi)}))}await Promise.all(Fn)}for(let Fn of(pe==null?void 0:pe.executionProviders)??[])if((typeof Fn=="string"?Fn:Fn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Fn!="string"){let fn=Fn,Di=fn==null?void 0:fn.context,Xi=fn==null?void 0:fn.gpuDevice,ar=fn==null?void 0:fn.deviceType,ul=fn==null?void 0:fn.powerPreference;Di?Ee.currentContext=Di:Xi?Ee.currentContext=await Ee.webnnCreateMLContext(Xi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:ar,powerPreference:ul})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}Ge=await Ee._OrtCreateSession(we,$e,Re),(lt=Ee.webgpuOnCreateSession)==null||lt.call(Ee,Ge),Ge===0&&jt("Can't create a session."),(rt=Ee.jsepOnCreateSession)==null||rt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(Ge,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[Pt,Fe]=es(Ge),ht=!!(pe!=null&&pe.enableGraphCapture),Rn=[],tn=[],nn=[],In=[],Bt=[];for(let Fn=0;Fn<Pt;Fn++){let[fn,Di,Xi]=Ws(Ge,Fn);fn===0&&jt("Can't get an input name."),He.push(fn);let ar=Ee.UTF8ToString(fn);Rn.push(ar),nn.push(Di===0?{name:ar,isTensor:!1}:{name:ar,isTensor:!0,type:ti(Di),shape:Xi})}for(let Fn=0;Fn<Fe;Fn++){let[fn,Di,Xi]=Ws(Ge,Fn+Pt);fn===0&&jt("Can't get an output name."),it.push(fn);let ar=Ee.UTF8ToString(fn);tn.push(ar),In.push(Di===0?{name:ar,isTensor:!1}:{name:ar,isTensor:!0,type:ti(Di),shape:Xi})}return sr.set(Ge,[Ge,He,it,null,ht,!1]),[Ge,Rn,tn,nn,In]}catch(Pt){throw He.forEach(Fe=>Ee._OrtFree(Fe)),it.forEach(Fe=>Ee._OrtFree(Fe)),Ge!==0&&Ee._OrtReleaseSession(Ge)!==0&&jt("Can't release session."),Pt}finally{Ee._free(we),Re!==0&&Ee._OrtReleaseSessionOptions(Re)!==0&&jt("Can't release session options."),Ie.forEach(Pt=>Ee._free(Pt)),(Je=Ee.unmountExternalData)==null||Je.call(Ee)}},uo=oe=>{var He,it,lt;let pe=Gt(),we=sr.get(oe);if(!we)throw new Error(`cannot release session. invalid session id: ${oe}`);let[$e,Ee,Ge,Re,Ie]=we;Re&&(Ie&&pe._OrtClearBoundOutputs(Re.handle)!==0&&jt("Can't clear bound outputs."),pe._OrtReleaseBinding(Re.handle)!==0&&jt("Can't release IO binding.")),(He=pe.jsepOnReleaseSession)==null||He.call(pe,oe),(it=pe.webnnOnReleaseSession)==null||it.call(pe,oe),(lt=pe.webgpuOnReleaseSession)==null||lt.call(pe,oe),Ee.forEach(rt=>pe._OrtFree(rt)),Ge.forEach(rt=>pe._OrtFree(rt)),pe._OrtReleaseSession($e)!==0&&jt("Can't release session."),sr.delete(oe)},Ur=async(oe,pe,we,$e,Ee,Ge,Re=!1)=>{if(!oe){pe.push(0);return}let Ie=Gt(),He=Ie.PTR_SIZE,it=oe[0],lt=oe[1],rt=oe[3],Je=rt,Pt,Fe;if(it==="string"&&(rt==="gpu-buffer"||rt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Re&&rt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Ge} when enableGraphCapture is true.`);if(rt==="gpu-buffer"){let tn=oe[2].gpuBuffer;Fe=Yi(Ki(it),lt);{let nn=Ie.jsepRegisterBuffer;if(!nn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Pt=nn($e,Ge,tn,Fe)}}else if(rt==="ml-tensor"){let tn=oe[2].mlTensor;Fe=Yi(Ki(it),lt);let nn=Ie.webnnRegisterMLTensor;if(!nn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Pt=nn($e,tn,Ki(it),lt)}else{let tn=oe[2];if(Array.isArray(tn)){Fe=He*tn.length,Pt=Ie._malloc(Fe),we.push(Pt);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`);Ie.setValue(Pt+nn*He,Zn(tn[nn],we),"*")}}else{let nn=Ie.webnnIsGraphInput,In=Ie.webnnIsGraphOutput;if(it!=="string"&&nn&&In){let Bt=Ie.UTF8ToString(Ee);if(nn($e,Bt)||In($e,Bt)){let Fn=Ki(it);Fe=Yi(Fn,lt),Je="ml-tensor";let fn=Ie.webnnCreateTemporaryTensor,Di=Ie.webnnUploadTensor;if(!fn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Xi=await fn($e,Fn,lt);Di(Xi,new Uint8Array(tn.buffer,tn.byteOffset,tn.byteLength)),Pt=Xi}else Fe=tn.byteLength,Pt=Ie._malloc(Fe),we.push(Pt),Ie.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,Fe),Pt)}else Fe=tn.byteLength,Pt=Ie._malloc(Fe),we.push(Pt),Ie.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,Fe),Pt)}}let ht=Ie.stackSave(),Rn=Ie.stackAlloc(4*lt.length);try{lt.forEach((nn,In)=>Ie.setValue(Rn+In*He,nn,He===4?"i32":"i64"));let tn=Ie._OrtCreateTensor(Ki(it),Pt,Fe,Rn,lt.length,Ni(Je));tn===0&&jt(`Can't create tensor for input/output. session=${$e}, index=${Ge}.`),pe.push(tn)}finally{Ie.stackRestore(ht)}},Xe=async(oe,pe,we,$e,Ee,Ge)=>{var lr,lc,bd;let Re=Gt(),Ie=Re.PTR_SIZE,He=sr.get(oe);if(!He)throw new Error(`cannot run inference. invalid session id: ${oe}`);let it=He[0],lt=He[1],rt=He[2],Je=He[3],Pt=He[4];He[5];let Fe=pe.length,ht=$e.length,Rn=0,tn=[],nn=[],In=[],Bt=[],Fn=[],fn=Re.stackSave(),Di=Re.stackAlloc(Fe*Ie),Xi=Re.stackAlloc(Fe*Ie),ar=Re.stackAlloc(ht*Ie),ul=Re.stackAlloc(ht*Ie);try{[Rn,tn]=Io(Ge),nt("wasm prepareInputOutputTensor");for(let un=0;un<Fe;un++)await Ur(we[un],nn,Bt,oe,lt[pe[un]],pe[un],Pt);for(let un=0;un<ht;un++)await Ur(Ee[un],In,Bt,oe,rt[$e[un]],Fe+$e[un],Pt);at("wasm prepareInputOutputTensor");for(let un=0;un<Fe;un++)Re.setValue(Di+un*Ie,nn[un],"*"),Re.setValue(Xi+un*Ie,lt[pe[un]],"*");for(let un=0;un<ht;un++)Re.setValue(ar+un*Ie,In[un],"*"),Re.setValue(ul+un*Ie,rt[$e[un]],"*");(lr=Re.jsepOnRunStart)==null||lr.call(Re,it),(lc=Re.webnnOnRunStart)==null||lc.call(Re,it);let Ai;Ai=await Re._OrtRun(it,Xi,Di,Fe,ul,ht,ar,Rn),Ai!==0&&jt("failed to call OrtRun().");let _s=[],yd=[];nt("wasm ProcessOutputTensor");for(let un=0;un<ht;un++){let ns=Number(Re.getValue(ar+un*Ie,"*"));if(ns===In[un]||Fn.includes(In[un])){_s.push(Ee[un]),ns!==In[un]&&Re._OrtReleaseTensor(ns)!==0&&jt("Can't release tensor.");continue}let Fu=Re.stackSave(),Ks=Re.stackAlloc(4*Ie),wa=!1,xi,cr=0;try{Re._OrtGetTensorData(ns,Ks,Ks+Ie,Ks+2*Ie,Ks+3*Ie)!==0&&jt(`Can't access output tensor data on index ${un}.`);let cc=Ie===4?"i32":"i64",dr=Number(Re.getValue(Ks,cc));cr=Re.getValue(Ks+Ie,"*");let wd=Re.getValue(Ks+Ie*2,"*"),Gu=Number(Re.getValue(Ks+Ie*3,cc)),Ys=[];for(let bi=0;bi<Gu;bi++)Ys.push(Number(Re.getValue(wd+bi*Ie,cc)));Re._OrtFree(wd)!==0&&jt("Can't free memory for tensor dims.");let is=Ys.reduce((bi,Qn)=>bi*Qn,1);xi=ti(dr);let Ss=Je==null?void 0:Je.outputPreferredLocations[$e[un]];if(xi==="string"){if(Ss==="gpu-buffer"||Ss==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let bi=[];for(let Qn=0;Qn<is;Qn++){let rs=Re.getValue(cr+Qn*Ie,"*"),_d=Re.getValue(cr+(Qn+1)*Ie,"*"),Sd=Qn===is-1?void 0:_d-rs;bi.push(Re.UTF8ToString(rs,Sd))}_s.push([xi,Ys,bi,"cpu"])}else if(Ss==="gpu-buffer"&&is>0){let bi=Re.jsepGetBuffer;if(!bi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Qn=bi(cr),rs=Yi(dr,is);if(rs===void 0||!Gs(xi))throw new Error(`Unsupported data type: ${xi}`);wa=!0,_s.push([xi,Ys,{gpuBuffer:Qn,download:Re.jsepCreateDownloader(Qn,rs,xi),dispose:()=>{Re._OrtReleaseTensor(ns)!==0&&jt("Can't release tensor.")}},"gpu-buffer"])}else if(Ss==="ml-tensor"&&is>0){let bi=Re.webnnEnsureTensor,Qn=Re.webnnIsGraphInputOutputTypeSupported;if(!bi||!Qn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Yi(dr,is)===void 0||!kr(xi))throw new Error(`Unsupported data type: ${xi}`);if(!Qn(oe,xi,!1))throw new Error(`preferredLocation "ml-tensor" for ${xi} output is not supported by current WebNN Context.`);let rs=await bi(oe,cr,dr,Ys,!1);wa=!0,_s.push([xi,Ys,{mlTensor:rs,download:Re.webnnCreateMLTensorDownloader(cr,xi),dispose:()=>{Re.webnnReleaseTensorId(cr),Re._OrtReleaseTensor(ns)}},"ml-tensor"])}else if(Ss==="ml-tensor-cpu-output"&&is>0){let bi=Re.webnnCreateMLTensorDownloader(cr,xi)(),Qn=_s.length;wa=!0,yd.push((async()=>{let rs=[Qn,await bi];return Re.webnnReleaseTensorId(cr),Re._OrtReleaseTensor(ns),rs})()),_s.push([xi,Ys,[],"cpu"])}else{let bi=ys(xi),Qn=new bi(is);new Uint8Array(Qn.buffer,Qn.byteOffset,Qn.byteLength).set(Re.HEAPU8.subarray(cr,cr+Qn.byteLength)),_s.push([xi,Ys,Qn,"cpu"])}}finally{Re.stackRestore(Fu),xi==="string"&&cr&&Re._free(cr),wa||Re._OrtReleaseTensor(ns)}}Je&&!Pt&&(Re._OrtClearBoundOutputs(Je.handle)!==0&&jt("Can't clear bound outputs."),sr.set(oe,[it,lt,rt,Je,Pt,!1]));for(let[un,ns]of await Promise.all(yd))_s[un][2]=ns;return at("wasm ProcessOutputTensor"),_s}finally{(bd=Re.webnnOnRunEnd)==null||bd.call(Re,it),Re.stackRestore(fn),nn.forEach(Ai=>Re._OrtReleaseTensor(Ai)),In.forEach(Ai=>Re._OrtReleaseTensor(Ai)),Bt.forEach(Ai=>Re._free(Ai)),Rn!==0&&Re._OrtReleaseRunOptions(Rn),tn.forEach(Ai=>Re._free(Ai))}},or=oe=>{let pe=Gt(),we=sr.get(oe);if(!we)throw new Error("invalid session id");let $e=we[0],Ee=pe._OrtEndProfiling($e);Ee===0&&jt("Can't get an profile file name."),pe._OrtFree(Ee)},gt=oe=>{let pe=[];for(let we of oe){let $e=we[2];!Array.isArray($e)&&"buffer"in $e&&pe.push($e.buffer)}return pe}}),Le,Qe,Dt,on,dn,zn,Mn,pi,Wn,vi,On,ts,ho,Lo,ws,Bu,zo,Bo,gd=d(()=>{xn(),_e(),rr(),ir(),Le=()=>!!M.wasm.proxy&&typeof document<"u",Dt=!1,on=!1,dn=!1,pi=new Map,Wn=(oe,pe)=>{let we=pi.get(oe);we?we.push(pe):pi.set(oe,[pe])},vi=()=>{if(Dt||!on||dn||!Qe)throw new Error("worker not ready")},On=oe=>{switch(oe.data.type){case"init-wasm":Dt=!1,oe.data.err?(dn=!0,Mn[1](oe.data.err)):(on=!0,Mn[0]()),zn&&(URL.revokeObjectURL(zn),zn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let pe=pi.get(oe.data.type);oe.data.err?pe.shift()[1](oe.data.err):pe.shift()[0](oe.data.out);break}}},ts=async()=>{if(!on){if(Dt)throw new Error("multiple calls to 'initWasm()' detected.");if(dn)throw new Error("previous call to 'initWasm()' failed.");if(Dt=!0,Le())return new Promise((oe,pe)=>{Qe==null||Qe.terminate(),Fs().then(([we,$e])=>{try{Qe=$e,Qe.onerror=Ge=>pe(Ge),Qe.onmessage=On,Mn=[oe,pe];let Ee={type:"init-wasm",in:M};if(!Ee.in.wasm.wasmPaths&&we){let Ge=nr();Ge&&(Ee.in.wasm.wasmPaths=Ge)}Qe.postMessage(Ee),zn=we}catch(Ee){pe(Ee)}},pe)});try{await bs(M.wasm),await ya(M),on=!0}catch(oe){throw dn=!0,oe}finally{Dt=!1}}},ho=async oe=>{if(Le())return vi(),new Promise((pe,we)=>{Wn("init-ep",[pe,we]);let $e={type:"init-ep",in:{epName:oe,env:M}};Qe.postMessage($e)});await Us(M,oe)},Lo=async oe=>Le()?(vi(),new Promise((pe,we)=>{Wn("copy-from",[pe,we]);let $e={type:"copy-from",in:{buffer:oe}};Qe.postMessage($e,[oe.buffer])})):cn(oe),ws=async(oe,pe)=>{if(Le()){if(pe!=null&&pe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return vi(),new Promise((we,$e)=>{Wn("create",[we,$e]);let Ee={type:"create",in:{model:oe,options:{...pe}}},Ge=[];oe instanceof Uint8Array&&Ge.push(oe.buffer),Qe.postMessage(Ee,Ge)})}else return Er(oe,pe)},Bu=async oe=>{if(Le())return vi(),new Promise((pe,we)=>{Wn("release",[pe,we]);let $e={type:"release",in:oe};Qe.postMessage($e)});uo(oe)},zo=async(oe,pe,we,$e,Ee,Ge)=>{if(Le()){if(we.some(Re=>Re[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some(Re=>Re))throw new Error("pre-allocated output tensor is not supported for proxy.");return vi(),new Promise((Re,Ie)=>{Wn("run",[Re,Ie]);let He=we,it={type:"run",in:{sessionId:oe,inputIndices:pe,inputs:He,outputIndices:$e,options:Ge}};Qe.postMessage(it,gt(He))})}else return Xe(oe,pe,we,$e,Ee,Ge)},Bo=async oe=>{if(Le())return vi(),new Promise((pe,we)=>{Wn("end-profiling",[pe,we]);let $e={type:"end-profiling",in:oe};Qe.postMessage($e)});or(oe)}}),rc,Fo,dl,sc=d(()=>{xn(),gd(),Ht(),Wi(),Hs(),rc=(oe,pe)=>{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 ${pe()}`)}},Fo=oe=>{switch(oe[3]){case"cpu":return new ge(oe[0],oe[2],oe[1]);case"gpu-buffer":{let pe=oe[0];if(!Gs(pe))throw new Error(`not supported data type: ${pe} for deserializing GPU tensor`);let{gpuBuffer:we,download:$e,dispose:Ee}=oe[2];return ge.fromGpuBuffer(we,{dataType:pe,dims:oe[1],download:$e,dispose:Ee})}case"ml-tensor":{let pe=oe[0];if(!kr(pe))throw new Error(`not supported data type: ${pe} for deserializing MLTensor tensor`);let{mlTensor:we,download:$e,dispose:Ee}=oe[2];return ge.fromMLTensor(we,{dataType:pe,dims:oe[1],download:$e,dispose:Ee})}default:throw new Error(`invalid data location: ${oe[3]}`)}},dl=class{async fetchModelAndCopyToWasmMemory(oe){return Lo(await ni(oe))}async loadModel(oe,pe){pt();let we;typeof oe=="string"?we=await this.fetchModelAndCopyToWasmMemory(oe):we=oe,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ws(we,pe),ot()}async dispose(){return Bu(this.sessionId)}async run(oe,pe,we){pt();let $e=[],Ee=[];Object.entries(oe).forEach(rt=>{let Je=rt[0],Pt=rt[1],Fe=this.inputNames.indexOf(Je);if(Fe===-1)throw new Error(`invalid input '${Je}'`);$e.push(Pt),Ee.push(Fe)});let Ge=[],Re=[];Object.entries(pe).forEach(rt=>{let Je=rt[0],Pt=rt[1],Fe=this.outputNames.indexOf(Je);if(Fe===-1)throw new Error(`invalid output '${Je}'`);Ge.push(Pt),Re.push(Fe)});let Ie=$e.map((rt,Je)=>rc(rt,()=>`input "${this.inputNames[Ee[Je]]}"`)),He=Ge.map((rt,Je)=>rt?rc(rt,()=>`output "${this.outputNames[Re[Je]]}"`):null),it=await zo(this.sessionId,Ee,Ie,Re,He,we),lt={};for(let rt=0;rt<it.length;rt++)lt[this.outputNames[Re[rt]]]=Ge[rt]??Fo(it[rt]);return ot(),lt}startProfiling(){}endProfiling(){Bo(this.sessionId)}}}),Vs={};p(Vs,{OnnxruntimeWebAssemblyBackend:()=>qs,initializeFlags:()=>po,wasmBackend:()=>Go});var po,qs,Go,vd=d(()=>{xn(),gd(),sc(),po=()=>{(typeof M.wasm.initTimeout!="number"||M.wasm.initTimeout<0)&&(M.wasm.initTimeout=0);let oe=M.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.`),M.wasm.simd=!1),typeof M.wasm.proxy!="boolean"&&(M.wasm.proxy=!1),typeof M.wasm.trace!="boolean"&&(M.wasm.trace=!1),typeof M.wasm.numThreads!="number"||!Number.isInteger(M.wasm.numThreads)||M.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)M.wasm.numThreads=1;else{let pe=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;M.wasm.numThreads=Math.min(4,Math.ceil((pe||1)/2))}},qs=class{async init(oe){po(),await ts(),await ho(oe)}async createInferenceSessionHandler(oe,pe){let we=new dl;return await we.loadModel(oe,pe),we}},Go=new qs}),xd={};p(xd,{InferenceSession:()=>Ze,TRACE:()=>ye,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>at,TRACE_FUNC_BEGIN:()=>pt,TRACE_FUNC_END:()=>ot,Tensor:()=>ge,default:()=>ac,env:()=>M,registerBackend:()=>w}),xn(),xn(),xn();var oc="1.26.0",ac=wr;{let oe=(vd(),f(Vs)).wasmBackend;w("cpu",oe,10),w("wasm",oe,10)}return Object.defineProperty(M.versions,"web",{value:oc,enumerable:!0}),f(xd)})();n.exports=i})(Tw)),Tw.exports}var Mk;function rR(){return Mk||(Mk=1,(function(n){var e=Rl&&Rl.__createBinding||(Object.create?(function(E,T,N,$){$===void 0&&($=N);var R=Object.getOwnPropertyDescriptor(T,N);(!R||("get"in R?!T.__esModule:R.writable||R.configurable))&&(R={enumerable:!0,get:function(){return T[N]}}),Object.defineProperty(E,$,R)}):(function(E,T,N,$){$===void 0&&($=N),E[$]=T[N]})),i=Rl&&Rl.__setModuleDefault||(Object.create?(function(E,T){Object.defineProperty(E,"default",{enumerable:!0,value:T})}):function(E,T){E.default=T}),r=Rl&&Rl.__importStar||function(E){if(E&&E.__esModule)return E;var T={};if(E!=null)for(var N in E)N!=="default"&&Object.prototype.hasOwnProperty.call(E,N)&&e(T,E,N);return i(T,E),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(iR()),a=f1(),c=m1(),l=fv(),d=Ly(),p=cT(),m=dT();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",x="silero_vad_v5.onnx",y="silero_vad_legacy.onnx",w=E=>({...c.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:E,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=w;const k=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(E,T,N,$,R){await N.audioWorklet.addModule(E),T.processorOptions={...T.processorOptions??{},frameSamples:$};const M=new AudioWorkletNode(N,"vad-helper-worklet",T);return M.port.onmessage=async z=>{const V=z.data;if(!(typeof V=="object"&&V&&"message"in V)){console.error("Invalid message event",V);return}switch(V.message){case d.Message.AudioFrame:{if(!("data"in V&&V.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const H=new Float32Array(V.data);await R(H);break}}},M}async function _(E,T,N){const $=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const M=E.createScriptProcessor(4096,1,1);let z=!1;return M.onaudioprocess=async V=>{if(!z){z=!0;try{const H=V.inputBuffer.getChannelData(0);V.outputBuffer.getChannelData(0).fill(0);const X=$.process(H);for(const q of X)await N(q)}catch(H){console.error("Error processing audio:",H)}finally{z=!1}}},M.connect(E.destination),M}class S{constructor(T,N,$,R,M=!1,z=null,V=null,H=null,Q=null,X=null,q=null,J="uninitialized",ee=!1){this.options=T,this.frameProcessor=N,this.model=$,this.frameSamples=R,this.listening=M,this.errored=z,this._stream=V,this._audioContext=H,this._vadNode=Q,this._mediaStreamAudioSourceNode=X,this._audioProcessorAdapterType=q,this.initializationState=J,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=ie=>{this.initializationState="errored",this.errored=ie},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(ie){throw ie instanceof Error?this.setErrored(ie.message):this.setErrored(String(ie)),ie}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 b(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await _(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:ie,audioContext:re,vadNode:B}=this.getAudioInstances();this._stream=await this.options.resumeStream(ie);const Z=new MediaStreamAudioSourceNode(re,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Z,Z.connect(B);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:ie,mediaStreamAudioSourceNode:re}=this.getAudioInstances();await this.options.pauseStream(ie),re.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var re;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:ie}=this.getAudioInstances();ie instanceof AudioWorkletNode&&ie.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((re=this._audioContext)==null?void 0:re.close())},this.setOptions=ie=>{this.frameProcessor.setOptions(ie)},this.processFrame=async ie=>{await this.frameProcessor.process(ie,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=ie=>{switch(ie.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(ie.probs,ie.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(ie.audio);break}}}static async new(T={}){const N={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,c.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const $=N.model==="v5"?x:y,R=N.baseAssetPath+$,M=N.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let z;try{z=await M(n.ort,()=>(0,a.defaultModelFetcher)(R))}catch(q){throw console.error(`Encountered an error while loading model file ${R}`),q}const V=N.model==="v5"?512:1536,H=V/16,Q=new c.FrameProcessor(z.process,z.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},H),X=new S(N,Q,z,V);if(N.startOnLoad)try{await X.start()}catch(q){throw console.error("Error starting micVad",q),q}return X}}n.MicVAD=S})(Rl)),Rl}var Ok;function sR(){return Ok||(Ok=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=oT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=f1();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=m1();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=Ly();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=tR();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const c=nR();n.utils={audioFileToArray:c.audioFileToArray,minFramesForTargetMS:c.minFramesForTargetMS,arrayBufferToBase64:c.arrayBufferToBase64,encodeWAV:c.encodeWAV};var l=rR();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}})})(Cw)),Cw}var oR=sR();function Tx(n,e,i,r,s){var c,l;try{(l=(c=window.api)==null?void 0:c.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 mt={debug:(n,e,i)=>Tx(n,"debug",e,i),info:(n,e,i)=>Tx(n,"info",e,i),warn:(n,e,i)=>Tx(n,"warn",e,i),error:(n,e,i,r)=>Tx(n,"error",e,i,r)},hT=16e3,aR=6,wp=hT*aR,lR=400,cR=hT*lR/1e3,Lk=300,zk=2e3,Bk=1500,Fk=3e3,dR=600,pT=.5,fT=.35,Gk=.85,Hk=.7;let Rs=null,Qa=!1,ps=!1;const B_=new Set;function Nx(n){for(const e of Array.from(B_))try{e(n)}catch(i){mt.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let Nw=0;const Uk=2;let Lp=!1,mT=!1;function gT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";mt[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{mt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),uR(`error:${e.message||"unknown"}`)})}function Xb(){return Rs||(Rs=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),gT(Rs),mt.info("speech","worker spawned"),Rs)}let Dx=!1;function uR(n){if(!Lp){if(Dx){mt.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(Dx=!0,Nw+=1,mT=!0,mt.warn("speech","respawnWorker: starting",{reason:n,attempt:Nw}),Nx({reason:n,respawned:!1,finalOnly:!0}),Nw>Uk){if(Lp=!0,mt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Uk}),Rs)try{Rs.terminate()}catch{}Rs=null,Qa=!1,ps=!1,Nx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),Dx=!1;return}if(Rs)try{Rs.terminate()}catch{}Rs=null,Qa=!1,ps=!1;try{Rs=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),gT(Rs),ps=!0,Rs.postMessage({type:"load"}),mt.info("speech","respawnWorker: new worker spawned, load posted"),Nx({reason:n,respawned:!0,finalOnly:!0})}catch(e){Lp=!0,mt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),Nx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{Dx=!1}}}function hR(n,e){if(Qa||ps)return;ps=!0;const i=Xb();mt.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"&&(Qa=!0,ps=!1,mt.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(ps=!1,mt.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 pR(){mt.info("speech","resetModel: clearing load flags"),Qa=!1,ps=!1}function zy(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function fR(n){const e=Xb();return!Qa&&!ps&&(ps=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var c,l,d;((c=a.data)==null?void 0:c.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")))):((d=a.data)==null?void 0:d.type)==="status"&&a.data.status==="ready"&&(Qa=!0,ps=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function vT(n){let e=Xb(),i=!1,r=null,s=null,a=null,c=null,l=null;const d=[],p=new Set;let m=null,f=0,x=!1,y=0,w=!1,k=!1,b=0,_=0,S=0,E=-1,T=Lk,N=0,$=null,R="",M="",z=!1,V=0;function H(ae,fe){const Te=Math.min(ae.length,fe.length);let Ne=0;for(;Ne<Te&&ae.charCodeAt(Ne)===fe.charCodeAt(Ne);)Ne++;return Ne}function Q(ae){const fe=H(R,ae);return R=ae,fe>M.length&&(M=ae.slice(0,fe)),M.length>ae.length&&(M=ae),M}const X=()=>(m||(m=new Float32Array(wp)),m),q=()=>{f=0},J=ae=>{const fe=X(),Te=ae.length;if(Te>=wp){fe.set(ae.subarray(Te-wp)),f=wp;return}if(f+Te<=wp){fe.set(ae,f),f+=Te;return}const Ne=f+Te-wp;fe.copyWithin(0,Ne,f),f-=Ne,fe.set(ae,f),f+=Te},ee=()=>{$&&(clearTimeout($),$=null)},ie=()=>{ee(),x=!1,w=!1,k=!1,T=Lk,R="",M="",z=!1,V=0,q()},re=()=>{if(i||!x||k||w||$)return;if(f<cR){$=setTimeout(()=>{$=null,re()},T);return}const ae=performance.now()-b;if(ae<T&&b!==0){$=setTimeout(()=>{$=null,re()},T-ae);return}if(mT||Lp||n.partialsEnabled&&!n.partialsEnabled())return;const fe=X(),Te=new Float32Array(f);Te.set(fe.subarray(0,f)),_+=1,S=_,w=!0,N=performance.now(),b=N,e.postMessage({type:"transcribe-partial",audio:Te,seq:_},[Te.buffer])},B=ae=>ae.length===0?Promise.resolve():Lp?(mt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(fe=>{d.push(fe),_+=1;const Te=_;E=Te,e.postMessage({type:"transcribe",audio:ae,seq:Te},[ae.buffer])}),Z=ae=>{const fe=B(ae);return p.add(fe),fe.finally(()=>{p.delete(fe)}),fe},W=ae=>{var fe,Te,Ne,me,se;if(ae.data.type==="result"){const Ae=ae.data.text,ge=ae.data.seq??0;ge&&ge<E&&mt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ge,latestFinalSeq:E}),!i&&Ae&&n.onFinal(Ae),(fe=d.shift())==null||fe()}else if(ae.data.type==="partial"){const Ae=ae.data.seq??0,ge=ae.data.text??"",Se=performance.now()-N;w=!1,Se>=Fk?(k=!0,mt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Se),seq:Ae})):Se>=Bk&&(T=Math.min(T*2,zk),mt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Se),newIntervalMs:T,seq:Ae})),z||(z=!0,Se>dR&&T<500&&(T=500,mt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Se),newIntervalMs:500})));const ye=Ae!==S||Ae<=E;if(!i&&!ye&&ge){const et=Q(ge);et&&((Te=n.onPartial)==null||Te.call(n,et),V===0&&(V=performance.now(),mt.info("speech","partial.first",{msSinceSpeechStart:Math.round(V-y)})))}re()}else if(ae.data.type==="partial-error"){const Ae=performance.now()-N;w=!1,Ae>=Fk?(k=!0,mt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ae),seq:ae.data.seq})):Ae>=Bk&&(T=Math.min(T*2,zk),mt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ae),newIntervalMs:T,seq:ae.data.seq})),mt.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),re()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(Ne=d.shift())==null||Ne()):ae.data.type==="status"?(i||(me=n.onModelStatus)==null||me.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(Qa=!0,ps=!1)):ae.data.type==="progress"&&(i||(se=n.onProgress)==null||se.call(n,ae.data.pct))};e.addEventListener("message",W);const le=ae=>{var fe,Te;if(!i){for(mt.warn("speech","createRecognition: worker death event",ae),(fe=n.onStatusChange)==null||fe.call(n,"restarting");d.length;)(Te=d.shift())==null||Te();if(p.clear(),ee(),w=!1,ae.respawned){try{e.removeEventListener("message",W)}catch{}e=Xb(),e.addEventListener("message",W)}}};return B_.add(le),{start:async()=>{if(!i){if(Lp){n.onError("Speech recognition disabled — please reload the app.");return}!Qa&&!ps&&(ps=!0,mt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),mt.info("speech","createRecognition.start: initializing VAD",{modelReady:Qa,modelLoading:ps});try{const ae=new URL("vad/",document.baseURI).href,fe=n.inputDeviceId||null,Te={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};fe&&(Te.deviceId={exact:fe}),mt.info("speech","getUserMedia",{hasDeviceId:!!fe,deviceIdPrefix:fe?fe.slice(0,8):null});const Ne=await navigator.mediaDevices.getUserMedia({audio:Te});s=Ne,a=new AudioContext;for(const me of Ne.getAudioTracks())me.addEventListener("ended",()=>{i||(mt.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),c=a.createAnalyser(),c.fftSize=2048,c.smoothingTimeConstant=.3,l.connect(c)}catch(me){mt.warn("speech","analyser init failed",{error:me instanceof Error?me.message:String(me)}),l=null,c=null}r=await oR.MicVAD.new({audioContext:a,getStream:async()=>Ne,resumeStream:async()=>Ne,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:pT,negativeSpeechThreshold:fT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(me,se)=>{var Ae;i||((Ae=n.onFrame)==null||Ae.call(n,me),x&&(J(se),re()))},onSpeechStart:()=>{var me;i||(ie(),x=!0,y=performance.now(),(me=n.onSpeechStart)==null||me.call(n))},onSpeechEnd:me=>{var se;i||((se=n.onStatusChange)==null||se.call(n,"transcribing"),ie(),Z(me))},onVADMisfire:()=>{var me,se;i||((me=n.onStatusChange)==null||me.call(n,"idle"),ie(),(se=n.onMisfire)==null||se.call(n))}}),r.start()}catch(ae){const fe=ae instanceof Error?ae.message:"Microphone access denied",Te=ae instanceof Error?ae.stack:"";if(mt.error("speech","createRecognition.start: VAD init failed",{error:fe,stack:Te}),c){try{c.disconnect()}catch{}c=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Ne=>Ne.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(fe)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(ie();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(c){try{c.disconnect()}catch{}c=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,fe)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:fe})}catch(Te){mt.warn("speech","setVadThresholds failed",{error:Te instanceof Error?Te.message:String(Te)})}},getAnalyser:()=>c,destroy:()=>{if(i=!0,ie(),r){try{r.destroy()}catch{}r=null}if(c){try{c.disconnect()}catch{}c=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}B_.delete(le),e.removeEventListener("message",W)}}}let Mg=null;const F_=new Set,G_=new Set;function mR(){for(const n of F_)try{n()}catch{}}function H_(){for(const n of G_)try{n()}catch{}}function gR(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 vR(n){if(!window.speechSynthesis)return;const e=gR(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{Mg=performance.now(),mR()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Mg=null,H_())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Mg=null,H_())},window.speechSynthesis.speak(i)}function xT(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Mg=null,H_())}function bT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function xR(){return Mg}function bR(n){return F_.add(n),()=>{F_.delete(n)}}function yR(n){return G_.add(n),()=>{G_.delete(n)}}function wR(n){bT()&&(n.setVadThresholds(Gk,Hk),mt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=bR(()=>{n.setVadThresholds(Gk,Hk),mt.info("voice","tts.duck.on")}),i=yR(()=>{n.setVadThresholds(pT,fT),mt.info("voice","tts.duck.off")});return()=>{e(),i()}}const _R=[{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 SR(n){const e=n.trim();return _R.find(i=>i.match.test(e))??null}const kR=4e4;let ku=null;function zp(){ku&&clearTimeout(ku),ku=setTimeout(()=>{ku=null,Ct.getState().stopRecording()},kR)}function Ax(){ku&&(clearTimeout(ku),ku=null)}let ad=null,td=null;const CR=.04,ER=.3;let Jb=0,U_=0;function jR(n){td!==null&&cancelAnimationFrame(td);const e=()=>{if(ad===null||Ct.getState().submitCountdownStartAt===null){td=null;return}const i=performance.now();if(i-U_<200&&Jb>ER){const s=i-n;mt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Jb.toFixed(2),msIntoCountdown:Math.round(s)}),Xc(),zp();return}const r=yT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const d=(s[l]-128)/128;a+=d*d}const c=Math.sqrt(a/s.length);if(c>CR){const l=i-n;mt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:c.toFixed(3),msIntoCountdown:Math.round(l)}),Xc(),zp();return}}td=requestAnimationFrame(e)};td=requestAnimationFrame(e)}function Wk(n){ad&&clearTimeout(ad);const e=Ct.getState().submitDelayMs,i=performance.now();Ct.setState({submitCountdownStartAt:i}),ad=setTimeout(()=>{var s;ad=null,Ct.setState({submitCountdownStartAt:null});const r=xt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=mn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(mn.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),mn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){mt.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}zp()},e),jR(i)}function Xc(){td!==null&&(cancelAnimationFrame(td),td=null),ad&&(clearTimeout(ad),ad=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let br=null,Kr=null,eg=null;function yT(){var n;return((n=br==null?void 0:br.getAnalyser)==null?void 0:n.call(br))??null}const $x=1e4;let Og=null;function Px(){Og&&(clearTimeout(Og),Og=null)}let Sb=null,kb=null;function Rx(){Sb=null,kb&&(kb(),kb=null)}const TR=1500,NR=9e4;let Ix=0,Cb=null,W_=-1;function Mx(){Cb&&(clearTimeout(Cb),Cb=null,W_=-1)}const DR=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=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;mt.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++Ix,r=()=>{i===Ix&&(Mx(),W_=i,Cb=setTimeout(()=>{W_===i&&e().modelStatus==="loading"&&(mt.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},NR))};r(),hR((s,a)=>{i===Ix&&(s==="ready"?(Mx(),mt.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Mx(),mt.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===Ix&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{mt.info("voice","mic.gate.retry"),Mx(),pR(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(br){mt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!zy()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const c=vT({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=>{Jb=l.isSpeech,U_=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),Ax(),Xc(),bT()){const d=xR(),p=d!==null?performance.now()-d:null;xT(),n({lastBargeInAt:performance.now()}),mt.info("voice","barge-in",{tabId:i,utteranceOffsetMs:p})}else mt.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),zp();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&mt.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var x;zp();const d=l.trim();if(!d||DR.has(d)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(eg){eg(d),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((x=xt.getState().tabs.find(y=>y.id===i))==null?void 0:x.status)==="dormant"){mn.getState().setPendingVoiceText(i,d),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Wk(i);const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:d}),y.__transcripts.length>500&&y.__transcripts.shift());return}const m=SR(d);if(m){mt.info("voice","voice-command",{tabId:i,label:m.label,transcript:d}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Xc();const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:d}),y.__transcripts.length>500&&y.__transcripts.shift());return}window.api.pty.write({tabId:i,data:d}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Wk(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:d}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{mt.error("voice","recognition error",{err:l}),Xc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Kr==null||Kr(),Kr=null,Ax(),br==null||br.destroy(),br=null,eg=null,Me.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)})});br=c,eg=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),zp(),c.start().then(()=>{br===c&&(Kr==null||Kr(),Kr=wR(c))}).catch(l=>{const d=l instanceof Error?l.message:String(l);mt.error("voice","handle.start() failed",{error:d}),Me.error(`Could not start mic: ${d}`)})}catch(c){n({error:c instanceof Error?c.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,c,l;return((l=(c=(a=window.api)==null?void 0:a.voice)==null?void 0:c.getDevicePref)==null?void 0:l.call(c))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{mt.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=br;i&&(Ax(),Xc(),Jb=0,U_=0,Kr==null||Kr(),Kr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),br===i&&(br=null,eg=null),e().hotkeyState==="stopping"&&(Px(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=br;if(!i)return;Ax(),Kr==null||Kr(),Kr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){mt.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),br===i&&(br=null);const{useSessions:r}=await pv(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>DP);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:()=>Xc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(mt.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"?mt.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?mt.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&mt.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 c=e(),{canRecord:l,reason:d}=Zb(c);if(i==="down"){if(d==="error"||d==="load-timeout"){c.resetAndRetryModel(),mt.info("voice-hotkey","down.retry",{source:r,reason:d});return}if(!l&&d!=="loading"){mt.warn("voice-hotkey","miss-model-loading",{modelStatus:c.modelStatus,reason:d});return}if(c.hotkeyState==="recording"||c.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),Px(),Og=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:$x}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},$x),c.stopRecording());return}if(d==="loading"){c.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),mt.info("voice-hotkey","armed",{source:r,modelStatus:c.modelStatus})),Rx(),Sb={tabId:a,source:r,mode:s},kb=Ct.subscribe((p,m)=>{if(Sb&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=Sb;if(Rx(),!f.tabId){mt.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}mt.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),Ct.getState().startRecording(f.tabId)}});return}if(!a){mt.warn("voice-hotkey","no-active-tab",{source:r});return}mt.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),c.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(mt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(c.hotkeyState==="armed"){Rx(),mt.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}c.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),Px(),Og=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:$x}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},$x),c.stopRecording())}},destroyHotkey:()=>{const i=e();if(Rx(),Xc(),i.hotkeyState==="recording"){mt.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(Px(),n({hotkeyState:"destroyed"}))}})),AR=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),Zb=n=>zy()?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=Ct,n.__transcripts=[]}const $R=6e4,PR=5e3,Lg=Ti(()=>({data:null,refreshing:!1}));let Vk=!1,Eb=null,qk=null,Kk=!1;async function g1(){Lg.setState({refreshing:!0});let n=$R;try{const e=await o1(window.api.billing.fetch(),PR,"billing.fetch");Lg.setState({data:e,refreshing:!1}),e.kind==="transient"?n=qk==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),qk=e.kind}catch(e){if(Lg.setState({refreshing:!1}),!Kk){Kk=!0;const i=e instanceof Error?e.message:String(e);Me.warn(`Billing usage fetch failed: ${i}`)}}Eb=setTimeout(g1,n)}function RR(){Vk||(Vk=!0,g1())}function wT(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 IR(){Eb!==null&&(clearTimeout(Eb),Eb=null),g1()}function sf(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 Ox=new Map,MR=3e4;function v1(n){const[e,i]=P.useState(()=>{var r;return n?((r=Ox.get(n))==null?void 0:r.value)??null:null});return P.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=Ox.get(n);if(a&&Date.now()-a.ts<MR){r||i(a.value);return}try{const c=await window.api.app.gitBranch(n);if(r)return;Ox.set(n,{value:c,ts:Date.now()}),i(c)}catch{if(r)return;Ox.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function OR(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 V_="sm.almanac.sidebarWidth",_T=180,ST=480,q_=252;function LR(){try{const n=parseInt(localStorage.getItem(V_)??"",10);if(Number.isFinite(n))return Math.min(ST,Math.max(_T,n))}catch{}return q_}const zR=52,kT="sm.almanac.sidebarCollapsed";function BR(){try{return localStorage.getItem(kT)==="1"}catch{}return!1}const CT="sm.almanac.collapsedGroups";function FR(){try{const n=localStorage.getItem(CT);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 GR(){const n=xt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:Jr(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function HR({active:n,onNavigate:e,onNewSession:i}){const[r,s]=P.useState(()=>FR()),a=P.useCallback(R=>{s(M=>{const z=new Set(M);z.has(R)?z.delete(R):z.add(R);try{localStorage.setItem(CT,JSON.stringify(Array.from(z)))}catch{}return z})},[]),[c,l]=P.useState(()=>BR()),d=P.useCallback(()=>{l(R=>{const M=!R;try{localStorage.setItem(kT,M?"1":"0")}catch{}return M})},[]),p=xt(R=>R.tabs),m=xt(R=>R.activeTabId),f=p.find(R=>R.id===m)??null,x=GR(),y=gn(R=>R.navFace),w=zP(y),k=w.filter(R=>R.group==="Workspace"),b=w.filter(R=>R.group==="Configure"),_=OR(w),[S,E]=P.useState(()=>LR()),T=P.useRef(S);T.current=S;const N=P.useCallback(R=>{R.preventDefault();const M=R.clientX,z=T.current;let V=z;const H=X=>{V=Math.min(ST,Math.max(_T,z+(X.clientX-M))),E(V)},Q=()=>{window.removeEventListener("pointermove",H),window.removeEventListener("pointerup",Q),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(V_,String(V))}catch{}};window.addEventListener("pointermove",H),window.addEventListener("pointerup",Q),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),$=P.useCallback(()=>{E(q_);try{localStorage.setItem(V_,String(q_))}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:c?zR:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(UR,{tab:f,navFace:y,onNewSession:i,rail:c,onToggleRail:d}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:c?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!c&&o.jsx(Dw,{label:"Workspace",desc:kw.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(c||!r.has("Workspace"))&&k.map(R=>o.jsx(Yk,{item:R,active:n===R.key,live:R.liveKind?x[R.liveKind]:!1,onClick:()=>e(R.key),rail:c},R.key)),!c&&o.jsx(Dw,{label:"Configure",desc:kw.Configure,collapsed:r.has("Configure"),count:b.length,onToggle:()=>a("Configure")}),(c||!r.has("Configure"))&&b.map(R=>o.jsx(Yk,{item:R,active:n===R.key,live:!1,onClick:()=>e(R.key),rail:c},R.key)),_.length>0&&!c&&o.jsx(Dw,{label:"Tools",desc:kw.Tools,collapsed:r.has("Tools"),count:_.length,onToggle:()=>a("Tools")}),_.length>0&&(c||!r.has("Tools"))&&_.map(R=>o.jsx(WR,{tool:R,active:n===R.key,onClick:()=>e(R.key),rail:c},R.key))]})}),o.jsx(VR,{rail:c,navFace:y}),!c&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:$,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 UR({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",c=v1((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(an,{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(an,{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(an,{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(an,{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(an,{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:c?`⌥${c}`: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(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Dw({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 Yk({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(an,{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 WR({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(an,{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 VR({rail:n,navFace:e}){const i=Ct(d=>d.isRecording),r=xt(d=>d.tabs),s=xt(d=>d.activeTabId),a=r.find(d=>d.id===s)??null,[c,l]=P.useState(null);return P.useEffect(()=>{let d=!1;if(!(a!=null&&a.presetId)){l(null);return}return Vj(a.presetId).then(p=>{d||l((p==null?void 0:p.model)??null)}).catch(()=>{d||l(null)}),()=>{d=!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:c??"",children:i?"recording…":c?`Claude · ${sf(c)}`:"Claude Code"})]})}function qR(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function KR(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 jb=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]:KR(i,r,s)}});const c=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:c}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const d=e().tabs[i];if(!d)return;if(!l.ok){const{toast:m}=await pv(async()=>{const{toast:f}=await Promise.resolve().then(()=>Xj);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...d,path:null}}});return}n({tabs:{...e().tabs,[i]:{...d,path:l.path}}});const p=await window.api.transcripts.buffer(i);for(const m of p)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 c={...e().tabs};delete c[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:c})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const c=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:c},d=[],p=(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||d.push({id:0,kind:"todo-update",at:c,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,x={};for(const y of["command","file_path","pattern","url","query","subagent_type","description"])f&&y in f&&(x[y]=f[y]);if(l.lastToolUses=[{id:m.id,name:m.name,input:x,at:c},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const y=m.input,w=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(y==null?void 0:y.file_path)=="string"?y.file_path:void 0,b=typeof(y==null?void 0:y.command)=="string"?y.command:void 0,_=k?k.split("/").pop()??k:b?p(b,28):"";d.push({id:0,kind:"tool-use",at:c,label:_?`${m.name} · ${_}`:m.name,target:k??b,toolName:m.name}),w&&k&&d.push({id:0,kind:"file-edit",at:c,label:`${m.name} · ${p(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:c,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"plan-revision",at:c,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:c,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:c},...a.agents].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"agent-spawn",at:c,label:m!=null&&m.subagent_type?`Agent: ${p(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),x=m.input_tokens??m.inputTokens??0,y=m.output_tokens??m.outputTokens??0,w=f+x+y;l.usage={inputTokens:(a.usage.inputTokens||0)+x,outputTokens:(a.usage.outputTokens||0)+y,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(w/1e3)>Math.floor(f/1e3)&&d.push({id:0,kind:"usage-tick",at:c,label:`${Math.floor(w/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=qR(a.agents,m==null?void 0:m.toolUseId,c);break}}if(d.length>0){let m=a.activitySeq;const f=d.map(x=>({...x,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function YR(n){const e=jb(s=>s.subscribe),i=jb(s=>s.unsubscribe),r=jb(s=>n?s.tabs[n.id]:void 0);return P.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 XR({onNavigate:n}){const e=xt(E=>E.tabs),i=xt(E=>E.activeTabId),r=e.find(E=>E.id===i)??null,s=YR(r),a=(s==null?void 0:s.lastEventAt)??0,c=Lg(E=>E.data),l=Jr(E=>{var T;return((T=E.snapshot)==null?void 0:T.paused)??null}),d=v1((r==null?void 0:r.cwd)??null),[,p]=P.useState(0);P.useEffect(()=>{const E=setInterval(()=>p(T=>T+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,x]=P.useState(!1),y=P.useRef(null);P.useEffect(()=>{if(!f)return;const E=T=>{y.current&&!y.current.contains(T.target)&&x(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),P.useEffect(()=>{m.length===0&&x(!1)},[m.length]);const w=wT(c),k=(w==null?void 0:w.usage.five_hour)??null,b=k?Math.round(k.utilization):null,_=(c==null?void 0:c.kind)==="ok"||(c==null?void 0:c.kind)==="ok-stale",S=a>0?QR(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:_?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:_?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:b!=null?`${b}% 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,d&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(JR,{ref:y,todos:m,open:f,onToggle:()=>x(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.59.0"]})]})}const JR=P.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(c=>c.status==="completed").length,in_progress:e.filter(c=>c.status==="in_progress").length,pending:e.filter(c=>c.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((c,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${c.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(ZR,{status:c.status}),o.jsx("span",{className:c.status==="completed"?"text-fg-faint line-through":c.status==="in_progress"?"text-fg":"text-fg-dim",children:c.status==="in_progress"&&c.activeForm?c.activeForm:c.content})]},l))})})]})});function ZR({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 QR(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 eI({onClose:n,onSent:e}){const i=xt(R=>R.tabs),[r,s]=P.useState(""),[a,c]=P.useState(()=>Object.fromEntries(i.map(R=>[R.id,!0]))),[l,d]=P.useState(!1),[p,m]=P.useState({}),f=P.useRef(null),x=P.useRef(e);P.useEffect(()=>{x.current=e},[e]),P.useEffect(()=>{c(R=>{const M={};for(const z of i)M[z.id]=R[z.id]??!0;return M})},[i]),P.useEffect(()=>{var R;(R=f.current)==null||R.focus()},[]),P.useEffect(()=>window.api.pty.onWriteError(M=>{m(z=>M.tabId in z?{...z,[M.tabId]:"skipped"}:z)}),[]),P.useEffect(()=>{if(Object.keys(p).length===0)return;const R=Object.values(p).filter(z=>z==="sent").length,M=window.setTimeout(()=>x.current(R),1500);return()=>window.clearTimeout(M)},[p]);const y=i.filter(R=>a[R.id]).map(R=>R.id),w=y.length,k=Object.keys(p).length>0,b=r.length>0&&w>0&&!l&&!k,_=()=>{if(!b)return;d(!0);const R=xt.getState().tabs,M=new Set(R.map(V=>V.id)),z={};for(const V of y)M.has(V)?(window.api.pty.write({tabId:V,data:r+"\r"}),z[V]="sent"):z[V]="skipped";m(z),d(!1)},S=R=>{if(R.key==="Escape"){R.preventDefault(),R.stopPropagation(),n();return}R.key==="Enter"&&(R.metaKey||R.ctrlKey)&&(R.preventDefault(),_())},E=i.length>0&&i.every(R=>a[R.id]),T=()=>{const R=!E;c(Object.fromEntries(i.map(M=>[M.id,R])))},N=Object.values(p).some(R=>R==="skipped"),$=k?N?"Sent (some skipped)":"Sent":`Send to ${w} tab${w===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:R=>s(R.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:E,onChange:T,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",w,"/",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(R=>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[R.id],onChange:M=>c(z=>({...z,[R.id]:M.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:R.label}),p[R.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[R.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},R.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:_,disabled:!b,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:$})]})]})}function tI({tabId:n,cwd:e,onClose:i}){const r=Ig(w=>w.watchersForTab(n)),s=Ig(w=>w.add),a=Ig(w=>w.remove),c=P.useRef(null),[l,d]=P.useState(""),[p,m]=P.useState(""),[f,x]=P.useState(!1);P.useEffect(()=>{const w=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[i]),P.useEffect(()=>{const w=k=>{c.current&&!c.current.contains(k.target)&&i()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[i]);const y=async()=>{const w=p.trim();if(!w||f)return;x(!0);const k=await s({tabId:n,label:l.trim(),command:w,cwd:e});x(!1),k&&(d(""),m(""))};return o.jsxs("div",{ref:c,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:w=>d(w.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:p,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&y()},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:y,disabled:!p.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(w=>{const k=w.lines[w.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:w.label}),o.jsxs("span",{className:"text-fg-faint",children:[w.lineCount," line",w.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(w.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${w.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:w.command,children:w.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…"})})]},w.watcherId)})})]})}/**
2910
+ */var Ik;function iR(){return Ik||(Ik=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,c=Object.prototype.hasOwnProperty,l=(oe=>typeof No<"u"?No:typeof Proxy<"u"?new Proxy(oe,{get:(pe,we)=>(typeof No<"u"?No:pe)[we]}):oe)(function(oe){if(typeof No<"u")return No.apply(this,arguments);throw Error('Dynamic require of "'+oe+'" is not supported')}),d=(oe,pe)=>()=>(oe&&(pe=oe(oe=0)),pe),p=(oe,pe)=>{for(var we in pe)r(oe,we,{get:pe[we],enumerable:!0})},m=(oe,pe,we,$e)=>{if(pe&&typeof pe=="object"||typeof pe=="function")for(let Ee of a(pe))!c.call(oe,Ee)&&Ee!==we&&r(oe,Ee,{get:()=>pe[Ee],enumerable:!($e=s(pe,Ee))||$e.enumerable});return oe},f=oe=>m(r({},"__esModule",{value:!0}),oe),x,y,w,k,b,_=d(()=>{x=new Map,y=[],w=(oe,pe,we)=>{if(pe&&typeof pe.init=="function"&&typeof pe.createInferenceSessionHandler=="function"){let $e=x.get(oe);if($e===void 0)x.set(oe,{backend:pe,priority:we});else{if($e.priority>we)return;if($e.priority===we&&$e.backend!==pe)throw new Error(`cannot register backend "${oe}" using priority ${we}`)}if(we>=0){let Ee=y.indexOf(oe);Ee!==-1&&y.splice(Ee,1);for(let Ge=0;Ge<y.length;Ge++)if(x.get(y[Ge]).priority<=we){y.splice(Ge,0,oe);return}y.push(oe)}return}throw new TypeError("not a valid backend")},k=async oe=>{let pe=x.get(oe);if(!pe)return"backend not found.";if(pe.initialized)return pe.backend;if(pe.aborted)return pe.error;{let we=!!pe.initPromise;try{return we||(pe.initPromise=pe.backend.init(oe)),await pe.initPromise,pe.initialized=!0,pe.backend}catch($e){return we||(pe.error=`${$e}`,pe.aborted=!0),pe.error}finally{delete pe.initPromise}}},b=async oe=>{let pe=oe.executionProviders||[],we=pe.map(He=>typeof He=="string"?He:He.name),$e=we.length===0?y:we,Ee,Ge=[],Re=new Set;for(let He of $e){let it=await k(He);typeof it=="string"?Ge.push({name:He,err:it}):(Ee||(Ee=it),Ee===it&&Re.add(He))}if(!Ee)throw new Error(`no available backend found. ERR: ${Ge.map(He=>`[${He.name}] ${He.err}`).join(", ")}`);for(let{name:He,err:it}of Ge)we.includes(He)&&console.warn(`removing requested execution provider "${He}" from session options because it is not available: ${it}`);let Ie=pe.filter(He=>Re.has(typeof He=="string"?He:He.name));return[Ee,new Proxy(oe,{get:(He,it)=>it==="executionProviders"?Ie:Reflect.get(He,it)})]}}),S=d(()=>{_()}),E,T=d(()=>{E="1.26.0"}),N,$,R=d(()=>{T(),N="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:E},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($,"logLevel",{enumerable:!0})}),M,z=d(()=>{R(),M=$}),V,H,Q=d(()=>{V=(oe,pe)=>{let we=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);we.width=oe.dims[3],we.height=oe.dims[2];let $e=we.getContext("2d");if($e!=null){let Ee,Ge;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Ge=oe.dims[3]):(Ee=oe.dims[3],Ge=oe.dims[2]);let Re=(pe==null?void 0:pe.format)!==void 0?pe.format:"RGB",Ie=pe==null?void 0:pe.norm,He,it;Ie===void 0||Ie.mean===void 0?He=[255,255,255,255]:typeof Ie.mean=="number"?He=[Ie.mean,Ie.mean,Ie.mean,Ie.mean]:(He=[Ie.mean[0],Ie.mean[1],Ie.mean[2],0],Ie.mean[3]!==void 0&&(He[3]=Ie.mean[3])),Ie===void 0||Ie.bias===void 0?it=[0,0,0,0]:typeof Ie.bias=="number"?it=[Ie.bias,Ie.bias,Ie.bias,Ie.bias]:(it=[Ie.bias[0],Ie.bias[1],Ie.bias[2],0],Ie.bias[3]!==void 0&&(it[3]=Ie.bias[3]));let lt=Ge*Ee,rt=0,Je=lt,Pt=lt*2,Fe=-1;Re==="RGBA"?(rt=0,Je=lt,Pt=lt*2,Fe=lt*3):Re==="RGB"?(rt=0,Je=lt,Pt=lt*2):Re==="RBG"&&(rt=0,Pt=lt,Je=lt*2);for(let ht=0;ht<Ge;ht++)for(let Rn=0;Rn<Ee;Rn++){let tn=(oe.data[rt++]-it[0])*He[0],nn=(oe.data[Je++]-it[1])*He[1],In=(oe.data[Pt++]-it[2])*He[2],Bt=Fe===-1?255:(oe.data[Fe++]-it[3])*He[3];$e.fillStyle="rgba("+tn+","+nn+","+In+","+Bt+")",$e.fillRect(Rn,ht,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")},H=(oe,pe)=>{let we=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),$e;if(we!=null){let Ee,Ge,Re;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(Ee=oe.dims[2],Ge=oe.dims[1],Re=oe.dims[3]):(Ee=oe.dims[3],Ge=oe.dims[2],Re=oe.dims[1]);let Ie=pe!==void 0&&pe.format!==void 0?pe.format:"RGB",He=pe==null?void 0:pe.norm,it,lt;He===void 0||He.mean===void 0?it=[255,255,255,255]:typeof He.mean=="number"?it=[He.mean,He.mean,He.mean,He.mean]:(it=[He.mean[0],He.mean[1],He.mean[2],255],He.mean[3]!==void 0&&(it[3]=He.mean[3])),He===void 0||He.bias===void 0?lt=[0,0,0,0]:typeof He.bias=="number"?lt=[He.bias,He.bias,He.bias,He.bias]:(lt=[He.bias[0],He.bias[1],He.bias[2],0],He.bias[3]!==void 0&&(lt[3]=He.bias[3]));let rt=Ge*Ee;if(pe!==void 0&&(pe.format!==void 0&&Re===4&&pe.format!=="RGBA"||Re===3&&pe.format!=="RGB"&&pe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Je=4,Pt=0,Fe=1,ht=2,Rn=3,tn=0,nn=rt,In=rt*2,Bt=-1;Ie==="RGBA"?(tn=0,nn=rt,In=rt*2,Bt=rt*3):Ie==="RGB"?(tn=0,nn=rt,In=rt*2):Ie==="RBG"&&(tn=0,In=rt,nn=rt*2),$e=we.createImageData(Ee,Ge);for(let Fn=0;Fn<Ge*Ee;Pt+=Je,Fe+=Je,ht+=Je,Rn+=Je,Fn++)$e.data[Pt]=(oe.data[tn++]-lt[0])*it[0],$e.data[Fe]=(oe.data[nn++]-lt[1])*it[1],$e.data[ht]=(oe.data[In++]-lt[2])*it[2],$e.data[Rn]=Bt===-1?255:(oe.data[Bt++]-lt[3])*it[3]}else throw new Error("Can not access image data");return $e}}),X,q,J,ee,ie,re,B=d(()=>{Ae(),X=(oe,pe)=>{if(oe===void 0)throw new Error("Image buffer must be defined");if(pe.height===void 0||pe.width===void 0)throw new Error("Image height and width must be defined");if(pe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:we,width:$e}=pe,Ee=pe.norm??{mean:255,bias:0},Ge,Re;typeof Ee.mean=="number"?Ge=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:Ge=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?Re=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:Re=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let Ie=pe.format!==void 0?pe.format:"RGBA",He=pe.tensorFormat!==void 0&&pe.tensorFormat!==void 0?pe.tensorFormat:"RGB",it=we*$e,lt=He==="RGBA"?new Float32Array(it*4):new Float32Array(it*3),rt=4,Je=0,Pt=1,Fe=2,ht=3,Rn=0,tn=it,nn=it*2,In=-1;Ie==="RGB"&&(rt=3,Je=0,Pt=1,Fe=2,ht=-1),He==="RGBA"?In=it*3:He==="RBG"?(Rn=0,nn=it,tn=it*2):He==="BGR"&&(nn=0,tn=it,Rn=it*2);for(let Bt=0;Bt<it;Bt++,Je+=rt,Fe+=rt,Pt+=rt,ht+=rt)lt[Rn++]=(oe[Je]+Re[0])/Ge[0],lt[tn++]=(oe[Pt]+Re[1])/Ge[1],lt[nn++]=(oe[Fe]+Re[2])/Ge[2],In!==-1&&ht!==-1&&(lt[In++]=(oe[ht]+Re[3])/Ge[3]);return He==="RGBA"?new se("float32",lt,[1,4,we,$e]):new se("float32",lt,[1,3,we,$e])},q=async(oe,pe)=>{let we=typeof HTMLImageElement<"u"&&oe instanceof HTMLImageElement,$e=typeof ImageData<"u"&&oe instanceof ImageData,Ee=typeof ImageBitmap<"u"&&oe instanceof ImageBitmap,Ge=typeof oe=="string",Re,Ie=pe??{},He=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},it=lt=>typeof HTMLCanvasElement<"u"&&lt instanceof HTMLCanvasElement||lt instanceof OffscreenCanvas?lt.getContext("2d"):null;if(we){let lt=He();lt.width=oe.width,lt.height=oe.height;let rt=it(lt);if(rt!=null){let Je=oe.height,Pt=oe.width;if(pe!==void 0&&pe.resizedHeight!==void 0&&pe.resizedWidth!==void 0&&(Je=pe.resizedHeight,Pt=pe.resizedWidth),pe!==void 0){if(Ie=pe,pe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ie.tensorFormat="RGBA",Ie.height=Je,Ie.width=Pt}else Ie.tensorFormat="RGBA",Ie.height=Je,Ie.width=Pt;rt.drawImage(oe,0,0),Re=rt.getImageData(0,0,Pt,Je).data}else throw new Error("Can not access image data")}else if($e){let lt,rt;if(pe!==void 0&&pe.resizedWidth!==void 0&&pe.resizedHeight!==void 0?(lt=pe.resizedHeight,rt=pe.resizedWidth):(lt=oe.height,rt=oe.width),pe!==void 0&&(Ie=pe),Ie.format="RGBA",Ie.height=lt,Ie.width=rt,pe!==void 0){let Je=He();Je.width=rt,Je.height=lt;let Pt=it(Je);if(Pt!=null)Pt.putImageData(oe,0,0),Re=Pt.getImageData(0,0,rt,lt).data;else throw new Error("Can not access image data")}else Re=oe.data}else if(Ee){if(pe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let lt=He();lt.width=oe.width,lt.height=oe.height;let rt=it(lt);if(rt!=null){let Je=oe.height,Pt=oe.width;return rt.drawImage(oe,0,0,Pt,Je),Re=rt.getImageData(0,0,Pt,Je).data,Ie.height=Je,Ie.width=Pt,X(Re,Ie)}else throw new Error("Can not access image data")}else{if(Ge)return new Promise((lt,rt)=>{let Je=He(),Pt=it(Je);if(!oe||!Pt)return rt();let Fe=new Image;Fe.crossOrigin="Anonymous",Fe.src=oe,Fe.onload=()=>{Je.width=Fe.width,Je.height=Fe.height,Pt.drawImage(Fe,0,0,Je.width,Je.height);let ht=Pt.getImageData(0,0,Je.width,Je.height);Ie.height=Je.height,Ie.width=Je.width,lt(X(ht.data,Ie))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Re!==void 0)return X(Re,Ie);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(oe,pe)=>{let{width:we,height:$e,download:Ee,dispose:Ge}=pe,Re=[1,$e,we,4];return new se({location:"texture",type:"float32",texture:oe,dims:Re,download:Ee,dispose:Ge})},ee=(oe,pe)=>{let{dataType:we,dims:$e,download:Ee,dispose:Ge}=pe;return new se({location:"gpu-buffer",type:we??"float32",gpuBuffer:oe,dims:$e,download:Ee,dispose:Ge})},ie=(oe,pe)=>{let{dataType:we,dims:$e,download:Ee,dispose:Ge}=pe;return new se({location:"ml-tensor",type:we??"float32",mlTensor:oe,dims:$e,download:Ee,dispose:Ge})},re=(oe,pe,we)=>new se({location:"cpu-pinned",type:oe,data:pe,dims:we??[pe.length]})}),Z,W,le,ae,fe=d(()=>{Z=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),W=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,pe=typeof BigUint64Array<"u"&&BigUint64Array.from,we=globalThis.Float16Array,$e=typeof we<"u"&&we.from;oe&&(Z.set("int64",BigInt64Array),W.set(BigInt64Array,"int64")),pe&&(Z.set("uint64",BigUint64Array),W.set(BigUint64Array,"uint64")),$e?(Z.set("float16",we),W.set(we,"float16")):Z.set("float16",Uint16Array)}}}),Te,Ne,me=d(()=>{Ae(),Te=oe=>{let pe=1;for(let we=0;we<oe.length;we++){let $e=oe[we];if(typeof $e!="number"||!Number.isSafeInteger($e))throw new TypeError(`dims[${we}] must be an integer, got: ${$e}`);if($e<0)throw new RangeError(`dims[${we}] must be a non-negative integer, got: ${$e}`);pe*=$e}return pe},Ne=(oe,pe)=>{switch(oe.location){case"cpu":return new se(oe.type,oe.data,pe);case"cpu-pinned":return new se({location:"cpu-pinned",data:oe.data,type:oe.type,dims:pe});case"texture":return new se({location:"texture",texture:oe.texture,type:oe.type,dims:pe});case"gpu-buffer":return new se({location:"gpu-buffer",gpuBuffer:oe.gpuBuffer,type:oe.type,dims:pe});case"ml-tensor":return new se({location:"ml-tensor",mlTensor:oe.mlTensor,type:oe.type,dims:pe});default:throw new Error(`tensorReshape: tensor location ${oe.location} is not supported`)}}}),se,Ae=d(()=>{Q(),B(),fe(),me(),se=class{constructor(oe,pe,we){ae();let $e,Ee;if(typeof oe=="object"&&"location"in oe)switch(this.dataLocation=oe.location,$e=oe.type,Ee=oe.dims,oe.location){case"cpu-pinned":{let Re=Z.get($e);if(!Re)throw new TypeError(`unsupported type "${$e}" to create tensor from pinned buffer`);if(!(oe.data instanceof Re))throw new TypeError(`buffer should be of type ${Re.name}`);this.cpuData=oe.data;break}case"texture":{if($e!=="float32")throw new TypeError(`unsupported type "${$e}" to create tensor from texture`);this.gpuTextureData=oe.texture,this.downloader=oe.download,this.disposer=oe.dispose;break}case"gpu-buffer":{if($e!=="float32"&&$e!=="float16"&&$e!=="int32"&&$e!=="int64"&&$e!=="uint32"&&$e!=="uint8"&&$e!=="bool"&&$e!=="uint4"&&$e!=="int4")throw new TypeError(`unsupported type "${$e}" to create tensor from gpu buffer`);this.gpuBufferData=oe.gpuBuffer,this.downloader=oe.download,this.disposer=oe.dispose;break}case"ml-tensor":{if($e!=="float32"&&$e!=="float16"&&$e!=="int32"&&$e!=="int64"&&$e!=="uint32"&&$e!=="uint64"&&$e!=="int8"&&$e!=="uint8"&&$e!=="bool"&&$e!=="uint4"&&$e!=="int4")throw new TypeError(`unsupported type "${$e}" 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 Re,Ie;if(typeof oe=="string")if($e=oe,Ie=we,oe==="string"){if(!Array.isArray(pe))throw new TypeError("A string tensor's data must be a string array.");Re=pe}else{let He=Z.get(oe);if(He===void 0)throw new TypeError(`Unsupported tensor type: ${oe}.`);if(Array.isArray(pe)){if(oe==="float16"&&He===Uint16Array||oe==="uint4"||oe==="int4")throw new TypeError(`Creating a ${oe} tensor from number array is not supported. Please use ${He.name} as data.`);oe==="uint64"||oe==="int64"?Re=He.from(pe,BigInt):Re=He.from(pe)}else if(pe instanceof He)Re=pe;else if(pe instanceof Uint8ClampedArray)if(oe==="uint8")Re=Uint8Array.from(pe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(oe==="float16"&&pe instanceof Uint16Array&&He!==Uint16Array)Re=new globalThis.Float16Array(pe.buffer,pe.byteOffset,pe.length);else throw new TypeError(`A ${$e} tensor's data must be type of ${He}`)}else if(Ie=pe,Array.isArray(oe)){if(oe.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let He=typeof oe[0];if(He==="string")$e="string",Re=oe;else if(He==="boolean")$e="bool",Re=Uint8Array.from(oe);else throw new TypeError(`Invalid element type of data array: ${He}.`)}else if(oe instanceof Uint8ClampedArray)$e="uint8",Re=Uint8Array.from(oe);else{let He=W.get(oe.constructor);if(He===void 0)throw new TypeError(`Unsupported type for tensor data: ${oe.constructor}.`);$e=He,Re=oe}if(Ie===void 0)Ie=[Re.length];else if(!Array.isArray(Ie))throw new TypeError("A tensor's dims must be a number array");Ee=Ie,this.cpuData=Re,this.dataLocation="cpu"}let Ge=Te(Ee);if(this.cpuData&&Ge!==this.cpuData.length&&!(($e==="uint4"||$e==="int4")&&Math.ceil(Ge/2)===this.cpuData.length))throw new Error(`Tensor's size(${Ge}) does not match data length(${this.cpuData.length}).`);this.type=$e,this.dims=Ee,this.size=Ge}static async fromImage(oe,pe){return q(oe,pe)}static fromTexture(oe,pe){return J(oe,pe)}static fromGpuBuffer(oe,pe){return ee(oe,pe)}static fromMLTensor(oe,pe){return ie(oe,pe)}static fromPinnedBuffer(oe,pe,we){return re(oe,pe,we)}toDataURL(oe){return V(this,oe)}toImageData(oe){return H(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 pe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=pe,oe&&this.disposer&&(this.disposer(),this.disposer=void 0),pe}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 Ne(this,oe)}}}),ge,Se=d(()=>{Ae(),ge=se}),ye,et,pt,ot,nt,at,Nt=d(()=>{R(),ye=(oe,pe)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${oe}::ORT::${pe}`)},et=(oe,pe)=>{var Ee;let we=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],$e=!1;for(let Ge=0;Ge<we.length;Ge++){if($e&&!we[Ge].includes("TRACE_FUNC")){let Re=`FUNC_${oe}::${we[Ge].trim().split(" ")[1]}`;pe&&(Re+=`::${pe}`),ye("CPU",Re);return}we[Ge].includes("TRACE_FUNC")&&($e=!0)}},pt=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||et("BEGIN",oe)},ot=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||et("END",oe)},nt=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${oe}`)},at=oe=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${oe}`)}}),sn,vn=d(()=>{_(),Se(),Nt(),sn=class uT{constructor(pe){this.handler=pe}async run(pe,we,$e){pt(),nt("InferenceSession.run");let Ee={},Ge={};if(typeof pe!="object"||pe===null||pe instanceof ge||Array.isArray(pe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Re=!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.");Re=!1;for(let it of we){if(typeof it!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(it)===-1)throw new RangeError(`'fetches' contains invalid output name: ${it}.`);Ee[it]=null}if(typeof $e=="object"&&$e!==null)Ge=$e;else if(typeof $e<"u")throw new TypeError("'options' must be an object.")}else{let it=!1,lt=Object.getOwnPropertyNames(we);for(let rt of this.outputNames)if(lt.indexOf(rt)!==-1){let Je=we[rt];(Je===null||Je instanceof ge)&&(it=!0,Re=!1,Ee[rt]=Je)}if(it){if(typeof $e=="object"&&$e!==null)Ge=$e;else if(typeof $e<"u")throw new TypeError("'options' must be an object.")}else Ge=we}}else if(typeof we<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let it of this.inputNames)if(typeof pe[it]>"u")throw new Error(`input '${it}' is missing in 'feeds'.`);if(Re)for(let it of this.outputNames)Ee[it]=null;let Ie=await this.handler.run(pe,Ee,Ge),He={};for(let it in Ie)if(Object.hasOwnProperty.call(Ie,it)){let lt=Ie[it];lt instanceof ge?He[it]=lt:He[it]=new ge(lt.type,lt.data,lt.dims)}return at("InferenceSession.run"),ot(),He}async release(){return this.handler.dispose()}static async create(pe,we,$e,Ee){pt(),nt("InferenceSession.create");let Ge,Re={};if(typeof pe=="string"){if(Ge=pe,typeof we=="object"&&we!==null)Re=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof Uint8Array){if(Ge=pe,typeof we=="object"&&we!==null)Re=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&pe instanceof SharedArrayBuffer){let lt=pe,rt=0,Je=pe.byteLength;if(typeof we=="object"&&we!==null)Re=we;else if(typeof we=="number"){if(rt=we,!Number.isSafeInteger(rt))throw new RangeError("'byteOffset' must be an integer.");if(rt<0||rt>=lt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${lt.byteLength}).`);if(Je=pe.byteLength-rt,typeof $e=="number"){if(Je=$e,!Number.isSafeInteger(Je))throw new RangeError("'byteLength' must be an integer.");if(Je<=0||rt+Je>lt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${lt.byteLength-rt}].`);if(typeof Ee=="object"&&Ee!==null)Re=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else if(typeof $e<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof we<"u")throw new TypeError("'options' must be an object.");Ge=new Uint8Array(lt,rt,Je)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ie,He]=await b(Re),it=await Ie.createInferenceSessionHandler(Ge,He);return at("InferenceSession.create"),ot(),new uT(it)}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,Et=d(()=>{vn(),Ze=sn}),bt=d(()=>{}),pn=d(()=>{}),$n=d(()=>{}),tr=d(()=>{}),wr={};p(wr,{InferenceSession:()=>Ze,TRACE:()=>ye,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>at,TRACE_FUNC_BEGIN:()=>pt,TRACE_FUNC_END:()=>ot,Tensor:()=>ge,env:()=>M,registerBackend:()=>w});var xn=d(()=>{S(),z(),Et(),Se(),bt(),pn(),Nt(),$n(),tr()}),Wi=d(()=>{}),Jn={};p(Jn,{default:()=>Os});var ui,bn,Os,ol=d(()=>{var oe;_e(),rr(),ir(),ui="ort-wasm-proxy-worker",bn=((oe=globalThis.self)==null?void 0:oe.name)===ui,bn&&(self.onmessage=pe=>{let{type:we,in:$e}=pe.data;try{switch(we){case"init-wasm":bs($e.wasm).then(()=>{ya($e).then(()=>{postMessage({type:we})},Ee=>{postMessage({type:we,err:Ee})})},Ee=>{postMessage({type:we,err:Ee})});break;case"init-ep":{let{epName:Ee,env:Ge}=$e;Us(Ge,Ee).then(()=>{postMessage({type:we})},Re=>{postMessage({type:we,err:Re})});break}case"copy-from":{let{buffer:Ee}=$e,Ge=cn(Ee);postMessage({type:we,out:Ge});break}case"create":{let{model:Ee,options:Ge}=$e;Er(Ee,Ge).then(Re=>{postMessage({type:we,out:Re})},Re=>{postMessage({type:we,err:Re})});break}case"release":uo($e),postMessage({type:we});break;case"run":{let{sessionId:Ee,inputIndices:Ge,inputs:Re,outputIndices:Ie,options:He}=$e;Xe(Ee,Ge,Re,Ie,new Array(Ie.length).fill(null),He).then(it=>{it.some(lt=>lt[3]!=="cpu")?postMessage({type:we,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:we,out:it},gt([...Re,...it]))},it=>{postMessage({type:we,err:it})});break}case"end-profiling":or($e),postMessage({type:we});break;default:}}catch(Ee){postMessage({type:we,err:Ee})}}),Os=bn?null:pe=>new Worker(pe??Cn,{type:"classic",name:ui})}),xa,Ls,Cn,nr,hi,zs,Zr,_r,ao,Bs,Fs,Qr,Vi,ir=d(()=>{Wi(),xa=typeof location>"u"?void 0:location.origin,Ls=()=>{var oe,pe;return typeof document<"u"?(oe=document.currentScript)==null?void 0:oe.src:typeof self<"u"?(pe=self.location)==null?void 0:pe.href:void 0},Cn=Ls(),nr=()=>{if(Cn&&!Cn.startsWith("blob:"))return Cn.substring(0,Cn.lastIndexOf("/")+1)},hi=(oe,pe)=>{try{let we=pe??Cn;return(we?new URL(oe,we):new URL(oe)).origin===xa}catch{return!1}},zs=(oe,pe)=>{let we=pe??Cn;try{return(we?new URL(oe,we):new URL(oe)).href}catch{return}},Zr=(oe,pe)=>`${pe??"./"}${oe}`,_r=async oe=>{let pe=await(await fetch(oe,{credentials:"same-origin"})).blob();return URL.createObjectURL(pe)},ao=async oe=>(await import(oe)).default,Bs=(ol(),f(Jn)).default,Fs=async()=>{if(!Cn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(hi(Cn))return[void 0,Bs()];let oe=await _r(Cn);return[oe,Bs(oe)]},Qr=void 0,Vi=async(oe,pe,we,$e)=>{let Ee=Qr&&!(oe||pe);if(Ee)if(Cn)Ee=hi(Cn)||$e&&!we;else if($e&&!we)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Qr];{let Ge="ort-wasm-simd-threaded.mjs",Re=oe??zs(Ge,pe),Ie=we&&Re&&!hi(Re,pe),He=Ie?await _r(Re):Re??Zr(Ge,pe);return[Ie?He:void 0,await ao(He)]}}}),gs,qi,Sr,Hr,Ro,vs,xs,bs,Gt,rr=d(()=>{ir(),qi=!1,Sr=!1,Hr=!1,Ro=()=>{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}},vs=()=>{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}},xs=()=>{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}},bs=async oe=>{if(qi)return Promise.resolve();if(Sr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Hr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Sr=!0;let pe=oe.initTimeout,we=oe.numThreads;if(oe.simd!==!1){if(oe.simd==="relaxed"){if(!xs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let $e=Ro();we>1&&!$e&&(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,Ge=typeof Ee=="string"?Ee:void 0,Re=Ee==null?void 0:Ee.mjs,Ie=(Re==null?void 0:Re.href)??Re,He=Ee==null?void 0:Ee.wasm,it=(He==null?void 0:He.href)??He,lt=oe.wasmBinary,[rt,Je]=await Vi(Ie,Ge,we>1,!!lt||!!it),Pt=!1,Fe=[];if(pe>0&&Fe.push(new Promise(ht=>{setTimeout(()=>{Pt=!0,ht()},pe)})),Fe.push(new Promise((ht,Rn)=>{let tn={numThreads:we};if(lt)tn.wasmBinary=lt,tn.locateFile=nn=>nn;else if(it||Ge)tn.locateFile=nn=>it??Ge+nn;else if(Ie&&Ie.indexOf("blob:")!==0)tn.locateFile=nn=>new URL(nn,Ie).href;else if(rt){let nn=nr();nn&&(tn.locateFile=In=>nn+In)}Je(tn).then(nn=>{Sr=!1,qi=!0,gs=nn,ht(),rt&&URL.revokeObjectURL(rt)},nn=>{Sr=!1,Hr=!0,Rn(nn)})})),await Promise.race(Fe),Pt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${pe}ms`)},Gt=()=>{if(qi&&gs)return gs;throw new Error("WebAssembly is not initialized yet.")}}),Zn,Nn,jt,lo=d(()=>{rr(),Zn=(oe,pe)=>{let we=Gt(),$e=we.lengthBytesUTF8(oe)+1,Ee=we._malloc($e);return we.stringToUTF8(oe,Ee,$e),pe.push(Ee),Ee},Nn=(oe,pe,we,$e)=>{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,Ge])=>{let Re=pe?pe+Ee:Ee;if(typeof Ge=="object")Nn(Ge,Re+".",we,$e);else if(typeof Ge=="string"||typeof Ge=="number")$e(Re,Ge.toString());else if(typeof Ge=="boolean")$e(Re,Ge?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Ge}`)})},jt=oe=>{let pe=Gt(),we=pe.stackSave();try{let $e=pe.PTR_SIZE,Ee=pe.stackAlloc(2*$e);pe._OrtGetLastError(Ee,Ee+$e);let Ge=Number(pe.getValue(Ee,$e===4?"i32":"i64")),Re=pe.getValue(Ee+$e,"*"),Ie=Re?pe.UTF8ToString(Re):"";throw new Error(`${oe} ERROR_CODE: ${Ge}, ERROR_MESSAGE: ${Ie}`)}finally{pe.stackRestore(we)}}}),Io,al=d(()=>{rr(),lo(),Io=oe=>{let pe=Gt(),we=0,$e=[],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 Ge=0;return(oe==null?void 0:oe.tag)!==void 0&&(Ge=Zn(oe.tag,$e)),we=pe._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,Ge),we===0&&jt("Can't create run options."),(oe==null?void 0:oe.extra)!==void 0&&Nn(oe.extra,"",new WeakSet,(Re,Ie)=>{let He=Zn(Re,$e),it=Zn(Ie,$e);pe._OrtAddRunConfigEntry(we,He,it)!==0&&jt(`Can't set a run config entry: ${Re} - ${Ie}.`)}),[we,$e]}catch(Ge){throw we!==0&&pe._OrtReleaseRunOptions(we),$e.forEach(Re=>pe._free(Re)),Ge}}}),Mo,Oo,ba,Li,ll,cl,Dn=d(()=>{rr(),lo(),Mo=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}`)}},Oo=oe=>{switch(oe){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${oe}`)}},ba=oe=>{oe.extra||(oe.extra={}),oe.extra.session||(oe.extra.session={});let pe=oe.extra.session;pe.use_ort_model_bytes_directly||(pe.use_ort_model_bytes_directly="1"),oe.executionProviders&&oe.executionProviders.some(we=>(typeof we=="string"?we:we.name)==="webgpu")&&(oe.enableMemPattern=!1)},Li=(oe,pe,we,$e)=>{let Ee=Zn(pe,$e),Ge=Zn(we,$e);Gt()._OrtAddSessionConfigEntry(oe,Ee,Ge)!==0&&jt(`Can't set a session config entry: ${pe} - ${we}.`)},ll=async(oe,pe,we)=>{let $e=pe.executionProviders;for(let Ee of $e){let Ge=typeof Ee=="string"?Ee:Ee.name,Re=[];switch(Ge){case"webnn":if(Ge="WEBNN",Li(oe,"session.disable_quant_qdq","1",we),Li(oe,"session.disable_qdq_constant_folding","1",we),typeof Ee!="string"){let rt=Ee==null?void 0:Ee.deviceType;rt&&Li(oe,"deviceType",rt,we)}break;case"webgpu":if(Ge="JS",typeof Ee!="string"){let rt=Ee;if(rt!=null&&rt.preferredLayout){if(rt.preferredLayout!=="NCHW"&&rt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${rt.preferredLayout}`);Li(oe,"preferredLayout",rt.preferredLayout,we)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Ge}`)}let Ie=Zn(Ge,we),He=Re.length,it=0,lt=0;if(He>0){it=Gt()._malloc(He*Gt().PTR_SIZE),we.push(it),lt=Gt()._malloc(He*Gt().PTR_SIZE),we.push(lt);for(let rt=0;rt<He;rt++)Gt().setValue(it+rt*Gt().PTR_SIZE,Re[rt][0],"*"),Gt().setValue(lt+rt*Gt().PTR_SIZE,Re[rt][1],"*")}await Gt()._OrtAppendExecutionProvider(oe,Ie,it,lt,He)!==0&&jt(`Can't append execution provider: ${Ge}.`)}},cl=async oe=>{let pe=Gt(),we=0,$e=[],Ee=oe||{};ba(Ee);try{let Ge=Mo(Ee.graphOptimizationLevel??"all"),Re=Oo(Ee.executionMode??"sequential"),Ie=typeof Ee.logId=="string"?Zn(Ee.logId,$e):0,He=Ee.logSeverityLevel??2;if(!Number.isInteger(He)||He<0||He>4)throw new Error(`log severity level is not valid: ${He}`);let it=Ee.logVerbosityLevel??0;if(!Number.isInteger(it)||it<0||it>4)throw new Error(`log verbosity level is not valid: ${it}`);let lt=typeof Ee.optimizedModelFilePath=="string"?Zn(Ee.optimizedModelFilePath,$e):0;if(we=pe._OrtCreateSessionOptions(Ge,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,Re,!!Ee.enableProfiling,0,Ie,He,it,lt),we===0&&jt("Can't create session options."),Ee.executionProviders&&await ll(we,Ee,$e),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(),$e)}if(Ee.freeDimensionOverrides)for(let[rt,Je]of Object.entries(Ee.freeDimensionOverrides)){if(typeof rt!="string")throw new Error(`free dimension override name must be a string: ${rt}`);if(typeof Je!="number"||!Number.isInteger(Je)||Je<0)throw new Error(`free dimension override value must be a non-negative integer: ${Je}`);let Pt=Zn(rt,$e);pe._OrtAddFreeDimensionOverride(we,Pt,Je)!==0&&jt(`Can't set a free dimension override: ${rt} - ${Je}.`)}return Ee.extra!==void 0&&Nn(Ee.extra,"",new WeakSet,(rt,Je)=>{Li(we,rt,Je,$e)}),[we,$e]}catch(Ge){throw we!==0&&pe._OrtReleaseSessionOptions(we)!==0&&jt("Can't release session options."),$e.forEach(Re=>pe._free(Re)),Ge}}}),Ki,ti,Yi,ys,co,Gs,kr,Ni,Ht=d(()=>{Ki=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}`)}},ti=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}`)}},Yi=(oe,pe)=>{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],$e=typeof pe=="number"?pe:pe.reduce((Ee,Ge)=>Ee*Ge,1);return we>0?Math.ceil($e*we):void 0},ys=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}`)}},co=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}`)}},Gs=oe=>oe==="float32"||oe==="float16"||oe==="int32"||oe==="int64"||oe==="uint32"||oe==="uint8"||oe==="bool"||oe==="uint4"||oe==="int4",kr=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}`)}}}),ni,Hs=d(()=>{Wi(),ni=async oe=>{if(typeof oe=="string"){let pe=await fetch(oe);if(!pe.ok)throw new Error(`failed to load external data file: ${oe}`);let we=pe.headers.get("Content-Length"),$e=we?parseInt(we,10):0;if($e<1073741824)return new Uint8Array(await pe.arrayBuffer());{if(!pe.body)throw new Error(`failed to load external data file: ${oe}, no response body.`);let Ee=pe.body.getReader(),Ge;try{Ge=new ArrayBuffer($e)}catch(Ie){if(Ie instanceof RangeError){let He=Math.ceil($e/65536);Ge=new WebAssembly.Memory({initial:He,maximum:He}).buffer}else throw Ie}let Re=0;for(;;){let{done:Ie,value:He}=await Ee.read();if(Ie)break;let it=He.byteLength;new Uint8Array(Ge,Re,it).set(He),Re+=it}return new Uint8Array(Ge,0,$e)}}else return oe instanceof Blob?new Uint8Array(await oe.arrayBuffer()):oe instanceof Uint8Array?oe:new Uint8Array(oe)}}),Cr,ya,Us,sr,es,Ws,cn,Er,uo,Ur,Xe,or,gt,_e=d(()=>{xn(),al(),Dn(),Ht(),rr(),lo(),Hs(),Cr=(oe,pe)=>{Gt()._OrtInit(oe,pe)!==0&&jt("Can't initialize onnxruntime.")},ya=async oe=>{Cr(oe.wasm.numThreads,co(oe.logLevel))},Us=async(oe,pe)=>{var $e,Ee;(Ee=($e=Gt()).asyncInit)==null||Ee.call($e);let we=oe.webgpu.adapter;if(pe==="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 Ge=oe.webgpu.powerPreference;if(Ge!==void 0&&Ge!=="low-power"&&Ge!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Ge}"`);let Re=oe.webgpu.forceFallbackAdapter;if(Re!==void 0&&typeof Re!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Re}"`);if(we=await navigator.gpu.requestAdapter({powerPreference:Ge,forceFallbackAdapter:Re}),!we)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(pe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},sr=new Map,es=oe=>{let pe=Gt(),we=pe.stackSave();try{let $e=pe.PTR_SIZE,Ee=pe.stackAlloc(2*$e);pe._OrtGetInputOutputCount(oe,Ee,Ee+$e)!==0&&jt("Can't get session input/output count.");let Ge=$e===4?"i32":"i64";return[Number(pe.getValue(Ee,Ge)),Number(pe.getValue(Ee+$e,Ge))]}finally{pe.stackRestore(we)}},Ws=(oe,pe)=>{let we=Gt(),$e=we.stackSave(),Ee=0;try{let Ge=we.PTR_SIZE,Re=we.stackAlloc(2*Ge);we._OrtGetInputOutputMetadata(oe,pe,Re,Re+Ge)!==0&&jt("Can't get session input/output metadata.");let Ie=Number(we.getValue(Re,"*"));Ee=Number(we.getValue(Re+Ge,"*"));let He=we.HEAP32[Ee/4];if(He===0)return[Ie,0];let it=we.HEAPU32[Ee/4+1],lt=[];for(let rt=0;rt<it;rt++){let Je=Number(we.getValue(Ee+8+rt*Ge,"*"));lt.push(Je!==0?we.UTF8ToString(Je):Number(we.getValue(Ee+8+(rt+it)*Ge,"*")))}return[Ie,He,lt]}finally{we.stackRestore($e),Ee!==0&&we._OrtFree(Ee)}},cn=oe=>{let pe=Gt(),we=pe._malloc(oe.byteLength);if(we===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${oe.byteLength}.`);return pe.HEAPU8.set(oe,we),[we,oe.byteLength]},Er=async(oe,pe)=>{var lt,rt,Je;let we,$e,Ee=Gt();Array.isArray(oe)?[we,$e]=oe:oe.buffer===Ee.HEAPU8.buffer?[we,$e]=[oe.byteOffset,oe.byteLength]:[we,$e]=cn(oe);let Ge=0,Re=0,Ie=[],He=[],it=[];try{if([Re,Ie]=await cl(pe),(pe==null?void 0:pe.externalData)&&Ee.mountExternalData){let Fn=[];for(let fn of pe.externalData){let Di=typeof fn=="string"?fn:fn.path;Fn.push(ni(typeof fn=="string"?fn:fn.data).then(Xi=>{Ee.mountExternalData(Di,Xi)}))}await Promise.all(Fn)}for(let Fn of(pe==null?void 0:pe.executionProviders)??[])if((typeof Fn=="string"?Fn:Fn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Fn!="string"){let fn=Fn,Di=fn==null?void 0:fn.context,Xi=fn==null?void 0:fn.gpuDevice,ar=fn==null?void 0:fn.deviceType,ul=fn==null?void 0:fn.powerPreference;Di?Ee.currentContext=Di:Xi?Ee.currentContext=await Ee.webnnCreateMLContext(Xi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:ar,powerPreference:ul})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}Ge=await Ee._OrtCreateSession(we,$e,Re),(lt=Ee.webgpuOnCreateSession)==null||lt.call(Ee,Ge),Ge===0&&jt("Can't create a session."),(rt=Ee.jsepOnCreateSession)==null||rt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(Ge,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[Pt,Fe]=es(Ge),ht=!!(pe!=null&&pe.enableGraphCapture),Rn=[],tn=[],nn=[],In=[],Bt=[];for(let Fn=0;Fn<Pt;Fn++){let[fn,Di,Xi]=Ws(Ge,Fn);fn===0&&jt("Can't get an input name."),He.push(fn);let ar=Ee.UTF8ToString(fn);Rn.push(ar),nn.push(Di===0?{name:ar,isTensor:!1}:{name:ar,isTensor:!0,type:ti(Di),shape:Xi})}for(let Fn=0;Fn<Fe;Fn++){let[fn,Di,Xi]=Ws(Ge,Fn+Pt);fn===0&&jt("Can't get an output name."),it.push(fn);let ar=Ee.UTF8ToString(fn);tn.push(ar),In.push(Di===0?{name:ar,isTensor:!1}:{name:ar,isTensor:!0,type:ti(Di),shape:Xi})}return sr.set(Ge,[Ge,He,it,null,ht,!1]),[Ge,Rn,tn,nn,In]}catch(Pt){throw He.forEach(Fe=>Ee._OrtFree(Fe)),it.forEach(Fe=>Ee._OrtFree(Fe)),Ge!==0&&Ee._OrtReleaseSession(Ge)!==0&&jt("Can't release session."),Pt}finally{Ee._free(we),Re!==0&&Ee._OrtReleaseSessionOptions(Re)!==0&&jt("Can't release session options."),Ie.forEach(Pt=>Ee._free(Pt)),(Je=Ee.unmountExternalData)==null||Je.call(Ee)}},uo=oe=>{var He,it,lt;let pe=Gt(),we=sr.get(oe);if(!we)throw new Error(`cannot release session. invalid session id: ${oe}`);let[$e,Ee,Ge,Re,Ie]=we;Re&&(Ie&&pe._OrtClearBoundOutputs(Re.handle)!==0&&jt("Can't clear bound outputs."),pe._OrtReleaseBinding(Re.handle)!==0&&jt("Can't release IO binding.")),(He=pe.jsepOnReleaseSession)==null||He.call(pe,oe),(it=pe.webnnOnReleaseSession)==null||it.call(pe,oe),(lt=pe.webgpuOnReleaseSession)==null||lt.call(pe,oe),Ee.forEach(rt=>pe._OrtFree(rt)),Ge.forEach(rt=>pe._OrtFree(rt)),pe._OrtReleaseSession($e)!==0&&jt("Can't release session."),sr.delete(oe)},Ur=async(oe,pe,we,$e,Ee,Ge,Re=!1)=>{if(!oe){pe.push(0);return}let Ie=Gt(),He=Ie.PTR_SIZE,it=oe[0],lt=oe[1],rt=oe[3],Je=rt,Pt,Fe;if(it==="string"&&(rt==="gpu-buffer"||rt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Re&&rt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Ge} when enableGraphCapture is true.`);if(rt==="gpu-buffer"){let tn=oe[2].gpuBuffer;Fe=Yi(Ki(it),lt);{let nn=Ie.jsepRegisterBuffer;if(!nn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Pt=nn($e,Ge,tn,Fe)}}else if(rt==="ml-tensor"){let tn=oe[2].mlTensor;Fe=Yi(Ki(it),lt);let nn=Ie.webnnRegisterMLTensor;if(!nn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Pt=nn($e,tn,Ki(it),lt)}else{let tn=oe[2];if(Array.isArray(tn)){Fe=He*tn.length,Pt=Ie._malloc(Fe),we.push(Pt);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`);Ie.setValue(Pt+nn*He,Zn(tn[nn],we),"*")}}else{let nn=Ie.webnnIsGraphInput,In=Ie.webnnIsGraphOutput;if(it!=="string"&&nn&&In){let Bt=Ie.UTF8ToString(Ee);if(nn($e,Bt)||In($e,Bt)){let Fn=Ki(it);Fe=Yi(Fn,lt),Je="ml-tensor";let fn=Ie.webnnCreateTemporaryTensor,Di=Ie.webnnUploadTensor;if(!fn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Xi=await fn($e,Fn,lt);Di(Xi,new Uint8Array(tn.buffer,tn.byteOffset,tn.byteLength)),Pt=Xi}else Fe=tn.byteLength,Pt=Ie._malloc(Fe),we.push(Pt),Ie.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,Fe),Pt)}else Fe=tn.byteLength,Pt=Ie._malloc(Fe),we.push(Pt),Ie.HEAPU8.set(new Uint8Array(tn.buffer,tn.byteOffset,Fe),Pt)}}let ht=Ie.stackSave(),Rn=Ie.stackAlloc(4*lt.length);try{lt.forEach((nn,In)=>Ie.setValue(Rn+In*He,nn,He===4?"i32":"i64"));let tn=Ie._OrtCreateTensor(Ki(it),Pt,Fe,Rn,lt.length,Ni(Je));tn===0&&jt(`Can't create tensor for input/output. session=${$e}, index=${Ge}.`),pe.push(tn)}finally{Ie.stackRestore(ht)}},Xe=async(oe,pe,we,$e,Ee,Ge)=>{var lr,lc,bd;let Re=Gt(),Ie=Re.PTR_SIZE,He=sr.get(oe);if(!He)throw new Error(`cannot run inference. invalid session id: ${oe}`);let it=He[0],lt=He[1],rt=He[2],Je=He[3],Pt=He[4];He[5];let Fe=pe.length,ht=$e.length,Rn=0,tn=[],nn=[],In=[],Bt=[],Fn=[],fn=Re.stackSave(),Di=Re.stackAlloc(Fe*Ie),Xi=Re.stackAlloc(Fe*Ie),ar=Re.stackAlloc(ht*Ie),ul=Re.stackAlloc(ht*Ie);try{[Rn,tn]=Io(Ge),nt("wasm prepareInputOutputTensor");for(let un=0;un<Fe;un++)await Ur(we[un],nn,Bt,oe,lt[pe[un]],pe[un],Pt);for(let un=0;un<ht;un++)await Ur(Ee[un],In,Bt,oe,rt[$e[un]],Fe+$e[un],Pt);at("wasm prepareInputOutputTensor");for(let un=0;un<Fe;un++)Re.setValue(Di+un*Ie,nn[un],"*"),Re.setValue(Xi+un*Ie,lt[pe[un]],"*");for(let un=0;un<ht;un++)Re.setValue(ar+un*Ie,In[un],"*"),Re.setValue(ul+un*Ie,rt[$e[un]],"*");(lr=Re.jsepOnRunStart)==null||lr.call(Re,it),(lc=Re.webnnOnRunStart)==null||lc.call(Re,it);let Ai;Ai=await Re._OrtRun(it,Xi,Di,Fe,ul,ht,ar,Rn),Ai!==0&&jt("failed to call OrtRun().");let _s=[],yd=[];nt("wasm ProcessOutputTensor");for(let un=0;un<ht;un++){let ns=Number(Re.getValue(ar+un*Ie,"*"));if(ns===In[un]||Fn.includes(In[un])){_s.push(Ee[un]),ns!==In[un]&&Re._OrtReleaseTensor(ns)!==0&&jt("Can't release tensor.");continue}let Fu=Re.stackSave(),Ks=Re.stackAlloc(4*Ie),wa=!1,xi,cr=0;try{Re._OrtGetTensorData(ns,Ks,Ks+Ie,Ks+2*Ie,Ks+3*Ie)!==0&&jt(`Can't access output tensor data on index ${un}.`);let cc=Ie===4?"i32":"i64",dr=Number(Re.getValue(Ks,cc));cr=Re.getValue(Ks+Ie,"*");let wd=Re.getValue(Ks+Ie*2,"*"),Gu=Number(Re.getValue(Ks+Ie*3,cc)),Ys=[];for(let bi=0;bi<Gu;bi++)Ys.push(Number(Re.getValue(wd+bi*Ie,cc)));Re._OrtFree(wd)!==0&&jt("Can't free memory for tensor dims.");let is=Ys.reduce((bi,Qn)=>bi*Qn,1);xi=ti(dr);let Ss=Je==null?void 0:Je.outputPreferredLocations[$e[un]];if(xi==="string"){if(Ss==="gpu-buffer"||Ss==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let bi=[];for(let Qn=0;Qn<is;Qn++){let rs=Re.getValue(cr+Qn*Ie,"*"),_d=Re.getValue(cr+(Qn+1)*Ie,"*"),Sd=Qn===is-1?void 0:_d-rs;bi.push(Re.UTF8ToString(rs,Sd))}_s.push([xi,Ys,bi,"cpu"])}else if(Ss==="gpu-buffer"&&is>0){let bi=Re.jsepGetBuffer;if(!bi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Qn=bi(cr),rs=Yi(dr,is);if(rs===void 0||!Gs(xi))throw new Error(`Unsupported data type: ${xi}`);wa=!0,_s.push([xi,Ys,{gpuBuffer:Qn,download:Re.jsepCreateDownloader(Qn,rs,xi),dispose:()=>{Re._OrtReleaseTensor(ns)!==0&&jt("Can't release tensor.")}},"gpu-buffer"])}else if(Ss==="ml-tensor"&&is>0){let bi=Re.webnnEnsureTensor,Qn=Re.webnnIsGraphInputOutputTypeSupported;if(!bi||!Qn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Yi(dr,is)===void 0||!kr(xi))throw new Error(`Unsupported data type: ${xi}`);if(!Qn(oe,xi,!1))throw new Error(`preferredLocation "ml-tensor" for ${xi} output is not supported by current WebNN Context.`);let rs=await bi(oe,cr,dr,Ys,!1);wa=!0,_s.push([xi,Ys,{mlTensor:rs,download:Re.webnnCreateMLTensorDownloader(cr,xi),dispose:()=>{Re.webnnReleaseTensorId(cr),Re._OrtReleaseTensor(ns)}},"ml-tensor"])}else if(Ss==="ml-tensor-cpu-output"&&is>0){let bi=Re.webnnCreateMLTensorDownloader(cr,xi)(),Qn=_s.length;wa=!0,yd.push((async()=>{let rs=[Qn,await bi];return Re.webnnReleaseTensorId(cr),Re._OrtReleaseTensor(ns),rs})()),_s.push([xi,Ys,[],"cpu"])}else{let bi=ys(xi),Qn=new bi(is);new Uint8Array(Qn.buffer,Qn.byteOffset,Qn.byteLength).set(Re.HEAPU8.subarray(cr,cr+Qn.byteLength)),_s.push([xi,Ys,Qn,"cpu"])}}finally{Re.stackRestore(Fu),xi==="string"&&cr&&Re._free(cr),wa||Re._OrtReleaseTensor(ns)}}Je&&!Pt&&(Re._OrtClearBoundOutputs(Je.handle)!==0&&jt("Can't clear bound outputs."),sr.set(oe,[it,lt,rt,Je,Pt,!1]));for(let[un,ns]of await Promise.all(yd))_s[un][2]=ns;return at("wasm ProcessOutputTensor"),_s}finally{(bd=Re.webnnOnRunEnd)==null||bd.call(Re,it),Re.stackRestore(fn),nn.forEach(Ai=>Re._OrtReleaseTensor(Ai)),In.forEach(Ai=>Re._OrtReleaseTensor(Ai)),Bt.forEach(Ai=>Re._free(Ai)),Rn!==0&&Re._OrtReleaseRunOptions(Rn),tn.forEach(Ai=>Re._free(Ai))}},or=oe=>{let pe=Gt(),we=sr.get(oe);if(!we)throw new Error("invalid session id");let $e=we[0],Ee=pe._OrtEndProfiling($e);Ee===0&&jt("Can't get an profile file name."),pe._OrtFree(Ee)},gt=oe=>{let pe=[];for(let we of oe){let $e=we[2];!Array.isArray($e)&&"buffer"in $e&&pe.push($e.buffer)}return pe}}),Le,Qe,Dt,on,dn,zn,Mn,pi,Wn,vi,On,ts,ho,Lo,ws,Bu,zo,Bo,gd=d(()=>{xn(),_e(),rr(),ir(),Le=()=>!!M.wasm.proxy&&typeof document<"u",Dt=!1,on=!1,dn=!1,pi=new Map,Wn=(oe,pe)=>{let we=pi.get(oe);we?we.push(pe):pi.set(oe,[pe])},vi=()=>{if(Dt||!on||dn||!Qe)throw new Error("worker not ready")},On=oe=>{switch(oe.data.type){case"init-wasm":Dt=!1,oe.data.err?(dn=!0,Mn[1](oe.data.err)):(on=!0,Mn[0]()),zn&&(URL.revokeObjectURL(zn),zn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let pe=pi.get(oe.data.type);oe.data.err?pe.shift()[1](oe.data.err):pe.shift()[0](oe.data.out);break}}},ts=async()=>{if(!on){if(Dt)throw new Error("multiple calls to 'initWasm()' detected.");if(dn)throw new Error("previous call to 'initWasm()' failed.");if(Dt=!0,Le())return new Promise((oe,pe)=>{Qe==null||Qe.terminate(),Fs().then(([we,$e])=>{try{Qe=$e,Qe.onerror=Ge=>pe(Ge),Qe.onmessage=On,Mn=[oe,pe];let Ee={type:"init-wasm",in:M};if(!Ee.in.wasm.wasmPaths&&we){let Ge=nr();Ge&&(Ee.in.wasm.wasmPaths=Ge)}Qe.postMessage(Ee),zn=we}catch(Ee){pe(Ee)}},pe)});try{await bs(M.wasm),await ya(M),on=!0}catch(oe){throw dn=!0,oe}finally{Dt=!1}}},ho=async oe=>{if(Le())return vi(),new Promise((pe,we)=>{Wn("init-ep",[pe,we]);let $e={type:"init-ep",in:{epName:oe,env:M}};Qe.postMessage($e)});await Us(M,oe)},Lo=async oe=>Le()?(vi(),new Promise((pe,we)=>{Wn("copy-from",[pe,we]);let $e={type:"copy-from",in:{buffer:oe}};Qe.postMessage($e,[oe.buffer])})):cn(oe),ws=async(oe,pe)=>{if(Le()){if(pe!=null&&pe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return vi(),new Promise((we,$e)=>{Wn("create",[we,$e]);let Ee={type:"create",in:{model:oe,options:{...pe}}},Ge=[];oe instanceof Uint8Array&&Ge.push(oe.buffer),Qe.postMessage(Ee,Ge)})}else return Er(oe,pe)},Bu=async oe=>{if(Le())return vi(),new Promise((pe,we)=>{Wn("release",[pe,we]);let $e={type:"release",in:oe};Qe.postMessage($e)});uo(oe)},zo=async(oe,pe,we,$e,Ee,Ge)=>{if(Le()){if(we.some(Re=>Re[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some(Re=>Re))throw new Error("pre-allocated output tensor is not supported for proxy.");return vi(),new Promise((Re,Ie)=>{Wn("run",[Re,Ie]);let He=we,it={type:"run",in:{sessionId:oe,inputIndices:pe,inputs:He,outputIndices:$e,options:Ge}};Qe.postMessage(it,gt(He))})}else return Xe(oe,pe,we,$e,Ee,Ge)},Bo=async oe=>{if(Le())return vi(),new Promise((pe,we)=>{Wn("end-profiling",[pe,we]);let $e={type:"end-profiling",in:oe};Qe.postMessage($e)});or(oe)}}),rc,Fo,dl,sc=d(()=>{xn(),gd(),Ht(),Wi(),Hs(),rc=(oe,pe)=>{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 ${pe()}`)}},Fo=oe=>{switch(oe[3]){case"cpu":return new ge(oe[0],oe[2],oe[1]);case"gpu-buffer":{let pe=oe[0];if(!Gs(pe))throw new Error(`not supported data type: ${pe} for deserializing GPU tensor`);let{gpuBuffer:we,download:$e,dispose:Ee}=oe[2];return ge.fromGpuBuffer(we,{dataType:pe,dims:oe[1],download:$e,dispose:Ee})}case"ml-tensor":{let pe=oe[0];if(!kr(pe))throw new Error(`not supported data type: ${pe} for deserializing MLTensor tensor`);let{mlTensor:we,download:$e,dispose:Ee}=oe[2];return ge.fromMLTensor(we,{dataType:pe,dims:oe[1],download:$e,dispose:Ee})}default:throw new Error(`invalid data location: ${oe[3]}`)}},dl=class{async fetchModelAndCopyToWasmMemory(oe){return Lo(await ni(oe))}async loadModel(oe,pe){pt();let we;typeof oe=="string"?we=await this.fetchModelAndCopyToWasmMemory(oe):we=oe,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ws(we,pe),ot()}async dispose(){return Bu(this.sessionId)}async run(oe,pe,we){pt();let $e=[],Ee=[];Object.entries(oe).forEach(rt=>{let Je=rt[0],Pt=rt[1],Fe=this.inputNames.indexOf(Je);if(Fe===-1)throw new Error(`invalid input '${Je}'`);$e.push(Pt),Ee.push(Fe)});let Ge=[],Re=[];Object.entries(pe).forEach(rt=>{let Je=rt[0],Pt=rt[1],Fe=this.outputNames.indexOf(Je);if(Fe===-1)throw new Error(`invalid output '${Je}'`);Ge.push(Pt),Re.push(Fe)});let Ie=$e.map((rt,Je)=>rc(rt,()=>`input "${this.inputNames[Ee[Je]]}"`)),He=Ge.map((rt,Je)=>rt?rc(rt,()=>`output "${this.outputNames[Re[Je]]}"`):null),it=await zo(this.sessionId,Ee,Ie,Re,He,we),lt={};for(let rt=0;rt<it.length;rt++)lt[this.outputNames[Re[rt]]]=Ge[rt]??Fo(it[rt]);return ot(),lt}startProfiling(){}endProfiling(){Bo(this.sessionId)}}}),Vs={};p(Vs,{OnnxruntimeWebAssemblyBackend:()=>qs,initializeFlags:()=>po,wasmBackend:()=>Go});var po,qs,Go,vd=d(()=>{xn(),gd(),sc(),po=()=>{(typeof M.wasm.initTimeout!="number"||M.wasm.initTimeout<0)&&(M.wasm.initTimeout=0);let oe=M.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.`),M.wasm.simd=!1),typeof M.wasm.proxy!="boolean"&&(M.wasm.proxy=!1),typeof M.wasm.trace!="boolean"&&(M.wasm.trace=!1),typeof M.wasm.numThreads!="number"||!Number.isInteger(M.wasm.numThreads)||M.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)M.wasm.numThreads=1;else{let pe=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;M.wasm.numThreads=Math.min(4,Math.ceil((pe||1)/2))}},qs=class{async init(oe){po(),await ts(),await ho(oe)}async createInferenceSessionHandler(oe,pe){let we=new dl;return await we.loadModel(oe,pe),we}},Go=new qs}),xd={};p(xd,{InferenceSession:()=>Ze,TRACE:()=>ye,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>at,TRACE_FUNC_BEGIN:()=>pt,TRACE_FUNC_END:()=>ot,Tensor:()=>ge,default:()=>ac,env:()=>M,registerBackend:()=>w}),xn(),xn(),xn();var oc="1.26.0",ac=wr;{let oe=(vd(),f(Vs)).wasmBackend;w("cpu",oe,10),w("wasm",oe,10)}return Object.defineProperty(M.versions,"web",{value:oc,enumerable:!0}),f(xd)})();n.exports=i})(Tw)),Tw.exports}var Mk;function rR(){return Mk||(Mk=1,(function(n){var e=Rl&&Rl.__createBinding||(Object.create?(function(E,T,N,$){$===void 0&&($=N);var R=Object.getOwnPropertyDescriptor(T,N);(!R||("get"in R?!T.__esModule:R.writable||R.configurable))&&(R={enumerable:!0,get:function(){return T[N]}}),Object.defineProperty(E,$,R)}):(function(E,T,N,$){$===void 0&&($=N),E[$]=T[N]})),i=Rl&&Rl.__setModuleDefault||(Object.create?(function(E,T){Object.defineProperty(E,"default",{enumerable:!0,value:T})}):function(E,T){E.default=T}),r=Rl&&Rl.__importStar||function(E){if(E&&E.__esModule)return E;var T={};if(E!=null)for(var N in E)N!=="default"&&Object.prototype.hasOwnProperty.call(E,N)&&e(T,E,N);return i(T,E),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(iR()),a=f1(),c=m1(),l=fv(),d=Ly(),p=cT(),m=dT();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",x="silero_vad_v5.onnx",y="silero_vad_legacy.onnx",w=E=>({...c.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:E,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=w;const k=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(E,T,N,$,R){await N.audioWorklet.addModule(E),T.processorOptions={...T.processorOptions??{},frameSamples:$};const M=new AudioWorkletNode(N,"vad-helper-worklet",T);return M.port.onmessage=async z=>{const V=z.data;if(!(typeof V=="object"&&V&&"message"in V)){console.error("Invalid message event",V);return}switch(V.message){case d.Message.AudioFrame:{if(!("data"in V&&V.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const H=new Float32Array(V.data);await R(H);break}}},M}async function _(E,T,N){const $=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const M=E.createScriptProcessor(4096,1,1);let z=!1;return M.onaudioprocess=async V=>{if(!z){z=!0;try{const H=V.inputBuffer.getChannelData(0);V.outputBuffer.getChannelData(0).fill(0);const X=$.process(H);for(const q of X)await N(q)}catch(H){console.error("Error processing audio:",H)}finally{z=!1}}},M.connect(E.destination),M}class S{constructor(T,N,$,R,M=!1,z=null,V=null,H=null,Q=null,X=null,q=null,J="uninitialized",ee=!1){this.options=T,this.frameProcessor=N,this.model=$,this.frameSamples=R,this.listening=M,this.errored=z,this._stream=V,this._audioContext=H,this._vadNode=Q,this._mediaStreamAudioSourceNode=X,this._audioProcessorAdapterType=q,this.initializationState=J,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=ie=>{this.initializationState="errored",this.errored=ie},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(ie){throw ie instanceof Error?this.setErrored(ie.message):this.setErrored(String(ie)),ie}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 b(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await _(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:ie,audioContext:re,vadNode:B}=this.getAudioInstances();this._stream=await this.options.resumeStream(ie);const Z=new MediaStreamAudioSourceNode(re,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Z,Z.connect(B);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:ie,mediaStreamAudioSourceNode:re}=this.getAudioInstances();await this.options.pauseStream(ie),re.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var re;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:ie}=this.getAudioInstances();ie instanceof AudioWorkletNode&&ie.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((re=this._audioContext)==null?void 0:re.close())},this.setOptions=ie=>{this.frameProcessor.setOptions(ie)},this.processFrame=async ie=>{await this.frameProcessor.process(ie,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=ie=>{switch(ie.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(ie.probs,ie.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(ie.audio);break}}}static async new(T={}){const N={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,c.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const $=N.model==="v5"?x:y,R=N.baseAssetPath+$,M=N.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let z;try{z=await M(n.ort,()=>(0,a.defaultModelFetcher)(R))}catch(q){throw console.error(`Encountered an error while loading model file ${R}`),q}const V=N.model==="v5"?512:1536,H=V/16,Q=new c.FrameProcessor(z.process,z.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},H),X=new S(N,Q,z,V);if(N.startOnLoad)try{await X.start()}catch(q){throw console.error("Error starting micVad",q),q}return X}}n.MicVAD=S})(Rl)),Rl}var Ok;function sR(){return Ok||(Ok=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=oT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=f1();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=m1();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=Ly();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=tR();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const c=nR();n.utils={audioFileToArray:c.audioFileToArray,minFramesForTargetMS:c.minFramesForTargetMS,arrayBufferToBase64:c.arrayBufferToBase64,encodeWAV:c.encodeWAV};var l=rR();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}})})(Cw)),Cw}var oR=sR();function Tx(n,e,i,r,s){var c,l;try{(l=(c=window.api)==null?void 0:c.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 mt={debug:(n,e,i)=>Tx(n,"debug",e,i),info:(n,e,i)=>Tx(n,"info",e,i),warn:(n,e,i)=>Tx(n,"warn",e,i),error:(n,e,i,r)=>Tx(n,"error",e,i,r)},hT=16e3,aR=6,wp=hT*aR,lR=400,cR=hT*lR/1e3,Lk=300,zk=2e3,Bk=1500,Fk=3e3,dR=600,pT=.5,fT=.35,Gk=.85,Hk=.7;let Rs=null,Qa=!1,ps=!1;const B_=new Set;function Nx(n){for(const e of Array.from(B_))try{e(n)}catch(i){mt.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let Nw=0;const Uk=2;let Lp=!1,mT=!1;function gT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";mt[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{mt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),uR(`error:${e.message||"unknown"}`)})}function Xb(){return Rs||(Rs=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),gT(Rs),mt.info("speech","worker spawned"),Rs)}let Dx=!1;function uR(n){if(!Lp){if(Dx){mt.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(Dx=!0,Nw+=1,mT=!0,mt.warn("speech","respawnWorker: starting",{reason:n,attempt:Nw}),Nx({reason:n,respawned:!1,finalOnly:!0}),Nw>Uk){if(Lp=!0,mt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Uk}),Rs)try{Rs.terminate()}catch{}Rs=null,Qa=!1,ps=!1,Nx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),Dx=!1;return}if(Rs)try{Rs.terminate()}catch{}Rs=null,Qa=!1,ps=!1;try{Rs=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),gT(Rs),ps=!0,Rs.postMessage({type:"load"}),mt.info("speech","respawnWorker: new worker spawned, load posted"),Nx({reason:n,respawned:!0,finalOnly:!0})}catch(e){Lp=!0,mt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),Nx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{Dx=!1}}}function hR(n,e){if(Qa||ps)return;ps=!0;const i=Xb();mt.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"&&(Qa=!0,ps=!1,mt.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(ps=!1,mt.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 pR(){mt.info("speech","resetModel: clearing load flags"),Qa=!1,ps=!1}function zy(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function fR(n){const e=Xb();return!Qa&&!ps&&(ps=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var c,l,d;((c=a.data)==null?void 0:c.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")))):((d=a.data)==null?void 0:d.type)==="status"&&a.data.status==="ready"&&(Qa=!0,ps=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function vT(n){let e=Xb(),i=!1,r=null,s=null,a=null,c=null,l=null;const d=[],p=new Set;let m=null,f=0,x=!1,y=0,w=!1,k=!1,b=0,_=0,S=0,E=-1,T=Lk,N=0,$=null,R="",M="",z=!1,V=0;function H(ae,fe){const Te=Math.min(ae.length,fe.length);let Ne=0;for(;Ne<Te&&ae.charCodeAt(Ne)===fe.charCodeAt(Ne);)Ne++;return Ne}function Q(ae){const fe=H(R,ae);return R=ae,fe>M.length&&(M=ae.slice(0,fe)),M.length>ae.length&&(M=ae),M}const X=()=>(m||(m=new Float32Array(wp)),m),q=()=>{f=0},J=ae=>{const fe=X(),Te=ae.length;if(Te>=wp){fe.set(ae.subarray(Te-wp)),f=wp;return}if(f+Te<=wp){fe.set(ae,f),f+=Te;return}const Ne=f+Te-wp;fe.copyWithin(0,Ne,f),f-=Ne,fe.set(ae,f),f+=Te},ee=()=>{$&&(clearTimeout($),$=null)},ie=()=>{ee(),x=!1,w=!1,k=!1,T=Lk,R="",M="",z=!1,V=0,q()},re=()=>{if(i||!x||k||w||$)return;if(f<cR){$=setTimeout(()=>{$=null,re()},T);return}const ae=performance.now()-b;if(ae<T&&b!==0){$=setTimeout(()=>{$=null,re()},T-ae);return}if(mT||Lp||n.partialsEnabled&&!n.partialsEnabled())return;const fe=X(),Te=new Float32Array(f);Te.set(fe.subarray(0,f)),_+=1,S=_,w=!0,N=performance.now(),b=N,e.postMessage({type:"transcribe-partial",audio:Te,seq:_},[Te.buffer])},B=ae=>ae.length===0?Promise.resolve():Lp?(mt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(fe=>{d.push(fe),_+=1;const Te=_;E=Te,e.postMessage({type:"transcribe",audio:ae,seq:Te},[ae.buffer])}),Z=ae=>{const fe=B(ae);return p.add(fe),fe.finally(()=>{p.delete(fe)}),fe},W=ae=>{var fe,Te,Ne,me,se;if(ae.data.type==="result"){const Ae=ae.data.text,ge=ae.data.seq??0;ge&&ge<E&&mt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ge,latestFinalSeq:E}),!i&&Ae&&n.onFinal(Ae),(fe=d.shift())==null||fe()}else if(ae.data.type==="partial"){const Ae=ae.data.seq??0,ge=ae.data.text??"",Se=performance.now()-N;w=!1,Se>=Fk?(k=!0,mt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Se),seq:Ae})):Se>=Bk&&(T=Math.min(T*2,zk),mt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Se),newIntervalMs:T,seq:Ae})),z||(z=!0,Se>dR&&T<500&&(T=500,mt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Se),newIntervalMs:500})));const ye=Ae!==S||Ae<=E;if(!i&&!ye&&ge){const et=Q(ge);et&&((Te=n.onPartial)==null||Te.call(n,et),V===0&&(V=performance.now(),mt.info("speech","partial.first",{msSinceSpeechStart:Math.round(V-y)})))}re()}else if(ae.data.type==="partial-error"){const Ae=performance.now()-N;w=!1,Ae>=Fk?(k=!0,mt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ae),seq:ae.data.seq})):Ae>=Bk&&(T=Math.min(T*2,zk),mt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ae),newIntervalMs:T,seq:ae.data.seq})),mt.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),re()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(Ne=d.shift())==null||Ne()):ae.data.type==="status"?(i||(me=n.onModelStatus)==null||me.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(Qa=!0,ps=!1)):ae.data.type==="progress"&&(i||(se=n.onProgress)==null||se.call(n,ae.data.pct))};e.addEventListener("message",W);const le=ae=>{var fe,Te;if(!i){for(mt.warn("speech","createRecognition: worker death event",ae),(fe=n.onStatusChange)==null||fe.call(n,"restarting");d.length;)(Te=d.shift())==null||Te();if(p.clear(),ee(),w=!1,ae.respawned){try{e.removeEventListener("message",W)}catch{}e=Xb(),e.addEventListener("message",W)}}};return B_.add(le),{start:async()=>{if(!i){if(Lp){n.onError("Speech recognition disabled — please reload the app.");return}!Qa&&!ps&&(ps=!0,mt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),mt.info("speech","createRecognition.start: initializing VAD",{modelReady:Qa,modelLoading:ps});try{const ae=new URL("vad/",document.baseURI).href,fe=n.inputDeviceId||null,Te={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};fe&&(Te.deviceId={exact:fe}),mt.info("speech","getUserMedia",{hasDeviceId:!!fe,deviceIdPrefix:fe?fe.slice(0,8):null});const Ne=await navigator.mediaDevices.getUserMedia({audio:Te});s=Ne,a=new AudioContext;for(const me of Ne.getAudioTracks())me.addEventListener("ended",()=>{i||(mt.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),c=a.createAnalyser(),c.fftSize=2048,c.smoothingTimeConstant=.3,l.connect(c)}catch(me){mt.warn("speech","analyser init failed",{error:me instanceof Error?me.message:String(me)}),l=null,c=null}r=await oR.MicVAD.new({audioContext:a,getStream:async()=>Ne,resumeStream:async()=>Ne,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:pT,negativeSpeechThreshold:fT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(me,se)=>{var Ae;i||((Ae=n.onFrame)==null||Ae.call(n,me),x&&(J(se),re()))},onSpeechStart:()=>{var me;i||(ie(),x=!0,y=performance.now(),(me=n.onSpeechStart)==null||me.call(n))},onSpeechEnd:me=>{var se;i||((se=n.onStatusChange)==null||se.call(n,"transcribing"),ie(),Z(me))},onVADMisfire:()=>{var me,se;i||((me=n.onStatusChange)==null||me.call(n,"idle"),ie(),(se=n.onMisfire)==null||se.call(n))}}),r.start()}catch(ae){const fe=ae instanceof Error?ae.message:"Microphone access denied",Te=ae instanceof Error?ae.stack:"";if(mt.error("speech","createRecognition.start: VAD init failed",{error:fe,stack:Te}),c){try{c.disconnect()}catch{}c=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Ne=>Ne.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(fe)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(ie();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(c){try{c.disconnect()}catch{}c=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,fe)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:fe})}catch(Te){mt.warn("speech","setVadThresholds failed",{error:Te instanceof Error?Te.message:String(Te)})}},getAnalyser:()=>c,destroy:()=>{if(i=!0,ie(),r){try{r.destroy()}catch{}r=null}if(c){try{c.disconnect()}catch{}c=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}B_.delete(le),e.removeEventListener("message",W)}}}let Mg=null;const F_=new Set,G_=new Set;function mR(){for(const n of F_)try{n()}catch{}}function H_(){for(const n of G_)try{n()}catch{}}function gR(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 vR(n){if(!window.speechSynthesis)return;const e=gR(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{Mg=performance.now(),mR()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Mg=null,H_())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Mg=null,H_())},window.speechSynthesis.speak(i)}function xT(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Mg=null,H_())}function bT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function xR(){return Mg}function bR(n){return F_.add(n),()=>{F_.delete(n)}}function yR(n){return G_.add(n),()=>{G_.delete(n)}}function wR(n){bT()&&(n.setVadThresholds(Gk,Hk),mt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=bR(()=>{n.setVadThresholds(Gk,Hk),mt.info("voice","tts.duck.on")}),i=yR(()=>{n.setVadThresholds(pT,fT),mt.info("voice","tts.duck.off")});return()=>{e(),i()}}const _R=[{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 SR(n){const e=n.trim();return _R.find(i=>i.match.test(e))??null}const kR=4e4;let ku=null;function zp(){ku&&clearTimeout(ku),ku=setTimeout(()=>{ku=null,Ct.getState().stopRecording()},kR)}function Ax(){ku&&(clearTimeout(ku),ku=null)}let ad=null,td=null;const CR=.04,ER=.3;let Jb=0,U_=0;function jR(n){td!==null&&cancelAnimationFrame(td);const e=()=>{if(ad===null||Ct.getState().submitCountdownStartAt===null){td=null;return}const i=performance.now();if(i-U_<200&&Jb>ER){const s=i-n;mt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Jb.toFixed(2),msIntoCountdown:Math.round(s)}),Xc(),zp();return}const r=yT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const d=(s[l]-128)/128;a+=d*d}const c=Math.sqrt(a/s.length);if(c>CR){const l=i-n;mt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:c.toFixed(3),msIntoCountdown:Math.round(l)}),Xc(),zp();return}}td=requestAnimationFrame(e)};td=requestAnimationFrame(e)}function Wk(n){ad&&clearTimeout(ad);const e=Ct.getState().submitDelayMs,i=performance.now();Ct.setState({submitCountdownStartAt:i}),ad=setTimeout(()=>{var s;ad=null,Ct.setState({submitCountdownStartAt:null});const r=xt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=mn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(mn.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),mn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){mt.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}zp()},e),jR(i)}function Xc(){td!==null&&(cancelAnimationFrame(td),td=null),ad&&(clearTimeout(ad),ad=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let br=null,Kr=null,eg=null;function yT(){var n;return((n=br==null?void 0:br.getAnalyser)==null?void 0:n.call(br))??null}const $x=1e4;let Og=null;function Px(){Og&&(clearTimeout(Og),Og=null)}let Sb=null,kb=null;function Rx(){Sb=null,kb&&(kb(),kb=null)}const TR=1500,NR=9e4;let Ix=0,Cb=null,W_=-1;function Mx(){Cb&&(clearTimeout(Cb),Cb=null,W_=-1)}const DR=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=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;mt.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++Ix,r=()=>{i===Ix&&(Mx(),W_=i,Cb=setTimeout(()=>{W_===i&&e().modelStatus==="loading"&&(mt.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},NR))};r(),hR((s,a)=>{i===Ix&&(s==="ready"?(Mx(),mt.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Mx(),mt.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===Ix&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{mt.info("voice","mic.gate.retry"),Mx(),pR(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(br){mt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!zy()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const c=vT({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=>{Jb=l.isSpeech,U_=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),Ax(),Xc(),bT()){const d=xR(),p=d!==null?performance.now()-d:null;xT(),n({lastBargeInAt:performance.now()}),mt.info("voice","barge-in",{tabId:i,utteranceOffsetMs:p})}else mt.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),zp();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&mt.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var x;zp();const d=l.trim();if(!d||DR.has(d)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(eg){eg(d),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((x=xt.getState().tabs.find(y=>y.id===i))==null?void 0:x.status)==="dormant"){mn.getState().setPendingVoiceText(i,d),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Wk(i);const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:d}),y.__transcripts.length>500&&y.__transcripts.shift());return}const m=SR(d);if(m){mt.info("voice","voice-command",{tabId:i,label:m.label,transcript:d}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Xc();const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:d}),y.__transcripts.length>500&&y.__transcripts.shift());return}window.api.pty.write({tabId:i,data:d}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Wk(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:d}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{mt.error("voice","recognition error",{err:l}),Xc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Kr==null||Kr(),Kr=null,Ax(),br==null||br.destroy(),br=null,eg=null,Me.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)})});br=c,eg=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),zp(),c.start().then(()=>{br===c&&(Kr==null||Kr(),Kr=wR(c))}).catch(l=>{const d=l instanceof Error?l.message:String(l);mt.error("voice","handle.start() failed",{error:d}),Me.error(`Could not start mic: ${d}`)})}catch(c){n({error:c instanceof Error?c.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,c,l;return((l=(c=(a=window.api)==null?void 0:a.voice)==null?void 0:c.getDevicePref)==null?void 0:l.call(c))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{mt.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=br;i&&(Ax(),Xc(),Jb=0,U_=0,Kr==null||Kr(),Kr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),br===i&&(br=null,eg=null),e().hotkeyState==="stopping"&&(Px(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=br;if(!i)return;Ax(),Kr==null||Kr(),Kr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){mt.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),br===i&&(br=null);const{useSessions:r}=await pv(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>DP);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:()=>Xc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(mt.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"?mt.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?mt.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&mt.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 c=e(),{canRecord:l,reason:d}=Zb(c);if(i==="down"){if(d==="error"||d==="load-timeout"){c.resetAndRetryModel(),mt.info("voice-hotkey","down.retry",{source:r,reason:d});return}if(!l&&d!=="loading"){mt.warn("voice-hotkey","miss-model-loading",{modelStatus:c.modelStatus,reason:d});return}if(c.hotkeyState==="recording"||c.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),Px(),Og=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:$x}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},$x),c.stopRecording());return}if(d==="loading"){c.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),mt.info("voice-hotkey","armed",{source:r,modelStatus:c.modelStatus})),Rx(),Sb={tabId:a,source:r,mode:s},kb=Ct.subscribe((p,m)=>{if(Sb&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=Sb;if(Rx(),!f.tabId){mt.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}mt.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),Ct.getState().startRecording(f.tabId)}});return}if(!a){mt.warn("voice-hotkey","no-active-tab",{source:r});return}mt.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),c.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(mt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(c.hotkeyState==="armed"){Rx(),mt.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}c.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),Px(),Og=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:$x}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},$x),c.stopRecording())}},destroyHotkey:()=>{const i=e();if(Rx(),Xc(),i.hotkeyState==="recording"){mt.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(Px(),n({hotkeyState:"destroyed"}))}})),AR=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),Zb=n=>zy()?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=Ct,n.__transcripts=[]}const $R=6e4,PR=5e3,Lg=Ti(()=>({data:null,refreshing:!1}));let Vk=!1,Eb=null,qk=null,Kk=!1;async function g1(){Lg.setState({refreshing:!0});let n=$R;try{const e=await o1(window.api.billing.fetch(),PR,"billing.fetch");Lg.setState({data:e,refreshing:!1}),e.kind==="transient"?n=qk==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),qk=e.kind}catch(e){if(Lg.setState({refreshing:!1}),!Kk){Kk=!0;const i=e instanceof Error?e.message:String(e);Me.warn(`Billing usage fetch failed: ${i}`)}}Eb=setTimeout(g1,n)}function RR(){Vk||(Vk=!0,g1())}function wT(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 IR(){Eb!==null&&(clearTimeout(Eb),Eb=null),g1()}function sf(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 Ox=new Map,MR=3e4;function v1(n){const[e,i]=P.useState(()=>{var r;return n?((r=Ox.get(n))==null?void 0:r.value)??null:null});return P.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=Ox.get(n);if(a&&Date.now()-a.ts<MR){r||i(a.value);return}try{const c=await window.api.app.gitBranch(n);if(r)return;Ox.set(n,{value:c,ts:Date.now()}),i(c)}catch{if(r)return;Ox.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function OR(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 V_="sm.almanac.sidebarWidth",_T=180,ST=480,q_=252;function LR(){try{const n=parseInt(localStorage.getItem(V_)??"",10);if(Number.isFinite(n))return Math.min(ST,Math.max(_T,n))}catch{}return q_}const zR=52,kT="sm.almanac.sidebarCollapsed";function BR(){try{return localStorage.getItem(kT)==="1"}catch{}return!1}const CT="sm.almanac.collapsedGroups";function FR(){try{const n=localStorage.getItem(CT);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 GR(){const n=xt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:Jr(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function HR({active:n,onNavigate:e,onNewSession:i}){const[r,s]=P.useState(()=>FR()),a=P.useCallback(R=>{s(M=>{const z=new Set(M);z.has(R)?z.delete(R):z.add(R);try{localStorage.setItem(CT,JSON.stringify(Array.from(z)))}catch{}return z})},[]),[c,l]=P.useState(()=>BR()),d=P.useCallback(()=>{l(R=>{const M=!R;try{localStorage.setItem(kT,M?"1":"0")}catch{}return M})},[]),p=xt(R=>R.tabs),m=xt(R=>R.activeTabId),f=p.find(R=>R.id===m)??null,x=GR(),y=gn(R=>R.navFace),w=zP(y),k=w.filter(R=>R.group==="Workspace"),b=w.filter(R=>R.group==="Configure"),_=OR(w),[S,E]=P.useState(()=>LR()),T=P.useRef(S);T.current=S;const N=P.useCallback(R=>{R.preventDefault();const M=R.clientX,z=T.current;let V=z;const H=X=>{V=Math.min(ST,Math.max(_T,z+(X.clientX-M))),E(V)},Q=()=>{window.removeEventListener("pointermove",H),window.removeEventListener("pointerup",Q),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(V_,String(V))}catch{}};window.addEventListener("pointermove",H),window.addEventListener("pointerup",Q),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),$=P.useCallback(()=>{E(q_);try{localStorage.setItem(V_,String(q_))}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:c?zR:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(UR,{tab:f,navFace:y,onNewSession:i,rail:c,onToggleRail:d}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:c?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!c&&o.jsx(Dw,{label:"Workspace",desc:kw.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(c||!r.has("Workspace"))&&k.map(R=>o.jsx(Yk,{item:R,active:n===R.key,live:R.liveKind?x[R.liveKind]:!1,onClick:()=>e(R.key),rail:c},R.key)),!c&&o.jsx(Dw,{label:"Configure",desc:kw.Configure,collapsed:r.has("Configure"),count:b.length,onToggle:()=>a("Configure")}),(c||!r.has("Configure"))&&b.map(R=>o.jsx(Yk,{item:R,active:n===R.key,live:!1,onClick:()=>e(R.key),rail:c},R.key)),_.length>0&&!c&&o.jsx(Dw,{label:"Tools",desc:kw.Tools,collapsed:r.has("Tools"),count:_.length,onToggle:()=>a("Tools")}),_.length>0&&(c||!r.has("Tools"))&&_.map(R=>o.jsx(WR,{tool:R,active:n===R.key,onClick:()=>e(R.key),rail:c},R.key))]})}),o.jsx(VR,{rail:c,navFace:y}),!c&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:$,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 UR({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",c=v1((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(an,{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(an,{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(an,{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(an,{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(an,{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:c?`⌥${c}`: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(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Dw({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 Yk({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(an,{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 WR({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(an,{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 VR({rail:n,navFace:e}){const i=Ct(d=>d.isRecording),r=xt(d=>d.tabs),s=xt(d=>d.activeTabId),a=r.find(d=>d.id===s)??null,[c,l]=P.useState(null);return P.useEffect(()=>{let d=!1;if(!(a!=null&&a.presetId)){l(null);return}return Vj(a.presetId).then(p=>{d||l((p==null?void 0:p.model)??null)}).catch(()=>{d||l(null)}),()=>{d=!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:c??"",children:i?"recording…":c?`Claude · ${sf(c)}`:"Claude Code"})]})}function qR(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function KR(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 jb=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]:KR(i,r,s)}});const c=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:c}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const d=e().tabs[i];if(!d)return;if(!l.ok){const{toast:m}=await pv(async()=>{const{toast:f}=await Promise.resolve().then(()=>Xj);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...d,path:null}}});return}n({tabs:{...e().tabs,[i]:{...d,path:l.path}}});const p=await window.api.transcripts.buffer(i);for(const m of p)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 c={...e().tabs};delete c[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:c})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const c=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:c},d=[],p=(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||d.push({id:0,kind:"todo-update",at:c,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,x={};for(const y of["command","file_path","pattern","url","query","subagent_type","description"])f&&y in f&&(x[y]=f[y]);if(l.lastToolUses=[{id:m.id,name:m.name,input:x,at:c},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const y=m.input,w=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(y==null?void 0:y.file_path)=="string"?y.file_path:void 0,b=typeof(y==null?void 0:y.command)=="string"?y.command:void 0,_=k?k.split("/").pop()??k:b?p(b,28):"";d.push({id:0,kind:"tool-use",at:c,label:_?`${m.name} · ${_}`:m.name,target:k??b,toolName:m.name}),w&&k&&d.push({id:0,kind:"file-edit",at:c,label:`${m.name} · ${p(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:c,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"plan-revision",at:c,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:c,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:c},...a.agents].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"agent-spawn",at:c,label:m!=null&&m.subagent_type?`Agent: ${p(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),x=m.input_tokens??m.inputTokens??0,y=m.output_tokens??m.outputTokens??0,w=f+x+y;l.usage={inputTokens:(a.usage.inputTokens||0)+x,outputTokens:(a.usage.outputTokens||0)+y,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(w/1e3)>Math.floor(f/1e3)&&d.push({id:0,kind:"usage-tick",at:c,label:`${Math.floor(w/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=qR(a.agents,m==null?void 0:m.toolUseId,c);break}}if(d.length>0){let m=a.activitySeq;const f=d.map(x=>({...x,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function YR(n){const e=jb(s=>s.subscribe),i=jb(s=>s.unsubscribe),r=jb(s=>n?s.tabs[n.id]:void 0);return P.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 XR({onNavigate:n}){const e=xt(E=>E.tabs),i=xt(E=>E.activeTabId),r=e.find(E=>E.id===i)??null,s=YR(r),a=(s==null?void 0:s.lastEventAt)??0,c=Lg(E=>E.data),l=Jr(E=>{var T;return((T=E.snapshot)==null?void 0:T.paused)??null}),d=v1((r==null?void 0:r.cwd)??null),[,p]=P.useState(0);P.useEffect(()=>{const E=setInterval(()=>p(T=>T+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,x]=P.useState(!1),y=P.useRef(null);P.useEffect(()=>{if(!f)return;const E=T=>{y.current&&!y.current.contains(T.target)&&x(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),P.useEffect(()=>{m.length===0&&x(!1)},[m.length]);const w=wT(c),k=(w==null?void 0:w.usage.five_hour)??null,b=k?Math.round(k.utilization):null,_=(c==null?void 0:c.kind)==="ok"||(c==null?void 0:c.kind)==="ok-stale",S=a>0?QR(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:_?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:_?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:b!=null?`${b}% 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,d&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(JR,{ref:y,todos:m,open:f,onToggle:()=>x(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.60.0"]})]})}const JR=P.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(c=>c.status==="completed").length,in_progress:e.filter(c=>c.status==="in_progress").length,pending:e.filter(c=>c.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((c,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${c.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(ZR,{status:c.status}),o.jsx("span",{className:c.status==="completed"?"text-fg-faint line-through":c.status==="in_progress"?"text-fg":"text-fg-dim",children:c.status==="in_progress"&&c.activeForm?c.activeForm:c.content})]},l))})})]})});function ZR({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 QR(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 eI({onClose:n,onSent:e}){const i=xt(R=>R.tabs),[r,s]=P.useState(""),[a,c]=P.useState(()=>Object.fromEntries(i.map(R=>[R.id,!0]))),[l,d]=P.useState(!1),[p,m]=P.useState({}),f=P.useRef(null),x=P.useRef(e);P.useEffect(()=>{x.current=e},[e]),P.useEffect(()=>{c(R=>{const M={};for(const z of i)M[z.id]=R[z.id]??!0;return M})},[i]),P.useEffect(()=>{var R;(R=f.current)==null||R.focus()},[]),P.useEffect(()=>window.api.pty.onWriteError(M=>{m(z=>M.tabId in z?{...z,[M.tabId]:"skipped"}:z)}),[]),P.useEffect(()=>{if(Object.keys(p).length===0)return;const R=Object.values(p).filter(z=>z==="sent").length,M=window.setTimeout(()=>x.current(R),1500);return()=>window.clearTimeout(M)},[p]);const y=i.filter(R=>a[R.id]).map(R=>R.id),w=y.length,k=Object.keys(p).length>0,b=r.length>0&&w>0&&!l&&!k,_=()=>{if(!b)return;d(!0);const R=xt.getState().tabs,M=new Set(R.map(V=>V.id)),z={};for(const V of y)M.has(V)?(window.api.pty.write({tabId:V,data:r+"\r"}),z[V]="sent"):z[V]="skipped";m(z),d(!1)},S=R=>{if(R.key==="Escape"){R.preventDefault(),R.stopPropagation(),n();return}R.key==="Enter"&&(R.metaKey||R.ctrlKey)&&(R.preventDefault(),_())},E=i.length>0&&i.every(R=>a[R.id]),T=()=>{const R=!E;c(Object.fromEntries(i.map(M=>[M.id,R])))},N=Object.values(p).some(R=>R==="skipped"),$=k?N?"Sent (some skipped)":"Sent":`Send to ${w} tab${w===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:R=>s(R.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:E,onChange:T,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",w,"/",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(R=>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[R.id],onChange:M=>c(z=>({...z,[R.id]:M.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:R.label}),p[R.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[R.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},R.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:_,disabled:!b,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:$})]})]})}function tI({tabId:n,cwd:e,onClose:i}){const r=Ig(w=>w.watchersForTab(n)),s=Ig(w=>w.add),a=Ig(w=>w.remove),c=P.useRef(null),[l,d]=P.useState(""),[p,m]=P.useState(""),[f,x]=P.useState(!1);P.useEffect(()=>{const w=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[i]),P.useEffect(()=>{const w=k=>{c.current&&!c.current.contains(k.target)&&i()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[i]);const y=async()=>{const w=p.trim();if(!w||f)return;x(!0);const k=await s({tabId:n,label:l.trim(),command:w,cwd:e});x(!1),k&&(d(""),m(""))};return o.jsxs("div",{ref:c,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:w=>d(w.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:p,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&y()},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:y,disabled:!p.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(w=>{const k=w.lines[w.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:w.label}),o.jsxs("span",{className:"text-fg-faint",children:[w.lineCount," line",w.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(w.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${w.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:w.command,children:w.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…"})})]},w.watcherId)})})]})}/**
2911
2911
  * dockview-core
2912
2912
  * @version 6.6.1
2913
2913
  * @link https://github.com/mathuo/dockview
@@ -3075,7 +3075,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3075
3075
 
3076
3076
  ${i}`}const Ng={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},iB=["popover","review","diff"],rD=["popover","review"];function rB(n,e){switch(e.type){case"SELECT":return{...Ng,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Ng,editCount:n.editCount};case"LISTEN":return rD.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 iB.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:{...Ng,editCount:n.editCount+1};case"RESET_FILE":return{...Ng,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function sB(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 oB(n,e,i){var a;let r=null,s=-1/0;for(const c of e){if(c.cwd!==n||c.status!=="dormant")continue;const l=((a=i[c.id])==null?void 0:a.lastEventAt)??0;(r===null||l>s)&&(r=c,s=l)}return r}const aB="sonnet";function lB(n,e){const[i,r]=P.useReducer(rB,Ng),s=P.useRef(0),a=P.useRef(null),c=P.useRef(n),l=P.useRef(new Map);P.useEffect(()=>window.api.docEdit.onSessionResult(E=>{const T=l.current.get(E.requestId);T&&(l.current.delete(E.requestId),T(E))}),[]),P.useEffect(()=>{c.current!==n&&(c.current=n,s.current+=1,d(),r({type:"RESET_FILE"}))},[n]);function d(){const E=a.current;E&&(a.current=null,E.stop().catch(()=>{}),E.destroy(),Ct.setState({externalRecording:!1}))}const p=P.useCallback(E=>{s.current+=1,d(),r({type:"SELECT",selection:E})},[]),m=P.useCallback(()=>{s.current+=1,d(),r({type:"CANCEL"})},[]),f=P.useCallback(()=>{if(!rD.includes(i.phase))return;if(Ct.getState().isRecording){Me.error("Microphone is already in use");return}if(!zy()){Me.error("Microphone or Web Worker not available");return}const E=++s.current;r({type:"LISTEN"}),Ct.setState({externalRecording:!0});const T=()=>{a.current===N&&(a.current=null),Ct.setState({externalRecording:!1})},N=vT({onFinal:$=>{if(s.current!==E)return;N.stop().catch(()=>{}),N.destroy(),T();const R=$.trim();if(!R){r({type:"CANCEL"});return}r({type:"HEARD",transcript:R})},onError:$=>{s.current===E&&(N.destroy(),T(),Me.error(`Microphone error: ${$}`),r({type:"CANCEL"}))},onModelStatus:($,R)=>{s.current===E&&r({type:"MODEL_STATUS",status:$,message:R})},onProgress:$=>{s.current===E&&r({type:"MODEL_STATUS",status:"loading",message:`${$}%`})}});a.current=N,N.start().catch($=>{s.current===E&&(N.destroy(),T(),Me.error(`Could not start mic: ${$ instanceof Error?$.message:String($)}`),r({type:"CANCEL"}))})},[i.phase]),x=P.useCallback(()=>{const E=sB(n,xt.getState().tabs);if(!E)return null;const T=oB(E,xt.getState().tabs,jb.getState().tabs);return!T||mn.getState().get(T.id).running?null:T},[n]),y=P.useCallback((E,T,N,$,R,M)=>{const z=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(V=>{l.current.set(z,V),window.api.docEdit.runInSession({tabId:E,sessionId:T,cwd:N,before:$,instruction:R,documentText:M,requestId:z})})},[]),w=P.useCallback(async(E,T)=>{const N=i.selection;if(!N)return;const $=++s.current;r({type:"RUN",instruction:E,recordInstruction:T});const R=nB(e);try{const M=x(),z=M?await y(M.id,M.sessionId,M.cwd,N.text,E,R):await window.api.docEdit.run({path:n,before:N.text,instruction:E,documentText:R});if(s.current!==$)return;if(!z.ok){Me.error(z.error||"Edit failed"),r({type:"RUN_ERR"});return}r({type:"RUN_OK",diff:{before:N.text,after:z.after??""}})}catch(M){if(s.current!==$)return;Me.error(M instanceof Error?M.message:"Edit failed"),r({type:"RUN_ERR"})}},[n,i.selection,e,x,y]),k=P.useCallback(E=>{w(E,!0)},[w]),b=P.useCallback(()=>{i.phase==="review"&&w(i.transcript,!0)},[w,i.phase,i.transcript]),_=P.useCallback(()=>{const E=i.instruction;E&&w(`${E}
3077
3077
 
3078
- (Give a different rewrite than the last one.)`,!1)},[w,i.instruction]),S=P.useCallback(E=>{const T=i.diff;if(!T)return{ok:!1,reason:"not-found"};const N=eB(E,T.before,T.after);return N.ok?(s.current+=1,r({type:"ACCEPT"})):Me.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:p,cancel:m,listen:f,sendHeard:b,run:k,retry:_,accept:S}}const cB=[{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."}],b2=320,hg=8;function dB(){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 uB(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,hg),Math.max(hg,e-b2-hg)),r=Math.max(n.top-hg,hg);return{position:"fixed",left:i,top:r,width:b2,transform:"translateY(-100%)",zIndex:50}}function hB({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:c,onListen:l,onSendHeard:d,onCancel:p,onAccept:m,onReject:f,onRetry:x}){const[y,w]=P.useState(""),k=()=>{const b=y.trim();b&&(c(b),w(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:uB(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"}),cB.map(b=>o.jsx("button",{onClick:()=>a(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),o.jsx("button",{onClick:p,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:y,onChange:b=>w(b.target.value),onKeyDown:b=>{b.key==="Enter"?k():b.key==="Escape"&&p()},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(dB,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:p,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:p,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:d,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:p,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:x,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 pB(){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 y2({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:c,onCancel:l,onAccept:d,onReject:p,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:sf(aB)})]}),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(pB,{}),"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:c,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:p,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:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function w2(n){return n.split("/").filter(Boolean).pop()||n}function fB({path:n,onRenamed:e,onDeleted:i}){const[r,s]=P.useState(!1),[a,c]=P.useState(!1),[l,d]=P.useState(""),[p,m]=P.useState(!1),f=Pn(V=>V.buffers[n]),x=Pn(V=>V.openFile),y=Pn(V=>V.renameOpenFile),w=Pn(V=>V.closeFile),k=ic(),b=w2(n),_=()=>s(!1),S=()=>{d(b),c(!0),_()},E=async()=>{const V=l.trim();if(!V||V===b){c(!1);return}try{const H=await window.api.files.rename(n,V);if(H.ok){const Q=n.slice(0,n.lastIndexOf("/")),X=H.newPath??`${Q}/${V}`;y(n,X),e==null||e(n,X),Me.info(`Renamed to ${V}`)}else Me.error(H.error??`Couldn't rename ${b}`)}catch(H){Me.error(H instanceof Error?H.message:`Couldn't rename ${b}`)}c(!1)},T=async()=>{_();try{const V=await window.api.files.duplicate(n);V.ok&&V.path?(x(V.path),Me.info(`Duplicated as ${w2(V.path)}`)):Me.error(V.error??`Couldn't duplicate ${b}`)}catch(V){Me.error(V instanceof Error?V.message:`Couldn't duplicate ${b}`)}},N=async()=>{try{const V=await window.api.files.delete(n);V.ok?(w(n),i==null||i(n),Me.info(`Deleted ${b}`)):Me.error(V.error??`Couldn't delete ${b}`)}catch(V){Me.error(V instanceof Error?V.message:`Couldn't delete ${b}`)}m(!1)},$=async()=>{_();const V=f??"";try{await navigator.clipboard.writeText(V),Me.info(`Copied ${V.length} chars`)}catch(H){Me.error(H instanceof Error?H.message:`Couldn't copy ${b}`)}},R=()=>{if(_(),!k){Me.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Me.info(`Added ${b} to Claude context`)},M=()=>{_(),window.api.shell.open({as:"openPath",path:n}).then(V=>{V.ok||Me.error(V.error??`Couldn't open ${b}`)}).catch(V=>Me.error(V instanceof Error?V.message:`Couldn't open ${b}`))},z=()=>{_(),window.api.shell.open({as:"revealPath",path:n}).then(V=>{V.ok||Me.error(V.error??`Couldn't reveal ${b}`)}).catch(V=>Me.error(V instanceof Error?V.message:`Couldn't reveal ${b}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(V=>!V),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:_}),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(e_,{children:"Edit"}),o.jsx(mu,{label:"Rename",onClick:S}),o.jsx(mu,{label:"Duplicate",onClick:T}),o.jsx(mu,{label:"Delete document",danger:!0,onClick:()=>{_(),m(!0)}}),o.jsx(_2,{}),o.jsx(e_,{children:"Open"}),o.jsx(mu,{label:"Open in default app",onClick:M}),o.jsx(mu,{label:"Reveal in OS",onClick:z}),o.jsx(_2,{}),o.jsx(e_,{children:"Export"}),o.jsx(mu,{label:"Copy as Markdown",onClick:$}),o.jsx(mu,{label:"Add to Claude context",onClick:R,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(mB,{value:l,onChange:d,onCancel:()=>c(!1),onConfirm:()=>void E()}),p&&o.jsx(gB,{name:b,onCancel:()=>m(!1),onConfirm:()=>void N()})]})}function e_({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 mu({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 _2(){return o.jsx("div",{className:"my-1 border-t border-line"})}function mB({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 gB({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 vB(){const[n,e]=P.useState(!1),i=Mp();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(jp,{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(jp,{label:"Word wrap",children:o.jsx(Qx,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(jp,{label:"Minimap",children:o.jsx(Qx,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(jp,{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(jp,{label:"Autosave",children:o.jsx(Qx,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(jp,{label:"Wide measure",children:o.jsx(Qx,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function jp({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 Qx({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 xB=P.lazy(()=>pv(()=>import("./TiptapBody-PUx4oZTh.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function eb(n){return n.split("/").filter(Boolean).pop()||n}function tb(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 nb(n){return ON(n)||LN(n)}function hy(){const n=yv(),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),c=Pn(Ze=>Ze.setActive),l=Pn(Ze=>Ze.closeFile),d=Pn(Ze=>Ze.closeOthers),p=Pn(Ze=>Ze.closeToTheRight),m=Pn(Ze=>Ze.closeAll),f=Pn(Ze=>Ze.loadBuffer),x=Pn(Ze=>Ze.setBuffer),y=Pn(Ze=>Ze.markSaved),w=Pn(Ze=>Ze.setViewMode),k=Mp(),[b,_]=P.useState({}),[S,E]=P.useState({}),[T,N]=P.useState(null),[$,R]=P.useState(null),[M,z]=P.useState(!1),[V,H]=P.useState(!1),[Q,X]=P.useState(!0),q=P.useRef(null),J=P.useRef(null),ee=P.useRef(void 0),ie=P.useRef(null),re=P.useRef(null),B=lB(i??"",a[i??""]??""),Z=P.useCallback(Ze=>{q.current=Ze},[]),W=P.useCallback(()=>q.current,[]);P.useEffect(()=>{const Ze=i;if(!Ze||nb(Ze))return;if(Pn.getState().hasBuffer(Ze)){_(bt=>bt[Ze]==="ready"?bt:{...bt,[Ze]:"ready"});return}let Et=!1;return _(bt=>({...bt,[Ze]:"loading"})),window.api.files.read(Ze).then(bt=>{Et||(bt.binary?_(pn=>({...pn,[Ze]:{binary:!0,size:bt.size??0,mime:bt.mime??"application/octet-stream",reason:bt.error??"Binary file"}})):bt.ok?(f(Ze,bt.text),_(pn=>({...pn,[Ze]:"ready"}))):_(pn=>({...pn,[Ze]:{error:bt.error??"failed to read"}})))}),()=>{Et=!0}},[i,f]),P.useEffect(()=>{R(null)},[i]);const le=P.useCallback(async(Ze,Et=!1)=>{const bt=Pn.getState().buffers[Ze];if(bt==null)return;Et&&z(!0);const pn=await window.api.files.write(Ze,bt);pn.ok?(y(Ze),E($n=>({...$n,[Ze]:($n[Ze]??0)+1})),Et||Me.info(`Saved ${eb(Ze)}`)):Me.error(pn.error??`Couldn't save ${eb(Ze)}`),Et&&z(!1)},[y]);P.useEffect(()=>{if(!k.autosave)return;const Ze=i;if(!(!Ze||nb(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=P.useCallback(Ze=>{Ze.length&&(_(Et=>tb(Et,Ze)),E(Et=>tb(Et,Ze)))},[]),fe=P.useCallback((Ze,Et)=>{_(bt=>Ze in bt?{...tb(bt,[Ze]),[Et]:bt[Ze]}:bt),E(bt=>Ze in bt?{...tb(bt,[Ze]),[Et]:bt[Ze]}:bt)},[]),Te=P.useCallback(Ze=>{r[Ze]?N({kind:"one",path:Ze}):(l(Ze),ae([Ze]))},[r,l,ae]),Ne=P.useCallback(Ze=>{e.some(bt=>bt.path!==Ze&&r[bt.path])?N({kind:"others",path:Ze}):(d(Ze),ae(e.filter(bt=>bt.path!==Ze).map(bt=>bt.path)))},[e,r,d,ae]),me=P.useCallback(Ze=>{const Et=e.findIndex(pn=>pn.path===Ze);Et!==-1&&e.slice(Et+1).some(pn=>r[pn.path])?N({kind:"right",path:Ze}):(p(Ze),ae(Et!==-1?e.slice(Et+1).map(pn=>pn.path):[]))},[e,r,p,ae]);P.useEffect(()=>{const Ze=Et=>{if(n.current)if((Et.metaKey||Et.ctrlKey)&&(Et.key==="s"||Et.key==="S")){const bt=Pn.getState().activeFilePath;bt&&!nb(bt)&&(Et.preventDefault(),le(bt))}else if((Et.metaKey||Et.ctrlKey)&&Et.shiftKey&&(Et.key==="f"||Et.key==="F"))Et.preventDefault(),H(bt=>!bt);else if((Et.metaKey||Et.ctrlKey)&&Et.shiftKey&&(Et.key==="w"||Et.key==="W")){const bt=Pn.getState().activeFilePath;bt&&Pn.getState().openFiles.length>1&&(Et.preventDefault(),Ne(bt))}else Et.key==="Escape"&&B.state.phase!=="idle"?B.cancel():Et.key==="Escape"&&V&&H(!1)};return window.addEventListener("keydown",Ze),()=>window.removeEventListener("keydown",Ze)},[le,V,Ne,B.state.phase,B.cancel]),P.useEffect(()=>{if(B.state.phase==="idle")return;const Ze=Et=>{var pn,$n;const bt=Et.target;(pn=re.current)!=null&&pn.contains(bt)||($n=ie.current)!=null&&$n.contains(bt)||B.cancel()};return window.addEventListener("mousedown",Ze),()=>window.removeEventListener("mousedown",Ze)},[B.state.phase,B.cancel]),P.useEffect(()=>{B.cancel()},[i,B.cancel]);const se=P.useCallback(()=>{e.some(Et=>r[Et.path])?N({kind:"all",path:""}):(m(),_({}),E({}))},[e,r,m]),Ae=()=>{if(T){if(T.kind==="one")l(T.path),ae([T.path]);else if(T.kind==="others"){const Ze=e.filter(Et=>Et.path!==T.path).map(Et=>Et.path);d(T.path),ae(Ze)}else if(T.kind==="right"){const Ze=e.findIndex(bt=>bt.path===T.path),Et=Ze!==-1?e.slice(Ze+1).map(bt=>bt.path):[];p(T.path),ae(Et)}else m(),_({}),E({});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,Se=ge?eb(ge):"",ye=ge?b[ge]:void 0,et=ge?FN(ge):!1,pt=ge?hz(ge):!1,ot=ge&&et?s[ge]??pz(ge):"edit",nt=!!ge&&!nb(ge)&&ye==="ready",at=nt,Nt=pt?["edit","wysiwyg","preview","split"]:et?["edit","preview"]:[],sn=ge&&o.jsx(_z,{path:ge,name:Se,value:a[ge]??"",onChange:Ze=>x(ge,Ze),onSave:()=>void le(ge),onReady:Z,onCursor:R}),vn=M?"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:[!V&&o.jsx(xz,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:c,onCloseFile:Te,onCloseOthers:Ne,onCloseToTheRight:me,onCloseAll:se}),ge&&!V&&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:Se}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:ge}),nt&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",vn]}),Bl(ge)&&(ot==="preview"||ot==="split")&&o.jsx("button",{onClick:()=>X(Ze=>!Ze),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Q?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Bl(ge)&&(ot==="preview"||ot==="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"}),Nt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Nt.map(Ze=>o.jsx("button",{onClick:()=>w(ge,Ze),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ot===Ze?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ze},Ze))}),o.jsx("div",{className:"flex-1"}),o.jsx(fB,{path:ge,onRenamed:fe,onDeleted:Ze=>ae([Ze])}),nt&&o.jsx(vB,{}),o.jsx("button",{onClick:()=>H(!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"})]}),V&&o.jsx("button",{onClick:()=>H(!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?ON(ge)?o.jsx(W4,{path:ge,name:Se}):LN(ge)?o.jsx(V4,{path:ge}):ye&&typeof ye=="object"&&"binary"in ye?o.jsx(Q4,{path:ge,name:Se,size:ye.size,mime:ye.mime,reason:ye.reason}):ye&&typeof ye=="object"&&"error"in ye?o.jsx("div",{className:"p-6 text-xs text-red-400",children:ye.error}):ye!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ot==="wysiwyg"&&Bl(ge)?o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(xB,{value:a[ge]??"",onChange:Ze=>x(ge,Ze)},ge)}):ot==="split"&&Bl(ge)?o.jsxs("div",{className:"flex h-full",children:[Q&&o.jsx(g2,{text:a[ge]??"",scrollRef:J}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(m2,{getEditor:W}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}),o.jsx("div",{ref:ie,className:"flex-1 min-w-0",children:o.jsx(f0,{ref:J,text:a[ge]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!V&&k.assistantRail&&o.jsx(y2,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const Ze=B.accept(a[ge]??"");Ze.ok&&x(ge,Ze.next)},onReject:B.cancel,onRetry:B.retry})]}):ot==="preview"&&Bl(ge)?o.jsxs("div",{className:"flex h-full",children:[Q&&o.jsx(g2,{text:a[ge]??"",scrollRef:J}),o.jsx("div",{ref:ie,className:"flex-1 min-w-0",children:o.jsx(f0,{ref:J,text:a[ge]??"",wideMeasure:k.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!V&&k.assistantRail&&o.jsx(y2,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const Ze=B.accept(a[ge]??"");Ze.ok&&x(ge,Ze.next)},onReject:B.cancel,onRetry:B.retry})]}):ot==="preview"&&MN(ge)?o.jsx(H4,{path:ge,dirty:!!r[ge],reloadToken:S[ge]??0}):ot==="preview"&&zN(ge)?o.jsx(K4,{path:ge,text:a[ge]??""}):ot==="preview"&&BN(ge)?o.jsx(J4,{path:ge,text:a[ge]??""}):Bl(ge)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(m2,{getEditor:W}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}):sn:null}),at&&o.jsx(G4,{text:a[ge]??"",cursor:$,language:so(ge)||void 0}),ge&&Bl(ge)&&(ot==="preview"||ot==="split")&&B.state.phase!=="idle"&&B.state.selection&&o.jsx("div",{ref:re,children:o.jsx(hB,{phase:B.state.phase,rect:B.state.selection.rect,diff:B.state.diff,transcript:B.state.transcript,modelStatus:B.state.modelStatus,onQuickAction:B.run,onRunCustom:B.run,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onReject:B.cancel,onRetry:B.retry,onAccept:()=>{const Ze=B.accept(a[ge]??"");Ze.ok&&x(ge,Ze.next)}})}),T&&o.jsx(bB,{message:T.kind==="one"?`Discard unsaved changes to ${eb(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:Ae})]})}function bB({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 yB={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},S2='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function uf({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:c=!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 ${c?"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 ${c?"":"p-6 pt-0"}`,children:i})]}):null;const d=P.useRef(null),p=P.useRef(null),m=P.useRef(e);if(m.current=e,P.useEffect(()=>{if(!n)return;p.current=typeof document<"u"?document.activeElement:null;const w=setTimeout(()=>{const b=d.current;if(!b)return;const _=b.querySelector(S2);_?_.focus():b.focus()},0),k=b=>{if(b.key==="Escape"){b.stopPropagation(),m.current();return}if(b.key==="Tab"){const _=d.current;if(!_)return;const S=Array.from(_.querySelectorAll(S2)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(S.length===0){b.preventDefault(),_.focus();return}const E=S[0],T=S[S.length-1],N=document.activeElement;b.shiftKey?(N===E||!_.contains(N))&&(b.preventDefault(),T.focus()):(N===T||!_.contains(N))&&(b.preventDefault(),E.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(w),document.removeEventListener("keydown",k);const b=p.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}p.current=null}},[n]),!n)return null;const f=y=>{y.target===y.currentTarget&&e()},x=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:d,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 ${yB[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${c?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${c?"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?gv.createPortal(x,document.body):x}class sD extends P.Component{constructor(){super(...arguments);Kn(this,"state",{error:null});Kn(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 wB({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(uf,{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(sD,{children:r})})]})}function oD(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 k2=n=>Symbol.iterator in n,C2=n=>"entries"in n,E2=(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},_B=(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 SB(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:k2(n)&&k2(e)?C2(n)&&C2(e)?E2(n,e):_B(n,e):E2({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function Z1(n){const e=It.useRef(void 0);return i=>{const r=n(i);return SB(e.current,r)?e.current:e.current=r}}let j2=0;const kB=1e3;function CB(n){const e=performance.now();e-j2<kB||(j2=e,mt.debug("voice","mic.gate.click_rejected",{reason:n}))}function aD(){const n=Ct(p=>p.isRecording),e=Ct(p=>p.error),i=Ct(p=>p.loadingProgress),r=Ct(Z1(Zb)),s=()=>{const p=Ct.getState(),{canRecord:m,reason:f}=Zb(p);if(p.isRecording)return p.stopRecording();if(p.wizardArmed&&!p.wizardOpen){p.openWizard();return}if(f==="error"||f==="load-timeout"){p.resetAndRetryModel();return}if(!m)return CB(f);const x=xt.getState().activeTabId;x&&p.startRecording(x)},a=oD(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),c=r.reason==="unsupported",l=!r.canRecord,d=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:c,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${d}`,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 EB(){const n=Ct(i=>i.ttsEnabled),e=Ct(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 jB(n){return/^monitor of /i.test(n.trim())}function T2(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function N2(n,e,i){if(n){const c=i.find(l=>l.deviceId===n);if(c)return c}if(!e)return null;const r=i.filter(c=>c.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=T2(e),a=i.filter(c=>c.label&&T2(c.label)===s);return a.length===1?a[0]:null}async function D2(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&jB(r.label))):[]}const A2=!1;function lD(){const n=Ct(p=>p.isRecording);Ct(p=>p.startRecording),Ct(p=>p.stopRecording);const[e,i]=P.useState([]),[r,s]=P.useState(null),[a,c]=P.useState(null);P.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await D2(A2);if(p)return;i(f),c(m.selectedLabel);const x=N2(m.selectedDeviceId,m.selectedLabel,f);x?(s(x.deviceId),m.selectedDeviceId&&x.deviceId!==m.selectedDeviceId&&(mt.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:x.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:x.deviceId,selectedLabel:x.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}),mt.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){mt.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=P.useCallback(async()=>{try{const p=await D2(A2);if(i(p),r&&!p.some(m=>m.deviceId===r)){const m=N2(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){mt.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);P.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const d=async p=>{var y;const m=p.target.value,f=m===""?null:m,x=f?((y=e.find(w=>w.deviceId===f))==null?void 0:y.label)??null:null;s(f),c(x);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:x}),mt.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(w){mt.warn("voice","setDevicePref failed",{error:w instanceof Error?w.message:String(w)})}if(n)try{await Ct.getState().restartWithDevice()}catch(w){mt.warn("voice","device-picker restart failed",{error:w instanceof Error?w.message:String(w)})}};return o.jsxs("select",{value:r??"",onChange:d,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(p=>o.jsx("option",{value:p.deviceId,children:p.label||`Mic ${p.deviceId.slice(0,6)}`},p.deviceId))]})}function TB(){const n=Ct(y=>y.isRecording),e=Ct(y=>y.levelMeterEnabled),[i,r]=P.useState(0),[s,a]=P.useState(0),c=P.useRef(0);c.current=s;const[l,d]=P.useState(0),[p,m]=P.useState(!1),f=P.useRef(null);if(P.useEffect(()=>{if(!n||!e){r(0),a(0);return}let y=0,w=!1,k=null,b=null;const _=()=>{if(w)return;const E=b??yT();if(!E){y=requestAnimationFrame(_);return}b!==E&&(b=E,k=new Uint8Array(new ArrayBuffer(E.fftSize)));const T=k;E.getByteTimeDomainData(T);let N=0;for(let z=0;z<T.length;z++){const V=T[z]-128;N+=V*V}const $=Math.sqrt(N/T.length)/128,R=$>0?20*Math.log10($):-60,M=Math.max(0,Math.min(1,(R+60)/60));a($),r(M),$>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),y=requestAnimationFrame(_)};y=requestAnimationFrame(_);const S=setInterval(()=>{w||d(Math.round(c.current*100))},250);return()=>{w=!0,cancelAnimationFrame(y),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!e)return null;const x=p?"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 ${p?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${x} transition-[width] duration-75 ease-out`,style:{width:`${i*100}%`}})})}function cD(){const n=Ct(p=>p.submitCountdownStartAt),e=Ct(p=>p.submitDelayMs),[i,r]=P.useState(()=>performance.now());if(P.useEffect(()=>{if(n===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),c=Math.max(0,Math.min(100,a/e*100)),l=a<500,d=Ct.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:d,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:`${c}%`}})})})}function NB({open:n,onClose:e,variant:i="overlay"}){return o.jsx(wB,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(PB,{}),o.jsx(cD,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(aD,{}),o.jsx(lD,{}),o.jsx(EB,{})]}),o.jsx(DB,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>Ct.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx($B,{})]}),o.jsx(TB,{})]})})}function DB(){const n=Ct(a=>a.isRecording),[e,i]=P.useState(null);if(P.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const c=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,c()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=AB(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 AB(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 $B(){const[n,e]=P.useState(null);if(P.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>mt.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){mt.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 PB(){const n=Ct(a=>a.isRecording),e=Ct(a=>a.lastTranscript),i=Ct(a=>a.error),r=Ct(a=>a.modelStatus),s=Ct(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 t_=null;function RB(){return t_||(t_=pv(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(I1.config({monaco:n}),n))),t_}function IB({value:n,onChange:e,path:i,readOnly:r}){const s=P.useRef(null),a=c=>{s.current=c};return o.jsx(M1,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:c=>e(c??""),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 $2=!1;async function MB(n){if($2)return;const e=await RB(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const c=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!c.includes(l))throw new Error("untrusted origin");const d=await fetch(s.uri);d.ok&&(a=await d.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}),$2=!0}function Q1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,c]=P.useState(""),[l,d]=P.useState(!0),p=[],m=n.kind==="object"&&Object.keys(n.children).length===0,x=((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:yr[e].label})]}),x&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:y=>d(y.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:y=>c(y.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(dD,{node:n,path:p,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function dD(n){return n.node.kind==="object"?o.jsx(OB,{...n,node:n.node}):n.node.kind==="array"?o.jsx(LB,{...n,node:n.node}):o.jsx(zB,{...n,node:n.node})}function P2(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Qp(n,e,i){return!!(!i.trim()||n.some(r=>P2(r,i))||e!=null&&e.description&&P2(e.description,i))}function OB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:c,schema:l,showGhosts:d,defaultOpen:p}){const[m,f]=P.useState(p??c<2),x=(l==null?void 0:l.at(e))??null,y=new Set(Object.keys(n.children)),w=d?(x==null?void 0:x.knownChildren)??[]:[],k=Array.from(new Set([...y,...w])).sort(),b=P.useMemo(()=>a.trim()?k.filter(S=>{const E=(l==null?void 0:l.at([...e,S]))??null;return Qp([...e,S],E,a)?!0:y.has(S)?uD(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&b.length===0&&!Qp(e,x,a))return null;if(e.length===0)return o.jsx("div",{children:b.map(S=>_(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:c*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:[" {",y.size,w.length>y.size?`/${new Set([...y,...w]).size}`:"","}"]}),(x==null?void 0:x.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:x.description,children:["— ",x.description]})]}),m&&b.map(S=>_(S))]});function _(S){if(y.has(S))return o.jsx(dD,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:c+1,schema:l,showGhosts:d},S);const E=(l==null?void 0:l.at([...e,S]))??null;return E?o.jsx(BB,{path:[...e,S],label:S,info:E,targetScope:r,onSet:s,depth:c+1,filter:a},S):null}}function uD(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Qp(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(uD(n.children[a],[...e,a],i,r))return!0;return!1}function LB({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[c,l]=P.useState(!0),d=(a==null?void 0:a.at(e))??null;return Qp(e,d,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(!c),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:c?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(sv,{tone:"warn",children:"accumulated"}),(d==null?void 0:d.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:d.description,children:["— ",d.description]})]}),c&&n.items.map((p,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:py(p.value)}),o.jsx(v0,{scope:p.fromScope})]},m))]}):null}function zB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:c,schema:l}){const[d,p]=P.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Qp(e,m,a))return null;const f=n.winner!==r,x=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:c*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${x?"text-fg-faint cursor-pointer":""}`,onClick:()=>x&&p(!d),children:x?d?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:py(n.value)}),o.jsx(v0,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(sv,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&FB(n.value,m.default)&&o.jsx(sv,{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(hD,{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 ${yr[r].label} draft`:`already winning in ${yr[r].label}`,children:"override"})]}),d&&n.shadowed.map((y,w)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(c+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:py(y.value)}),o.jsx(v0,{scope:y.scope,dim:!0})]},w))]})}function BB({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:c}){if(!Qp(n,i,c))return null;const l=i.default!==void 0?i.default:GB(i.type),d=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(sv,{tone:"dim",children:d}),i.required&&o.jsx(sv,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",py(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(hD,{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 ${yr[r].label} draft`,children:"set"})]})}function FB(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function GB(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 py(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 v0({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:yr[n].label})}function sv({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 hD({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 HB=[{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:"Model allow/override lists, reasoning depth, and fast-mode toggles — machine-wide, with no per-Epic override yet. An Epic's Agent persona model (Agent Library) still wins over Essentials' plain model default.",advanced:!0,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"]}],UB={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function pD(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=UB[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function fD(n){const e=new Set,i=[];for(const s of HB){const a=s.keys.filter(c=>n.has(c));a.forEach(c=>e.add(c)),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 WB(n,e){return fD(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 VB={};function mD(n,e){if(e)return{text:e,authored:!1};const i=VB[n];return i?{text:i,authored:!0}:null}const qB={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"},KB=["user","project","local","default"],YB={user:"user",project:"project",local:"local",default:"default"};function XB({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=P.useState(""),[c,l]=P.useState(!1),[d,p]=P.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],x=r.rootKeys(),y=new Set([...f,...x]),w=P.useMemo(()=>fD(y),[Array.from(y).sort().join(",")]),k=P.useMemo(()=>WB(y,new Set(f)),[Array.from(y).sort().join(","),f.join(",")]),[b,_]=P.useState(null),S=P.useRef(null),E=N=>{const $=w.find(R=>R.id===N);$!=null&&$.advanced&&!c&&l(!0),_(N)};P.useEffect(()=>{if(!b)return;_(null);const N=S.current,$=document.getElementById(`settings-group-${b}`);if(!N||!$)return;const R=$.getBoundingClientRect().top-N.getBoundingClientRect().top;N.scrollBy({top:R,behavior:"smooth"})},[b]);const T=P.useMemo(()=>w.filter(N=>c||!N.advanced).map(N=>({...N,keys:N.keys.filter($=>{const R=(m==null?void 0:m.children[$])!==void 0;if(!d&&!R)return!1;if(!s.trim())return!0;const M=r.at([$]);return[$,pD($),(M==null?void 0:M.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(N=>N.keys.length>0),[w,s,c,d,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:yr[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:N=>p(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:c,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(JB,{groups:k,onJump:E}),o.jsxs("div",{ref:S,className:"flex-1 overflow-auto py-3",children:[T.map(N=>o.jsx(ZB,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map($=>{const R=m==null?void 0:m.children[$],M=r.at([$]);return o.jsx(QB,{keyName:$,node:R,info:M,targetScope:e,onOverride:(z,V)=>i([$],z,V)},$)})},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 JB({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(an,{name:qB[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 ZB({id:n,title:e,summary:i,advanced:r,children:s}){const[a,c]=P.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:()=>c(!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 QB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,c]=P.useState(!1),[l,d]=P.useState(!1),p=pD(n),m=e!==void 0,x=(e==null?void 0:e.kind)==="leaf"?e:null,y=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",w=i==null?void 0:i.default,k=x&&w!==void 0&&vD(x.value,w),b=aF({isSet:m,leafNode:x,defaultVal:w,isDefault:!!k,node:e}),_=eF(x,w),S=_.length>=2,E=!!x&&!k,T=mD(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:()=>c(!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:p}),o.jsx(lF,{kind:b.kind,label:b.label}),S&&o.jsxs("button",{onClick:N=>{N.stopPropagation(),a||c(!0),d($=>!$)},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 · ",_.map(N=>YB[N]).join(" · ")]}),E&&x&&o.jsx("button",{onClick:N=>{N.stopPropagation(),s(void 0,x.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 ${yr[x.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:cF(T.text)}),a&&l&&x&&o.jsx(tF,{leaf:x,defaultVal:w,onReset:N=>s(void 0,N)}),a&&o.jsx(nF,{keyName:n,node:e,info:i,targetScope:r,onOverride:N=>s(N)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(oF,{node:e,info:i,onSet:N=>{s(N)},disabled:y&&m})})]})})}function eF(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"),KB.filter(r=>i.has(r))}function tF({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],c=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:yr[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:c?Wp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),c?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 ${yr[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?Wp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function nF({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const c=(e==null?void 0:e.kind)==="leaf"?e:null,l=mD(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:Wp(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(d=>String(d)).join(" | ")})]}),c&&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:Wp(c.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",yr[c.winner].label]})]})]}),c&&c.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:c.shadowed.map((d,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Wp(d.value)," —"," ",o.jsx("span",{className:"no-underline",children:yr[d.scope].label})]},p))})]}),(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(iF,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function iF({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,c=gD(e==null?void 0:e.type);if(c==="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:d,label:p})=>o.jsx("button",{onClick:()=>i(d),className:`px-3 py-0.5 text-xs transition-colors ${l===d?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:p},p))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",yr[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 d=vD(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${d?"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:["→ ",yr[r].label]})]}):c==="integer"||c==="number"?o.jsx(rF,{value:typeof a=="number"?a:void 0,integer:c==="integer",onCommit:i,target:yr[r].label}):c==="string"?o.jsx(sF,{value:typeof a=="string"?a:"",onCommit:i,target:yr[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",c??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function rF({value:n,integer:e,onCommit:i,target:r}){const[s,a]=P.useState(n!==void 0?String(n):""),c=()=>{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:c,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:c,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 sF({value:n,onCommit:e,target:i}){const[r,s]=P.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 oF({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=gD(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const c=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!c),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${c?"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:c?"on":"off"})}return null}function aF({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 · ${yr[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${yr[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${Wp(i)}`}:{kind:"unset",label:"not configured"}}function lF({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 gD(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function vD(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function cF(n){const e=n.trim().split(`
3078
+ (Give a different rewrite than the last one.)`,!1)},[w,i.instruction]),S=P.useCallback(E=>{const T=i.diff;if(!T)return{ok:!1,reason:"not-found"};const N=eB(E,T.before,T.after);return N.ok?(s.current+=1,r({type:"ACCEPT"})):Me.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:p,cancel:m,listen:f,sendHeard:b,run:k,retry:_,accept:S}}const cB=[{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."}],b2=320,hg=8;function dB(){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 uB(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,hg),Math.max(hg,e-b2-hg)),r=Math.max(n.top-hg,hg);return{position:"fixed",left:i,top:r,width:b2,transform:"translateY(-100%)",zIndex:50}}function hB({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:c,onListen:l,onSendHeard:d,onCancel:p,onAccept:m,onReject:f,onRetry:x}){const[y,w]=P.useState(""),k=()=>{const b=y.trim();b&&(c(b),w(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:uB(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"}),cB.map(b=>o.jsx("button",{onClick:()=>a(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),o.jsx("button",{onClick:p,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:y,onChange:b=>w(b.target.value),onKeyDown:b=>{b.key==="Enter"?k():b.key==="Escape"&&p()},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(dB,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:p,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:p,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:d,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:p,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:x,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 pB(){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 y2({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:c,onCancel:l,onAccept:d,onReject:p,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:sf(aB)})]}),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(pB,{}),"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:c,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:p,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:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function w2(n){return n.split("/").filter(Boolean).pop()||n}function fB({path:n,onRenamed:e,onDeleted:i}){const[r,s]=P.useState(!1),[a,c]=P.useState(!1),[l,d]=P.useState(""),[p,m]=P.useState(!1),f=Pn(V=>V.buffers[n]),x=Pn(V=>V.openFile),y=Pn(V=>V.renameOpenFile),w=Pn(V=>V.closeFile),k=ic(),b=w2(n),_=()=>s(!1),S=()=>{d(b),c(!0),_()},E=async()=>{const V=l.trim();if(!V||V===b){c(!1);return}try{const H=await window.api.files.rename(n,V);if(H.ok){const Q=n.slice(0,n.lastIndexOf("/")),X=H.newPath??`${Q}/${V}`;y(n,X),e==null||e(n,X),Me.info(`Renamed to ${V}`)}else Me.error(H.error??`Couldn't rename ${b}`)}catch(H){Me.error(H instanceof Error?H.message:`Couldn't rename ${b}`)}c(!1)},T=async()=>{_();try{const V=await window.api.files.duplicate(n);V.ok&&V.path?(x(V.path),Me.info(`Duplicated as ${w2(V.path)}`)):Me.error(V.error??`Couldn't duplicate ${b}`)}catch(V){Me.error(V instanceof Error?V.message:`Couldn't duplicate ${b}`)}},N=async()=>{try{const V=await window.api.files.delete(n);V.ok?(w(n),i==null||i(n),Me.info(`Deleted ${b}`)):Me.error(V.error??`Couldn't delete ${b}`)}catch(V){Me.error(V instanceof Error?V.message:`Couldn't delete ${b}`)}m(!1)},$=async()=>{_();const V=f??"";try{await navigator.clipboard.writeText(V),Me.info(`Copied ${V.length} chars`)}catch(H){Me.error(H instanceof Error?H.message:`Couldn't copy ${b}`)}},R=()=>{if(_(),!k){Me.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Me.info(`Added ${b} to Claude context`)},M=()=>{_(),window.api.shell.open({as:"openPath",path:n}).then(V=>{V.ok||Me.error(V.error??`Couldn't open ${b}`)}).catch(V=>Me.error(V instanceof Error?V.message:`Couldn't open ${b}`))},z=()=>{_(),window.api.shell.open({as:"revealPath",path:n}).then(V=>{V.ok||Me.error(V.error??`Couldn't reveal ${b}`)}).catch(V=>Me.error(V instanceof Error?V.message:`Couldn't reveal ${b}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(V=>!V),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:_}),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(e_,{children:"Edit"}),o.jsx(mu,{label:"Rename",onClick:S}),o.jsx(mu,{label:"Duplicate",onClick:T}),o.jsx(mu,{label:"Delete document",danger:!0,onClick:()=>{_(),m(!0)}}),o.jsx(_2,{}),o.jsx(e_,{children:"Open"}),o.jsx(mu,{label:"Open in default app",onClick:M}),o.jsx(mu,{label:"Reveal in OS",onClick:z}),o.jsx(_2,{}),o.jsx(e_,{children:"Export"}),o.jsx(mu,{label:"Copy as Markdown",onClick:$}),o.jsx(mu,{label:"Add to Claude context",onClick:R,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(mB,{value:l,onChange:d,onCancel:()=>c(!1),onConfirm:()=>void E()}),p&&o.jsx(gB,{name:b,onCancel:()=>m(!1),onConfirm:()=>void N()})]})}function e_({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 mu({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 _2(){return o.jsx("div",{className:"my-1 border-t border-line"})}function mB({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 gB({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 vB(){const[n,e]=P.useState(!1),i=Mp();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(jp,{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(jp,{label:"Word wrap",children:o.jsx(Qx,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(jp,{label:"Minimap",children:o.jsx(Qx,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(jp,{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(jp,{label:"Autosave",children:o.jsx(Qx,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(jp,{label:"Wide measure",children:o.jsx(Qx,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function jp({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 Qx({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 xB=P.lazy(()=>pv(()=>import("./TiptapBody-BtVPGBaq.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function eb(n){return n.split("/").filter(Boolean).pop()||n}function tb(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 nb(n){return ON(n)||LN(n)}function hy(){const n=yv(),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),c=Pn(Ze=>Ze.setActive),l=Pn(Ze=>Ze.closeFile),d=Pn(Ze=>Ze.closeOthers),p=Pn(Ze=>Ze.closeToTheRight),m=Pn(Ze=>Ze.closeAll),f=Pn(Ze=>Ze.loadBuffer),x=Pn(Ze=>Ze.setBuffer),y=Pn(Ze=>Ze.markSaved),w=Pn(Ze=>Ze.setViewMode),k=Mp(),[b,_]=P.useState({}),[S,E]=P.useState({}),[T,N]=P.useState(null),[$,R]=P.useState(null),[M,z]=P.useState(!1),[V,H]=P.useState(!1),[Q,X]=P.useState(!0),q=P.useRef(null),J=P.useRef(null),ee=P.useRef(void 0),ie=P.useRef(null),re=P.useRef(null),B=lB(i??"",a[i??""]??""),Z=P.useCallback(Ze=>{q.current=Ze},[]),W=P.useCallback(()=>q.current,[]);P.useEffect(()=>{const Ze=i;if(!Ze||nb(Ze))return;if(Pn.getState().hasBuffer(Ze)){_(bt=>bt[Ze]==="ready"?bt:{...bt,[Ze]:"ready"});return}let Et=!1;return _(bt=>({...bt,[Ze]:"loading"})),window.api.files.read(Ze).then(bt=>{Et||(bt.binary?_(pn=>({...pn,[Ze]:{binary:!0,size:bt.size??0,mime:bt.mime??"application/octet-stream",reason:bt.error??"Binary file"}})):bt.ok?(f(Ze,bt.text),_(pn=>({...pn,[Ze]:"ready"}))):_(pn=>({...pn,[Ze]:{error:bt.error??"failed to read"}})))}),()=>{Et=!0}},[i,f]),P.useEffect(()=>{R(null)},[i]);const le=P.useCallback(async(Ze,Et=!1)=>{const bt=Pn.getState().buffers[Ze];if(bt==null)return;Et&&z(!0);const pn=await window.api.files.write(Ze,bt);pn.ok?(y(Ze),E($n=>({...$n,[Ze]:($n[Ze]??0)+1})),Et||Me.info(`Saved ${eb(Ze)}`)):Me.error(pn.error??`Couldn't save ${eb(Ze)}`),Et&&z(!1)},[y]);P.useEffect(()=>{if(!k.autosave)return;const Ze=i;if(!(!Ze||nb(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=P.useCallback(Ze=>{Ze.length&&(_(Et=>tb(Et,Ze)),E(Et=>tb(Et,Ze)))},[]),fe=P.useCallback((Ze,Et)=>{_(bt=>Ze in bt?{...tb(bt,[Ze]),[Et]:bt[Ze]}:bt),E(bt=>Ze in bt?{...tb(bt,[Ze]),[Et]:bt[Ze]}:bt)},[]),Te=P.useCallback(Ze=>{r[Ze]?N({kind:"one",path:Ze}):(l(Ze),ae([Ze]))},[r,l,ae]),Ne=P.useCallback(Ze=>{e.some(bt=>bt.path!==Ze&&r[bt.path])?N({kind:"others",path:Ze}):(d(Ze),ae(e.filter(bt=>bt.path!==Ze).map(bt=>bt.path)))},[e,r,d,ae]),me=P.useCallback(Ze=>{const Et=e.findIndex(pn=>pn.path===Ze);Et!==-1&&e.slice(Et+1).some(pn=>r[pn.path])?N({kind:"right",path:Ze}):(p(Ze),ae(Et!==-1?e.slice(Et+1).map(pn=>pn.path):[]))},[e,r,p,ae]);P.useEffect(()=>{const Ze=Et=>{if(n.current)if((Et.metaKey||Et.ctrlKey)&&(Et.key==="s"||Et.key==="S")){const bt=Pn.getState().activeFilePath;bt&&!nb(bt)&&(Et.preventDefault(),le(bt))}else if((Et.metaKey||Et.ctrlKey)&&Et.shiftKey&&(Et.key==="f"||Et.key==="F"))Et.preventDefault(),H(bt=>!bt);else if((Et.metaKey||Et.ctrlKey)&&Et.shiftKey&&(Et.key==="w"||Et.key==="W")){const bt=Pn.getState().activeFilePath;bt&&Pn.getState().openFiles.length>1&&(Et.preventDefault(),Ne(bt))}else Et.key==="Escape"&&B.state.phase!=="idle"?B.cancel():Et.key==="Escape"&&V&&H(!1)};return window.addEventListener("keydown",Ze),()=>window.removeEventListener("keydown",Ze)},[le,V,Ne,B.state.phase,B.cancel]),P.useEffect(()=>{if(B.state.phase==="idle")return;const Ze=Et=>{var pn,$n;const bt=Et.target;(pn=re.current)!=null&&pn.contains(bt)||($n=ie.current)!=null&&$n.contains(bt)||B.cancel()};return window.addEventListener("mousedown",Ze),()=>window.removeEventListener("mousedown",Ze)},[B.state.phase,B.cancel]),P.useEffect(()=>{B.cancel()},[i,B.cancel]);const se=P.useCallback(()=>{e.some(Et=>r[Et.path])?N({kind:"all",path:""}):(m(),_({}),E({}))},[e,r,m]),Ae=()=>{if(T){if(T.kind==="one")l(T.path),ae([T.path]);else if(T.kind==="others"){const Ze=e.filter(Et=>Et.path!==T.path).map(Et=>Et.path);d(T.path),ae(Ze)}else if(T.kind==="right"){const Ze=e.findIndex(bt=>bt.path===T.path),Et=Ze!==-1?e.slice(Ze+1).map(bt=>bt.path):[];p(T.path),ae(Et)}else m(),_({}),E({});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,Se=ge?eb(ge):"",ye=ge?b[ge]:void 0,et=ge?FN(ge):!1,pt=ge?hz(ge):!1,ot=ge&&et?s[ge]??pz(ge):"edit",nt=!!ge&&!nb(ge)&&ye==="ready",at=nt,Nt=pt?["edit","wysiwyg","preview","split"]:et?["edit","preview"]:[],sn=ge&&o.jsx(_z,{path:ge,name:Se,value:a[ge]??"",onChange:Ze=>x(ge,Ze),onSave:()=>void le(ge),onReady:Z,onCursor:R}),vn=M?"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:[!V&&o.jsx(xz,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:c,onCloseFile:Te,onCloseOthers:Ne,onCloseToTheRight:me,onCloseAll:se}),ge&&!V&&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:Se}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:ge}),nt&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",vn]}),Bl(ge)&&(ot==="preview"||ot==="split")&&o.jsx("button",{onClick:()=>X(Ze=>!Ze),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Q?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Bl(ge)&&(ot==="preview"||ot==="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"}),Nt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Nt.map(Ze=>o.jsx("button",{onClick:()=>w(ge,Ze),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ot===Ze?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ze},Ze))}),o.jsx("div",{className:"flex-1"}),o.jsx(fB,{path:ge,onRenamed:fe,onDeleted:Ze=>ae([Ze])}),nt&&o.jsx(vB,{}),o.jsx("button",{onClick:()=>H(!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"})]}),V&&o.jsx("button",{onClick:()=>H(!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?ON(ge)?o.jsx(W4,{path:ge,name:Se}):LN(ge)?o.jsx(V4,{path:ge}):ye&&typeof ye=="object"&&"binary"in ye?o.jsx(Q4,{path:ge,name:Se,size:ye.size,mime:ye.mime,reason:ye.reason}):ye&&typeof ye=="object"&&"error"in ye?o.jsx("div",{className:"p-6 text-xs text-red-400",children:ye.error}):ye!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ot==="wysiwyg"&&Bl(ge)?o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(xB,{value:a[ge]??"",onChange:Ze=>x(ge,Ze)},ge)}):ot==="split"&&Bl(ge)?o.jsxs("div",{className:"flex h-full",children:[Q&&o.jsx(g2,{text:a[ge]??"",scrollRef:J}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(m2,{getEditor:W}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}),o.jsx("div",{ref:ie,className:"flex-1 min-w-0",children:o.jsx(f0,{ref:J,text:a[ge]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!V&&k.assistantRail&&o.jsx(y2,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const Ze=B.accept(a[ge]??"");Ze.ok&&x(ge,Ze.next)},onReject:B.cancel,onRetry:B.retry})]}):ot==="preview"&&Bl(ge)?o.jsxs("div",{className:"flex h-full",children:[Q&&o.jsx(g2,{text:a[ge]??"",scrollRef:J}),o.jsx("div",{ref:ie,className:"flex-1 min-w-0",children:o.jsx(f0,{ref:J,text:a[ge]??"",wideMeasure:k.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!V&&k.assistantRail&&o.jsx(y2,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const Ze=B.accept(a[ge]??"");Ze.ok&&x(ge,Ze.next)},onReject:B.cancel,onRetry:B.retry})]}):ot==="preview"&&MN(ge)?o.jsx(H4,{path:ge,dirty:!!r[ge],reloadToken:S[ge]??0}):ot==="preview"&&zN(ge)?o.jsx(K4,{path:ge,text:a[ge]??""}):ot==="preview"&&BN(ge)?o.jsx(J4,{path:ge,text:a[ge]??""}):Bl(ge)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(m2,{getEditor:W}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}):sn:null}),at&&o.jsx(G4,{text:a[ge]??"",cursor:$,language:so(ge)||void 0}),ge&&Bl(ge)&&(ot==="preview"||ot==="split")&&B.state.phase!=="idle"&&B.state.selection&&o.jsx("div",{ref:re,children:o.jsx(hB,{phase:B.state.phase,rect:B.state.selection.rect,diff:B.state.diff,transcript:B.state.transcript,modelStatus:B.state.modelStatus,onQuickAction:B.run,onRunCustom:B.run,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onReject:B.cancel,onRetry:B.retry,onAccept:()=>{const Ze=B.accept(a[ge]??"");Ze.ok&&x(ge,Ze.next)}})}),T&&o.jsx(bB,{message:T.kind==="one"?`Discard unsaved changes to ${eb(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:Ae})]})}function bB({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 yB={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},S2='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function uf({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:c=!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 ${c?"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 ${c?"":"p-6 pt-0"}`,children:i})]}):null;const d=P.useRef(null),p=P.useRef(null),m=P.useRef(e);if(m.current=e,P.useEffect(()=>{if(!n)return;p.current=typeof document<"u"?document.activeElement:null;const w=setTimeout(()=>{const b=d.current;if(!b)return;const _=b.querySelector(S2);_?_.focus():b.focus()},0),k=b=>{if(b.key==="Escape"){b.stopPropagation(),m.current();return}if(b.key==="Tab"){const _=d.current;if(!_)return;const S=Array.from(_.querySelectorAll(S2)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(S.length===0){b.preventDefault(),_.focus();return}const E=S[0],T=S[S.length-1],N=document.activeElement;b.shiftKey?(N===E||!_.contains(N))&&(b.preventDefault(),T.focus()):(N===T||!_.contains(N))&&(b.preventDefault(),E.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(w),document.removeEventListener("keydown",k);const b=p.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}p.current=null}},[n]),!n)return null;const f=y=>{y.target===y.currentTarget&&e()},x=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:d,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 ${yB[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${c?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${c?"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?gv.createPortal(x,document.body):x}class sD extends P.Component{constructor(){super(...arguments);Kn(this,"state",{error:null});Kn(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 wB({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(uf,{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(sD,{children:r})})]})}function oD(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 k2=n=>Symbol.iterator in n,C2=n=>"entries"in n,E2=(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},_B=(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 SB(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:k2(n)&&k2(e)?C2(n)&&C2(e)?E2(n,e):_B(n,e):E2({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function Z1(n){const e=It.useRef(void 0);return i=>{const r=n(i);return SB(e.current,r)?e.current:e.current=r}}let j2=0;const kB=1e3;function CB(n){const e=performance.now();e-j2<kB||(j2=e,mt.debug("voice","mic.gate.click_rejected",{reason:n}))}function aD(){const n=Ct(p=>p.isRecording),e=Ct(p=>p.error),i=Ct(p=>p.loadingProgress),r=Ct(Z1(Zb)),s=()=>{const p=Ct.getState(),{canRecord:m,reason:f}=Zb(p);if(p.isRecording)return p.stopRecording();if(p.wizardArmed&&!p.wizardOpen){p.openWizard();return}if(f==="error"||f==="load-timeout"){p.resetAndRetryModel();return}if(!m)return CB(f);const x=xt.getState().activeTabId;x&&p.startRecording(x)},a=oD(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),c=r.reason==="unsupported",l=!r.canRecord,d=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:c,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${d}`,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 EB(){const n=Ct(i=>i.ttsEnabled),e=Ct(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 jB(n){return/^monitor of /i.test(n.trim())}function T2(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function N2(n,e,i){if(n){const c=i.find(l=>l.deviceId===n);if(c)return c}if(!e)return null;const r=i.filter(c=>c.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=T2(e),a=i.filter(c=>c.label&&T2(c.label)===s);return a.length===1?a[0]:null}async function D2(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&jB(r.label))):[]}const A2=!1;function lD(){const n=Ct(p=>p.isRecording);Ct(p=>p.startRecording),Ct(p=>p.stopRecording);const[e,i]=P.useState([]),[r,s]=P.useState(null),[a,c]=P.useState(null);P.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await D2(A2);if(p)return;i(f),c(m.selectedLabel);const x=N2(m.selectedDeviceId,m.selectedLabel,f);x?(s(x.deviceId),m.selectedDeviceId&&x.deviceId!==m.selectedDeviceId&&(mt.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:x.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:x.deviceId,selectedLabel:x.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}),mt.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){mt.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=P.useCallback(async()=>{try{const p=await D2(A2);if(i(p),r&&!p.some(m=>m.deviceId===r)){const m=N2(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){mt.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);P.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const d=async p=>{var y;const m=p.target.value,f=m===""?null:m,x=f?((y=e.find(w=>w.deviceId===f))==null?void 0:y.label)??null:null;s(f),c(x);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:x}),mt.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(w){mt.warn("voice","setDevicePref failed",{error:w instanceof Error?w.message:String(w)})}if(n)try{await Ct.getState().restartWithDevice()}catch(w){mt.warn("voice","device-picker restart failed",{error:w instanceof Error?w.message:String(w)})}};return o.jsxs("select",{value:r??"",onChange:d,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(p=>o.jsx("option",{value:p.deviceId,children:p.label||`Mic ${p.deviceId.slice(0,6)}`},p.deviceId))]})}function TB(){const n=Ct(y=>y.isRecording),e=Ct(y=>y.levelMeterEnabled),[i,r]=P.useState(0),[s,a]=P.useState(0),c=P.useRef(0);c.current=s;const[l,d]=P.useState(0),[p,m]=P.useState(!1),f=P.useRef(null);if(P.useEffect(()=>{if(!n||!e){r(0),a(0);return}let y=0,w=!1,k=null,b=null;const _=()=>{if(w)return;const E=b??yT();if(!E){y=requestAnimationFrame(_);return}b!==E&&(b=E,k=new Uint8Array(new ArrayBuffer(E.fftSize)));const T=k;E.getByteTimeDomainData(T);let N=0;for(let z=0;z<T.length;z++){const V=T[z]-128;N+=V*V}const $=Math.sqrt(N/T.length)/128,R=$>0?20*Math.log10($):-60,M=Math.max(0,Math.min(1,(R+60)/60));a($),r(M),$>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),y=requestAnimationFrame(_)};y=requestAnimationFrame(_);const S=setInterval(()=>{w||d(Math.round(c.current*100))},250);return()=>{w=!0,cancelAnimationFrame(y),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!e)return null;const x=p?"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 ${p?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${x} transition-[width] duration-75 ease-out`,style:{width:`${i*100}%`}})})}function cD(){const n=Ct(p=>p.submitCountdownStartAt),e=Ct(p=>p.submitDelayMs),[i,r]=P.useState(()=>performance.now());if(P.useEffect(()=>{if(n===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),c=Math.max(0,Math.min(100,a/e*100)),l=a<500,d=Ct.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:d,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:`${c}%`}})})})}function NB({open:n,onClose:e,variant:i="overlay"}){return o.jsx(wB,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(PB,{}),o.jsx(cD,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(aD,{}),o.jsx(lD,{}),o.jsx(EB,{})]}),o.jsx(DB,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>Ct.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx($B,{})]}),o.jsx(TB,{})]})})}function DB(){const n=Ct(a=>a.isRecording),[e,i]=P.useState(null);if(P.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const c=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,c()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=AB(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 AB(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 $B(){const[n,e]=P.useState(null);if(P.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>mt.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){mt.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 PB(){const n=Ct(a=>a.isRecording),e=Ct(a=>a.lastTranscript),i=Ct(a=>a.error),r=Ct(a=>a.modelStatus),s=Ct(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 t_=null;function RB(){return t_||(t_=pv(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(I1.config({monaco:n}),n))),t_}function IB({value:n,onChange:e,path:i,readOnly:r}){const s=P.useRef(null),a=c=>{s.current=c};return o.jsx(M1,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:c=>e(c??""),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 $2=!1;async function MB(n){if($2)return;const e=await RB(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const c=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!c.includes(l))throw new Error("untrusted origin");const d=await fetch(s.uri);d.ok&&(a=await d.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}),$2=!0}function Q1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,c]=P.useState(""),[l,d]=P.useState(!0),p=[],m=n.kind==="object"&&Object.keys(n.children).length===0,x=((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:yr[e].label})]}),x&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:y=>d(y.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:y=>c(y.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(dD,{node:n,path:p,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function dD(n){return n.node.kind==="object"?o.jsx(OB,{...n,node:n.node}):n.node.kind==="array"?o.jsx(LB,{...n,node:n.node}):o.jsx(zB,{...n,node:n.node})}function P2(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Qp(n,e,i){return!!(!i.trim()||n.some(r=>P2(r,i))||e!=null&&e.description&&P2(e.description,i))}function OB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:c,schema:l,showGhosts:d,defaultOpen:p}){const[m,f]=P.useState(p??c<2),x=(l==null?void 0:l.at(e))??null,y=new Set(Object.keys(n.children)),w=d?(x==null?void 0:x.knownChildren)??[]:[],k=Array.from(new Set([...y,...w])).sort(),b=P.useMemo(()=>a.trim()?k.filter(S=>{const E=(l==null?void 0:l.at([...e,S]))??null;return Qp([...e,S],E,a)?!0:y.has(S)?uD(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&b.length===0&&!Qp(e,x,a))return null;if(e.length===0)return o.jsx("div",{children:b.map(S=>_(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:c*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:[" {",y.size,w.length>y.size?`/${new Set([...y,...w]).size}`:"","}"]}),(x==null?void 0:x.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:x.description,children:["— ",x.description]})]}),m&&b.map(S=>_(S))]});function _(S){if(y.has(S))return o.jsx(dD,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:c+1,schema:l,showGhosts:d},S);const E=(l==null?void 0:l.at([...e,S]))??null;return E?o.jsx(BB,{path:[...e,S],label:S,info:E,targetScope:r,onSet:s,depth:c+1,filter:a},S):null}}function uD(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Qp(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(uD(n.children[a],[...e,a],i,r))return!0;return!1}function LB({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[c,l]=P.useState(!0),d=(a==null?void 0:a.at(e))??null;return Qp(e,d,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(!c),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:c?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(sv,{tone:"warn",children:"accumulated"}),(d==null?void 0:d.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:d.description,children:["— ",d.description]})]}),c&&n.items.map((p,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:py(p.value)}),o.jsx(v0,{scope:p.fromScope})]},m))]}):null}function zB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:c,schema:l}){const[d,p]=P.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Qp(e,m,a))return null;const f=n.winner!==r,x=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:c*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${x?"text-fg-faint cursor-pointer":""}`,onClick:()=>x&&p(!d),children:x?d?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:py(n.value)}),o.jsx(v0,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(sv,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&FB(n.value,m.default)&&o.jsx(sv,{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(hD,{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 ${yr[r].label} draft`:`already winning in ${yr[r].label}`,children:"override"})]}),d&&n.shadowed.map((y,w)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(c+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:py(y.value)}),o.jsx(v0,{scope:y.scope,dim:!0})]},w))]})}function BB({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:c}){if(!Qp(n,i,c))return null;const l=i.default!==void 0?i.default:GB(i.type),d=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(sv,{tone:"dim",children:d}),i.required&&o.jsx(sv,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",py(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(hD,{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 ${yr[r].label} draft`,children:"set"})]})}function FB(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function GB(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 py(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 v0({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:yr[n].label})}function sv({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 hD({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 HB=[{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:"Model allow/override lists, reasoning depth, and fast-mode toggles — machine-wide, with no per-Epic override yet. An Epic's Agent persona model (Agent Library) still wins over Essentials' plain model default.",advanced:!0,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"]}],UB={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function pD(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=UB[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function fD(n){const e=new Set,i=[];for(const s of HB){const a=s.keys.filter(c=>n.has(c));a.forEach(c=>e.add(c)),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 WB(n,e){return fD(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 VB={};function mD(n,e){if(e)return{text:e,authored:!1};const i=VB[n];return i?{text:i,authored:!0}:null}const qB={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"},KB=["user","project","local","default"],YB={user:"user",project:"project",local:"local",default:"default"};function XB({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=P.useState(""),[c,l]=P.useState(!1),[d,p]=P.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],x=r.rootKeys(),y=new Set([...f,...x]),w=P.useMemo(()=>fD(y),[Array.from(y).sort().join(",")]),k=P.useMemo(()=>WB(y,new Set(f)),[Array.from(y).sort().join(","),f.join(",")]),[b,_]=P.useState(null),S=P.useRef(null),E=N=>{const $=w.find(R=>R.id===N);$!=null&&$.advanced&&!c&&l(!0),_(N)};P.useEffect(()=>{if(!b)return;_(null);const N=S.current,$=document.getElementById(`settings-group-${b}`);if(!N||!$)return;const R=$.getBoundingClientRect().top-N.getBoundingClientRect().top;N.scrollBy({top:R,behavior:"smooth"})},[b]);const T=P.useMemo(()=>w.filter(N=>c||!N.advanced).map(N=>({...N,keys:N.keys.filter($=>{const R=(m==null?void 0:m.children[$])!==void 0;if(!d&&!R)return!1;if(!s.trim())return!0;const M=r.at([$]);return[$,pD($),(M==null?void 0:M.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(N=>N.keys.length>0),[w,s,c,d,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:yr[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:N=>p(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:c,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(JB,{groups:k,onJump:E}),o.jsxs("div",{ref:S,className:"flex-1 overflow-auto py-3",children:[T.map(N=>o.jsx(ZB,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map($=>{const R=m==null?void 0:m.children[$],M=r.at([$]);return o.jsx(QB,{keyName:$,node:R,info:M,targetScope:e,onOverride:(z,V)=>i([$],z,V)},$)})},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 JB({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(an,{name:qB[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 ZB({id:n,title:e,summary:i,advanced:r,children:s}){const[a,c]=P.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:()=>c(!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 QB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,c]=P.useState(!1),[l,d]=P.useState(!1),p=pD(n),m=e!==void 0,x=(e==null?void 0:e.kind)==="leaf"?e:null,y=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",w=i==null?void 0:i.default,k=x&&w!==void 0&&vD(x.value,w),b=aF({isSet:m,leafNode:x,defaultVal:w,isDefault:!!k,node:e}),_=eF(x,w),S=_.length>=2,E=!!x&&!k,T=mD(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:()=>c(!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:p}),o.jsx(lF,{kind:b.kind,label:b.label}),S&&o.jsxs("button",{onClick:N=>{N.stopPropagation(),a||c(!0),d($=>!$)},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 · ",_.map(N=>YB[N]).join(" · ")]}),E&&x&&o.jsx("button",{onClick:N=>{N.stopPropagation(),s(void 0,x.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 ${yr[x.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:cF(T.text)}),a&&l&&x&&o.jsx(tF,{leaf:x,defaultVal:w,onReset:N=>s(void 0,N)}),a&&o.jsx(nF,{keyName:n,node:e,info:i,targetScope:r,onOverride:N=>s(N)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(oF,{node:e,info:i,onSet:N=>{s(N)},disabled:y&&m})})]})})}function eF(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"),KB.filter(r=>i.has(r))}function tF({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],c=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:yr[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:c?Wp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),c?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 ${yr[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?Wp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function nF({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const c=(e==null?void 0:e.kind)==="leaf"?e:null,l=mD(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:Wp(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(d=>String(d)).join(" | ")})]}),c&&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:Wp(c.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",yr[c.winner].label]})]})]}),c&&c.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:c.shadowed.map((d,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Wp(d.value)," —"," ",o.jsx("span",{className:"no-underline",children:yr[d.scope].label})]},p))})]}),(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(iF,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function iF({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,c=gD(e==null?void 0:e.type);if(c==="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:d,label:p})=>o.jsx("button",{onClick:()=>i(d),className:`px-3 py-0.5 text-xs transition-colors ${l===d?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:p},p))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",yr[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 d=vD(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${d?"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:["→ ",yr[r].label]})]}):c==="integer"||c==="number"?o.jsx(rF,{value:typeof a=="number"?a:void 0,integer:c==="integer",onCommit:i,target:yr[r].label}):c==="string"?o.jsx(sF,{value:typeof a=="string"?a:"",onCommit:i,target:yr[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",c??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function rF({value:n,integer:e,onCommit:i,target:r}){const[s,a]=P.useState(n!==void 0?String(n):""),c=()=>{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:c,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:c,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 sF({value:n,onCommit:e,target:i}){const[r,s]=P.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 oF({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=gD(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const c=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!c),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${c?"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:c?"on":"off"})}return null}function aF({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 · ${yr[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${yr[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${Wp(i)}`}:{kind:"unset",label:"not configured"}}function lF({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 gD(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function vD(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function cF(n){const e=n.trim().split(`
3079
3079
  `)[0],i=e.match(/^([^.!?]+[.!?])/);return i?i[1]:e.length>120?e.slice(0,120)+"…":e}function Wp(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 eS(n,e,i){const r=hn(d=>d.files),s=hn(d=>d.loadJson),a=hn(d=>d.watchFile),c=hn(d=>d.unwatchFile),l=P.useMemo(()=>{const d={};for(const p of n.scopes){const m=n.resolve(p,e??"",i);m&&(d[p]=m)}return d},[n,e,i]);return P.useEffect(()=>{const d=Object.values(l).filter(Boolean);return d.forEach(p=>{r[p]||s(p),a(p)}),()=>{d.forEach(p=>c(p))}},[JSON.stringify(l)]),l}const dF=[];function ib(n){return Array.isArray(n)?"array":n!==null&&typeof n=="object"?"object":"scalar"}function tS(n){const e=n.filter(i=>i.data!==void 0);return e.length===0?{kind:"object",children:{}}:xD(e,[])}function xD(n,e){const i=dF.includes(e.join(".")),r=n.every(m=>ib(m.data)==="object"),s=n.every(m=>ib(m.data)==="array");if(r){const m=new Set;for(const x of n)for(const y of Object.keys(x.data))m.add(y);const f={};for(const x of m){const y=n.filter(w=>x in w.data).map(w=>({scope:w.scope,data:w.data[x]}));f[x]=xD(y,[...e,x])}return{kind:"object",children:f}}if(s&&!i){const m=[];for(const f of[...n].reverse())for(const x of f.data)m.push({value:x,fromScope:f.scope,index:m.length});return{kind:"array",items:m}}const a=[...n].reverse(),c=a[0],l=a.slice(1).map(m=>({scope:m.scope,value:m.data})),d=ib(c.data),p=l.some(m=>ib(m.value)!==d);return{kind:"leaf",value:c.data,winner:c.scope,shadowed:l,...p?{typeMismatch:!0}:{}}}function nS(n,e){if(e.length===0)return n;if(n.kind!=="object")return null;const[i,...r]=e,s=n.children[i];return s?nS(s,r):null}function Xy(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]=Xy(a[r],s,i),a}const uF=["user","project","local"];function iS(n,e){const i=[];for(const r of uF){const s=e[r];if(!s)continue;const a=n[s];if(!a||!a.exists)continue;const c=a.draftRaw??"";if(c.trim())try{i.push({scope:r,data:JSON.parse(c)})}catch{}}return i}const hF="http://json-schema.org/draft-07/schema#",pF="https://json.schemastore.org/claude-code-settings.json",fF={permissionRule:{type:"string",description:`Tool permission rule.
3080
3080
  See https://code.claude.com/docs/en/settings#permission-rule-syntax
3081
3081
  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"}}}}},mF="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",gF=!0,vF=!0,xF="object",bF=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"]}]}}}`),yF="Claude Code Settings",wF={$schema:hF,$id:pF,$defs:fF,description:mF,allowTrailingCommas:gF,additionalProperties:vF,type:xF,properties:bF,title:yF};function _F(n){const e=n??{},i={...e.$defs??{},...e.definitions??{}},r=y=>{if(!y)return{};if(!y.$ref)return c(y);const w=/^#\/(\$defs|definitions)\/(.+)$/.exec(y.$ref);if(!w)return c(y);const k=i[w[2]];return k?r({...k,...l(y)}):c(y)},s=new Set(["__proto__","constructor","prototype"]),a=y=>{if(!y)return{};const w={};for(const[k,b]of Object.entries(y))s.has(k)||(w[k]=b);return w},c=y=>{if(!y.allOf||y.allOf.length===0)return y;const w={...y};delete w.allOf;for(const k of y.allOf){const b=r(k);Object.assign(w,{properties:{...a(w.properties),...a(b.properties)},required:SF([...w.required??[],...b.required??[]])}),!w.description&&b.description&&(w.description=b.description),w.default===void 0&&b.default!==void 0&&(w.default=b.default),!w.type&&b.type&&(w.type=b.type)}return w},l=y=>{const{$ref:w,...k}=y;return k},d=(y,w)=>{let k=r(y);for(const b of w){if(!k)return null;if(/^\d+$/.test(b)){const E=Array.isArray(k.items)?k.items[Number(b)]:k.items;k=E?r(E):null;continue}const _=k.properties;if(_&&!s.has(b)&&b in _){k=r(_[b]);continue}const S=k.additionalProperties;if(S&&typeof S=="object"){k=r(S);continue}return null}return k},p=(y,w,k)=>{if(!y)return null;const b={};if(y.description&&(b.description=y.description),y.type&&(b.type=y.type),y.default!==void 0&&(b.default=y.default),y.enum&&(b.enum=y.enum),y.const!==void 0&&(b.const=y.const),y.deprecated&&(b.deprecated=!0),y.examples&&(b.examples=y.examples),y.properties&&(b.knownChildren=Object.keys(y.properties)),k&&(w!=null&&w.includes(k))&&(b.required=!0),y.items&&!Array.isArray(y.items)){const _=r(y.items),S=p(_,void 0,null);S&&(b.itemsInfo=S)}return(y.additionalProperties===!0||typeof y.additionalProperties=="object")&&(b.open=!0),b},m=y=>w=>{if(w.length===0)return p(r(y),void 0,null);const k=d(y,w.slice(0,-1));if(!k)return null;const b=w[w.length-1],_=d(k,[b]);return p(_,k.required,b)},f=y=>{const w=r(y);return Object.keys(w.properties??{})},x=y=>({at:m(y),rootKeys:()=>f(y),rootedAt:w=>{const k=d(y,w);return x(k??{})}});return x(e)}function SF(n){return Array.from(new Set(n))}let n_=null;function fy(){return n_||(n_=_F(wF)),n_}function kF(){const[n,e]=P.useState(null),[i,r]=P.useState(null),[s,a]=P.useState(null),[c,l]=P.useState(null),[d,p]=P.useState(!1),[m,f]=P.useState(null),[x,y]=P.useState(null);if(P.useEffect(()=>{let S=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([E,T,N])=>{S||(e(E),a(E),r(T),l(N))}).catch(E=>{console.warn("[telemetry] load failed:",E==null?void 0:E.message)}),()=>{S=!0}},[]),!s||!n)return o.jsx(zt,{title:"loading…"});const w=JSON.stringify(s)!==JSON.stringify(n),k=(S,E)=>{f(null),a({...s,[S]:E})},b=async()=>{p(!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),y(Date.now())}catch(S){f(S instanceof Error?S.message:String(S))}finally{p(!1)}},_=()=>{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."}),c&&o.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",o.jsx("span",{className:"font-mono",children:c})]})]}),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(iv,{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(iv,{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:b,disabled:!w||d,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:d?"saving…":"Save"}),o.jsx("button",{onClick:_,disabled:!w||d,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&&x&&!w&&o.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function CF(){const{model:n,setModel:e}=J$();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:Kj.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 EF(){const n=Ui(),e=xt(z=>z.tabs),i=xt(z=>z.activeTabId),r=e.find(z=>z.id===i)??null,s=(r==null?void 0:r.cwd)??null,a=gn(z=>z.navFace),c=P.useRef(!1),l=P.useRef(a),[d,p]=P.useState(()=>a==="project"&&s?"project":"user"),[m,f]=P.useState("effective");P.useEffect(()=>{if(l.current!==a){if(l.current=a,c.current){c.current=!1;return}p(a==="project"&&s?"project":"user")}},[a,s]),P.useEffect(()=>{a==="project"&&(m==="telemetry"||m==="app")&&f("effective")},[a,m]);const x=z=>{c.current=!0,p(z)},y=eS(Ru,n,s),w=y[d]??null,k=hn(z=>z.files),b=hn(z=>z.setDraft),_=hn(z=>z.saveJson),S=hn(z=>z.revert),[E,T]=P.useState(null),N=P.useMemo(()=>tS(iS(k,y)),[k,y]),$=(z,V,H)=>{var ie;const X=y[H??d];if(!X)return;T(null);const q=((ie=k[X])==null?void 0:ie.draftRaw)??"";let J={};if(q.trim())try{J=JSON.parse(q)}catch{J={}}const ee=Xy(J,z,V);b(X,JSON.stringify(ee,null,2)+`